Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2019 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package com.android.providers.media.util; |
| 18 | |
Jeff Sharkey | f06febd | 2020-04-07 13:03:30 -0600 | [diff] [blame] | 19 | import static android.os.ParcelFileDescriptor.MODE_APPEND; |
| 20 | import static android.os.ParcelFileDescriptor.MODE_CREATE; |
| 21 | import static android.os.ParcelFileDescriptor.MODE_READ_ONLY; |
| 22 | import static android.os.ParcelFileDescriptor.MODE_READ_WRITE; |
| 23 | import static android.os.ParcelFileDescriptor.MODE_TRUNCATE; |
| 24 | import static android.os.ParcelFileDescriptor.MODE_WRITE_ONLY; |
| 25 | import static android.system.OsConstants.F_OK; |
| 26 | import static android.system.OsConstants.O_ACCMODE; |
| 27 | import static android.system.OsConstants.O_APPEND; |
Jeff Sharkey | 9a49764 | 2020-04-23 13:15:10 -0600 | [diff] [blame] | 28 | import static android.system.OsConstants.O_CLOEXEC; |
Jeff Sharkey | f06febd | 2020-04-07 13:03:30 -0600 | [diff] [blame] | 29 | import static android.system.OsConstants.O_CREAT; |
Jeff Sharkey | 9a49764 | 2020-04-23 13:15:10 -0600 | [diff] [blame] | 30 | import static android.system.OsConstants.O_NOFOLLOW; |
Jeff Sharkey | f06febd | 2020-04-07 13:03:30 -0600 | [diff] [blame] | 31 | import static android.system.OsConstants.O_RDONLY; |
| 32 | import static android.system.OsConstants.O_RDWR; |
| 33 | import static android.system.OsConstants.O_TRUNC; |
| 34 | import static android.system.OsConstants.O_WRONLY; |
| 35 | import static android.system.OsConstants.R_OK; |
Jeff Sharkey | 9a49764 | 2020-04-23 13:15:10 -0600 | [diff] [blame] | 36 | import static android.system.OsConstants.S_IRWXG; |
| 37 | import static android.system.OsConstants.S_IRWXU; |
Jeff Sharkey | f06febd | 2020-04-07 13:03:30 -0600 | [diff] [blame] | 38 | import static android.system.OsConstants.W_OK; |
| 39 | |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 40 | import static com.android.providers.media.util.DatabaseUtils.getAsBoolean; |
| 41 | import static com.android.providers.media.util.DatabaseUtils.getAsLong; |
Jeff Sharkey | a9473e9 | 2020-04-17 15:54:30 -0600 | [diff] [blame] | 42 | import static com.android.providers.media.util.DatabaseUtils.parseBoolean; |
Jeff Sharkey | c55994b | 2019-12-20 19:43:59 -0700 | [diff] [blame] | 43 | import static com.android.providers.media.util.Logging.TAG; |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 44 | |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 45 | import android.content.ClipDescription; |
Jeff Sharkey | c55994b | 2019-12-20 19:43:59 -0700 | [diff] [blame] | 46 | import android.content.ContentValues; |
Jeff Sharkey | c5c3914 | 2019-12-15 22:46:03 -0700 | [diff] [blame] | 47 | import android.content.Context; |
| 48 | import android.net.Uri; |
| 49 | import android.os.Environment; |
Jeff Sharkey | 9a49764 | 2020-04-23 13:15:10 -0600 | [diff] [blame] | 50 | import android.os.ParcelFileDescriptor; |
Jeff Sharkey | c5c3914 | 2019-12-15 22:46:03 -0700 | [diff] [blame] | 51 | import android.os.storage.StorageManager; |
Martijn Coenen | 2bf49fa | 2020-11-02 11:46:32 +0100 | [diff] [blame] | 52 | import android.os.storage.StorageVolume; |
Jeff Sharkey | c5c3914 | 2019-12-15 22:46:03 -0700 | [diff] [blame] | 53 | import android.provider.MediaStore; |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 54 | import android.provider.MediaStore.MediaColumns; |
Jeff Sharkey | 9a49764 | 2020-04-23 13:15:10 -0600 | [diff] [blame] | 55 | import android.system.ErrnoException; |
| 56 | import android.system.Os; |
| 57 | import android.system.OsConstants; |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 58 | import android.text.TextUtils; |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 59 | import android.text.format.DateUtils; |
Zim | 7e730f3 | 2020-09-30 11:38:50 +0100 | [diff] [blame] | 60 | import android.util.ArraySet; |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 61 | import android.util.Log; |
| 62 | import android.webkit.MimeTypeMap; |
| 63 | |
| 64 | import androidx.annotation.NonNull; |
| 65 | import androidx.annotation.Nullable; |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 66 | import androidx.annotation.VisibleForTesting; |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 67 | |
| 68 | import java.io.File; |
Jeff Sharkey | 9a49764 | 2020-04-23 13:15:10 -0600 | [diff] [blame] | 69 | import java.io.FileDescriptor; |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 70 | import java.io.FileNotFoundException; |
| 71 | import java.io.IOException; |
| 72 | import java.io.InputStream; |
| 73 | import java.io.OutputStream; |
| 74 | import java.nio.charset.StandardCharsets; |
Jeff Sharkey | bb4e5e6 | 2020-02-09 17:14:08 -0700 | [diff] [blame] | 75 | import java.nio.file.FileVisitResult; |
| 76 | import java.nio.file.FileVisitor; |
| 77 | import java.nio.file.Files; |
| 78 | import java.nio.file.NoSuchFileException; |
| 79 | import java.nio.file.Path; |
Jeff Sharkey | bb4e5e6 | 2020-02-09 17:14:08 -0700 | [diff] [blame] | 80 | import java.nio.file.attribute.BasicFileAttributes; |
Jeff Sharkey | c5c3914 | 2019-12-15 22:46:03 -0700 | [diff] [blame] | 81 | import java.util.ArrayList; |
Jeff Sharkey | 5278ead | 2020-01-07 16:40:18 -0700 | [diff] [blame] | 82 | import java.util.Arrays; |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 83 | import java.util.Collection; |
Jeff Sharkey | 5278ead | 2020-01-07 16:40:18 -0700 | [diff] [blame] | 84 | import java.util.Comparator; |
Jeff Sharkey | 06b38ca | 2019-12-17 15:51:12 -0700 | [diff] [blame] | 85 | import java.util.Iterator; |
Jeff Sharkey | 470b97e | 2019-10-15 16:32:04 -0600 | [diff] [blame] | 86 | import java.util.Locale; |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 87 | import java.util.Objects; |
Jeff Sharkey | bb4e5e6 | 2020-02-09 17:14:08 -0700 | [diff] [blame] | 88 | import java.util.Optional; |
Zim | 7e730f3 | 2020-09-30 11:38:50 +0100 | [diff] [blame] | 89 | import java.util.Set; |
Jeff Sharkey | bb4e5e6 | 2020-02-09 17:14:08 -0700 | [diff] [blame] | 90 | import java.util.function.Consumer; |
Jeff Sharkey | 06b38ca | 2019-12-17 15:51:12 -0700 | [diff] [blame] | 91 | import java.util.regex.Matcher; |
| 92 | import java.util.regex.Pattern; |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 93 | |
| 94 | public class FileUtils { |
Jeff Sharkey | 9a49764 | 2020-04-23 13:15:10 -0600 | [diff] [blame] | 95 | /** |
| 96 | * Drop-in replacement for {@link ParcelFileDescriptor#open(File, int)} |
| 97 | * which adds security features like {@link OsConstants#O_CLOEXEC} and |
| 98 | * {@link OsConstants#O_NOFOLLOW}. |
| 99 | */ |
| 100 | public static @NonNull ParcelFileDescriptor openSafely(@NonNull File file, int pfdFlags) |
| 101 | throws FileNotFoundException { |
| 102 | final int posixFlags = translateModePfdToPosix(pfdFlags) | O_CLOEXEC | O_NOFOLLOW; |
| 103 | try { |
| 104 | final FileDescriptor fd = Os.open(file.getAbsolutePath(), posixFlags, |
| 105 | S_IRWXU | S_IRWXG); |
| 106 | try { |
| 107 | return ParcelFileDescriptor.dup(fd); |
| 108 | } finally { |
| 109 | closeQuietly(fd); |
| 110 | } |
| 111 | } catch (IOException | ErrnoException e) { |
| 112 | throw new FileNotFoundException(e.getMessage()); |
| 113 | } |
| 114 | } |
| 115 | |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 116 | public static void closeQuietly(@Nullable AutoCloseable closeable) { |
| 117 | android.os.FileUtils.closeQuietly(closeable); |
| 118 | } |
| 119 | |
Jeff Sharkey | 9a49764 | 2020-04-23 13:15:10 -0600 | [diff] [blame] | 120 | public static void closeQuietly(@Nullable FileDescriptor fd) { |
| 121 | if (fd == null) return; |
| 122 | try { |
| 123 | Os.close(fd); |
| 124 | } catch (ErrnoException ignored) { |
| 125 | } |
| 126 | } |
| 127 | |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 128 | public static long copy(@NonNull InputStream in, @NonNull OutputStream out) throws IOException { |
| 129 | return android.os.FileUtils.copy(in, out); |
| 130 | } |
| 131 | |
| 132 | public static File buildPath(File base, String... segments) { |
| 133 | File cur = base; |
| 134 | for (String segment : segments) { |
| 135 | if (cur == null) { |
| 136 | cur = new File(segment); |
| 137 | } else { |
| 138 | cur = new File(cur, segment); |
| 139 | } |
| 140 | } |
| 141 | return cur; |
| 142 | } |
| 143 | |
| 144 | /** |
Jeff Sharkey | 5278ead | 2020-01-07 16:40:18 -0700 | [diff] [blame] | 145 | * Delete older files in a directory until only those matching the given |
| 146 | * constraints remain. |
| 147 | * |
| 148 | * @param minCount Always keep at least this many files. |
| 149 | * @param minAgeMs Always keep files younger than this age, in milliseconds. |
| 150 | * @return if any files were deleted. |
| 151 | */ |
| 152 | public static boolean deleteOlderFiles(File dir, int minCount, long minAgeMs) { |
| 153 | if (minCount < 0 || minAgeMs < 0) { |
| 154 | throw new IllegalArgumentException("Constraints must be positive or 0"); |
| 155 | } |
| 156 | |
| 157 | final File[] files = dir.listFiles(); |
| 158 | if (files == null) return false; |
| 159 | |
| 160 | // Sort with newest files first |
| 161 | Arrays.sort(files, new Comparator<File>() { |
| 162 | @Override |
| 163 | public int compare(File lhs, File rhs) { |
| 164 | return Long.compare(rhs.lastModified(), lhs.lastModified()); |
| 165 | } |
| 166 | }); |
| 167 | |
| 168 | // Keep at least minCount files |
| 169 | boolean deleted = false; |
| 170 | for (int i = minCount; i < files.length; i++) { |
| 171 | final File file = files[i]; |
| 172 | |
| 173 | // Keep files newer than minAgeMs |
| 174 | final long age = System.currentTimeMillis() - file.lastModified(); |
| 175 | if (age > minAgeMs) { |
| 176 | if (file.delete()) { |
| 177 | Log.d(TAG, "Deleted old file " + file); |
| 178 | deleted = true; |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | return deleted; |
| 183 | } |
| 184 | |
| 185 | /** |
Jeff Sharkey | f06febd | 2020-04-07 13:03:30 -0600 | [diff] [blame] | 186 | * Shamelessly borrowed from {@code android.os.FileUtils}. |
| 187 | */ |
| 188 | public static int translateModeStringToPosix(String mode) { |
| 189 | // Sanity check for invalid chars |
| 190 | for (int i = 0; i < mode.length(); i++) { |
| 191 | switch (mode.charAt(i)) { |
| 192 | case 'r': |
| 193 | case 'w': |
| 194 | case 't': |
| 195 | case 'a': |
| 196 | break; |
| 197 | default: |
| 198 | throw new IllegalArgumentException("Bad mode: " + mode); |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | int res = 0; |
| 203 | if (mode.startsWith("rw")) { |
| 204 | res = O_RDWR | O_CREAT; |
| 205 | } else if (mode.startsWith("w")) { |
| 206 | res = O_WRONLY | O_CREAT; |
| 207 | } else if (mode.startsWith("r")) { |
| 208 | res = O_RDONLY; |
| 209 | } else { |
| 210 | throw new IllegalArgumentException("Bad mode: " + mode); |
| 211 | } |
| 212 | if (mode.indexOf('t') != -1) { |
| 213 | res |= O_TRUNC; |
| 214 | } |
| 215 | if (mode.indexOf('a') != -1) { |
| 216 | res |= O_APPEND; |
| 217 | } |
| 218 | return res; |
| 219 | } |
| 220 | |
| 221 | /** |
| 222 | * Shamelessly borrowed from {@code android.os.FileUtils}. |
| 223 | */ |
| 224 | public static String translateModePosixToString(int mode) { |
| 225 | String res = ""; |
| 226 | if ((mode & O_ACCMODE) == O_RDWR) { |
| 227 | res = "rw"; |
| 228 | } else if ((mode & O_ACCMODE) == O_WRONLY) { |
| 229 | res = "w"; |
| 230 | } else if ((mode & O_ACCMODE) == O_RDONLY) { |
| 231 | res = "r"; |
| 232 | } else { |
| 233 | throw new IllegalArgumentException("Bad mode: " + mode); |
| 234 | } |
| 235 | if ((mode & O_TRUNC) == O_TRUNC) { |
| 236 | res += "t"; |
| 237 | } |
| 238 | if ((mode & O_APPEND) == O_APPEND) { |
| 239 | res += "a"; |
| 240 | } |
| 241 | return res; |
| 242 | } |
| 243 | |
| 244 | /** |
| 245 | * Shamelessly borrowed from {@code android.os.FileUtils}. |
| 246 | */ |
| 247 | public static int translateModePosixToPfd(int mode) { |
| 248 | int res = 0; |
| 249 | if ((mode & O_ACCMODE) == O_RDWR) { |
| 250 | res = MODE_READ_WRITE; |
| 251 | } else if ((mode & O_ACCMODE) == O_WRONLY) { |
| 252 | res = MODE_WRITE_ONLY; |
| 253 | } else if ((mode & O_ACCMODE) == O_RDONLY) { |
| 254 | res = MODE_READ_ONLY; |
| 255 | } else { |
| 256 | throw new IllegalArgumentException("Bad mode: " + mode); |
| 257 | } |
| 258 | if ((mode & O_CREAT) == O_CREAT) { |
| 259 | res |= MODE_CREATE; |
| 260 | } |
| 261 | if ((mode & O_TRUNC) == O_TRUNC) { |
| 262 | res |= MODE_TRUNCATE; |
| 263 | } |
| 264 | if ((mode & O_APPEND) == O_APPEND) { |
| 265 | res |= MODE_APPEND; |
| 266 | } |
| 267 | return res; |
| 268 | } |
| 269 | |
| 270 | /** |
| 271 | * Shamelessly borrowed from {@code android.os.FileUtils}. |
| 272 | */ |
| 273 | public static int translateModePfdToPosix(int mode) { |
| 274 | int res = 0; |
| 275 | if ((mode & MODE_READ_WRITE) == MODE_READ_WRITE) { |
| 276 | res = O_RDWR; |
| 277 | } else if ((mode & MODE_WRITE_ONLY) == MODE_WRITE_ONLY) { |
| 278 | res = O_WRONLY; |
| 279 | } else if ((mode & MODE_READ_ONLY) == MODE_READ_ONLY) { |
| 280 | res = O_RDONLY; |
| 281 | } else { |
| 282 | throw new IllegalArgumentException("Bad mode: " + mode); |
| 283 | } |
| 284 | if ((mode & MODE_CREATE) == MODE_CREATE) { |
| 285 | res |= O_CREAT; |
| 286 | } |
| 287 | if ((mode & MODE_TRUNCATE) == MODE_TRUNCATE) { |
| 288 | res |= O_TRUNC; |
| 289 | } |
| 290 | if ((mode & MODE_APPEND) == MODE_APPEND) { |
| 291 | res |= O_APPEND; |
| 292 | } |
| 293 | return res; |
| 294 | } |
| 295 | |
| 296 | /** |
| 297 | * Shamelessly borrowed from {@code android.os.FileUtils}. |
| 298 | */ |
| 299 | public static int translateModeAccessToPosix(int mode) { |
| 300 | if (mode == F_OK) { |
| 301 | // There's not an exact mapping, so we attempt a read-only open to |
| 302 | // determine if a file exists |
| 303 | return O_RDONLY; |
| 304 | } else if ((mode & (R_OK | W_OK)) == (R_OK | W_OK)) { |
| 305 | return O_RDWR; |
| 306 | } else if ((mode & R_OK) == R_OK) { |
| 307 | return O_RDONLY; |
| 308 | } else if ((mode & W_OK) == W_OK) { |
| 309 | return O_WRONLY; |
| 310 | } else { |
| 311 | throw new IllegalArgumentException("Bad mode: " + mode); |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | /** |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 316 | * Test if a file lives under the given directory, either as a direct child |
| 317 | * or a distant grandchild. |
| 318 | * <p> |
| 319 | * Both files <em>must</em> have been resolved using |
| 320 | * {@link File#getCanonicalFile()} to avoid symlink or path traversal |
| 321 | * attacks. |
| 322 | * |
| 323 | * @hide |
| 324 | */ |
| 325 | public static boolean contains(File[] dirs, File file) { |
| 326 | for (File dir : dirs) { |
| 327 | if (contains(dir, file)) { |
| 328 | return true; |
| 329 | } |
| 330 | } |
| 331 | return false; |
| 332 | } |
| 333 | |
| 334 | /** {@hide} */ |
| 335 | public static boolean contains(Collection<File> dirs, File file) { |
| 336 | for (File dir : dirs) { |
| 337 | if (contains(dir, file)) { |
| 338 | return true; |
| 339 | } |
| 340 | } |
| 341 | return false; |
| 342 | } |
| 343 | |
| 344 | /** |
| 345 | * Test if a file lives under the given directory, either as a direct child |
| 346 | * or a distant grandchild. |
| 347 | * <p> |
| 348 | * Both files <em>must</em> have been resolved using |
| 349 | * {@link File#getCanonicalFile()} to avoid symlink or path traversal |
| 350 | * attacks. |
| 351 | * |
| 352 | * @hide |
| 353 | */ |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 354 | public static boolean contains(File dir, File file) { |
| 355 | if (dir == null || file == null) return false; |
| 356 | return contains(dir.getAbsolutePath(), file.getAbsolutePath()); |
| 357 | } |
| 358 | |
| 359 | /** |
| 360 | * Test if a file lives under the given directory, either as a direct child |
| 361 | * or a distant grandchild. |
| 362 | * <p> |
| 363 | * Both files <em>must</em> have been resolved using |
| 364 | * {@link File#getCanonicalFile()} to avoid symlink or path traversal |
| 365 | * attacks. |
| 366 | * |
| 367 | * @hide |
| 368 | */ |
| 369 | public static boolean contains(String dirPath, String filePath) { |
| 370 | if (dirPath.equals(filePath)) { |
| 371 | return true; |
| 372 | } |
| 373 | if (!dirPath.endsWith("/")) { |
| 374 | dirPath += "/"; |
| 375 | } |
| 376 | return filePath.startsWith(dirPath); |
| 377 | } |
| 378 | |
Jeff Sharkey | bb4e5e6 | 2020-02-09 17:14:08 -0700 | [diff] [blame] | 379 | /** |
| 380 | * Write {@link String} to the given {@link File}. Deletes any existing file |
| 381 | * when the argument is {@link Optional#empty()}. |
| 382 | */ |
| 383 | public static void writeString(@NonNull File file, @NonNull Optional<String> value) |
| 384 | throws IOException { |
| 385 | if (value.isPresent()) { |
| 386 | Files.write(file.toPath(), value.get().getBytes(StandardCharsets.UTF_8)); |
| 387 | } else { |
| 388 | file.delete(); |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 389 | } |
Jeff Sharkey | bb4e5e6 | 2020-02-09 17:14:08 -0700 | [diff] [blame] | 390 | } |
| 391 | |
| 392 | /** |
| 393 | * Read given {@link File} as a single {@link String}. Returns |
| 394 | * {@link Optional#empty()} when the file doesn't exist. |
| 395 | */ |
| 396 | public static @NonNull Optional<String> readString(@NonNull File file) throws IOException { |
| 397 | try { |
| 398 | final String value = new String(Files.readAllBytes(file.toPath()), |
| 399 | StandardCharsets.UTF_8); |
| 400 | return Optional.of(value); |
| 401 | } catch (NoSuchFileException e) { |
| 402 | return Optional.empty(); |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | /** |
| 407 | * Recursively walk the contents of the given {@link Path}, invoking the |
| 408 | * given {@link Consumer} for every file and directory encountered. This is |
| 409 | * typically used for recursively deleting a directory tree. |
| 410 | * <p> |
| 411 | * Gracefully attempts to process as much as possible in the face of any |
| 412 | * failures. |
| 413 | */ |
| 414 | public static void walkFileTreeContents(@NonNull Path path, @NonNull Consumer<Path> operation) { |
| 415 | try { |
| 416 | Files.walkFileTree(path, new FileVisitor<Path>() { |
| 417 | @Override |
| 418 | public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { |
| 419 | return FileVisitResult.CONTINUE; |
| 420 | } |
| 421 | |
| 422 | @Override |
| 423 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { |
| 424 | if (!Objects.equals(path, file)) { |
| 425 | operation.accept(file); |
| 426 | } |
| 427 | return FileVisitResult.CONTINUE; |
| 428 | } |
| 429 | |
| 430 | @Override |
| 431 | public FileVisitResult visitFileFailed(Path file, IOException e) { |
| 432 | Log.w(TAG, "Failed to visit " + file, e); |
| 433 | return FileVisitResult.CONTINUE; |
| 434 | } |
| 435 | |
| 436 | @Override |
| 437 | public FileVisitResult postVisitDirectory(Path dir, IOException e) { |
| 438 | if (!Objects.equals(path, dir)) { |
| 439 | operation.accept(dir); |
| 440 | } |
| 441 | return FileVisitResult.CONTINUE; |
| 442 | } |
| 443 | }); |
| 444 | } catch (IOException e) { |
| 445 | Log.w(TAG, "Failed to walk " + path, e); |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | /** |
| 450 | * Recursively delete all contents inside the given directory. Gracefully |
| 451 | * attempts to delete as much as possible in the face of any failures. |
| 452 | * |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 453 | * @deprecated if you're calling this from inside {@code MediaProvider}, you |
Jeff Sharkey | bb4e5e6 | 2020-02-09 17:14:08 -0700 | [diff] [blame] | 454 | * likely want to call {@link #forEach} with a separate |
| 455 | * invocation to invalidate FUSE entries. |
| 456 | */ |
| 457 | @Deprecated |
| 458 | public static void deleteContents(@NonNull File dir) { |
| 459 | walkFileTreeContents(dir.toPath(), (path) -> { |
| 460 | path.toFile().delete(); |
| 461 | }); |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 462 | } |
| 463 | |
| 464 | private static boolean isValidFatFilenameChar(char c) { |
| 465 | if ((0x00 <= c && c <= 0x1f)) { |
| 466 | return false; |
| 467 | } |
| 468 | switch (c) { |
| 469 | case '"': |
| 470 | case '*': |
| 471 | case '/': |
| 472 | case ':': |
| 473 | case '<': |
| 474 | case '>': |
| 475 | case '?': |
| 476 | case '\\': |
| 477 | case '|': |
| 478 | case 0x7F: |
| 479 | return false; |
| 480 | default: |
| 481 | return true; |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | /** |
| 486 | * Check if given filename is valid for a FAT filesystem. |
| 487 | * |
| 488 | * @hide |
| 489 | */ |
| 490 | public static boolean isValidFatFilename(String name) { |
| 491 | return (name != null) && name.equals(buildValidFatFilename(name)); |
| 492 | } |
| 493 | |
| 494 | /** |
| 495 | * Mutate the given filename to make it valid for a FAT filesystem, |
| 496 | * replacing any invalid characters with "_". |
| 497 | * |
| 498 | * @hide |
| 499 | */ |
| 500 | public static String buildValidFatFilename(String name) { |
| 501 | if (TextUtils.isEmpty(name) || ".".equals(name) || "..".equals(name)) { |
| 502 | return "(invalid)"; |
| 503 | } |
| 504 | final StringBuilder res = new StringBuilder(name.length()); |
| 505 | for (int i = 0; i < name.length(); i++) { |
| 506 | final char c = name.charAt(i); |
| 507 | if (isValidFatFilenameChar(c)) { |
| 508 | res.append(c); |
| 509 | } else { |
| 510 | res.append('_'); |
| 511 | } |
| 512 | } |
| 513 | // Even though vfat allows 255 UCS-2 chars, we might eventually write to |
| 514 | // ext4 through a FUSE layer, so use that limit. |
| 515 | trimFilename(res, 255); |
| 516 | return res.toString(); |
| 517 | } |
| 518 | |
| 519 | /** {@hide} */ |
| 520 | // @VisibleForTesting |
| 521 | public static String trimFilename(String str, int maxBytes) { |
| 522 | final StringBuilder res = new StringBuilder(str); |
| 523 | trimFilename(res, maxBytes); |
| 524 | return res.toString(); |
| 525 | } |
| 526 | |
| 527 | /** {@hide} */ |
| 528 | private static void trimFilename(StringBuilder res, int maxBytes) { |
| 529 | byte[] raw = res.toString().getBytes(StandardCharsets.UTF_8); |
| 530 | if (raw.length > maxBytes) { |
| 531 | maxBytes -= 3; |
| 532 | while (raw.length > maxBytes) { |
| 533 | res.deleteCharAt(res.length() / 2); |
| 534 | raw = res.toString().getBytes(StandardCharsets.UTF_8); |
| 535 | } |
| 536 | res.insert(res.length() / 2, "..."); |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | /** {@hide} */ |
| 541 | private static File buildUniqueFileWithExtension(File parent, String name, String ext) |
| 542 | throws FileNotFoundException { |
Jeff Sharkey | 06b38ca | 2019-12-17 15:51:12 -0700 | [diff] [blame] | 543 | final Iterator<String> names = buildUniqueNameIterator(parent, name); |
| 544 | while (names.hasNext()) { |
| 545 | File file = buildFile(parent, names.next(), ext); |
| 546 | if (!file.exists()) { |
| 547 | return file; |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 548 | } |
Jeff Sharkey | 06b38ca | 2019-12-17 15:51:12 -0700 | [diff] [blame] | 549 | } |
| 550 | throw new FileNotFoundException("Failed to create unique file"); |
| 551 | } |
| 552 | |
| 553 | private static final Pattern PATTERN_DCF_STRICT = Pattern |
| 554 | .compile("([A-Z0-9_]{4})([0-9]{4})"); |
| 555 | private static final Pattern PATTERN_DCF_RELAXED = Pattern |
| 556 | .compile("((?:IMG|MVIMG|VID)_[0-9]{8}_[0-9]{6})(?:~([0-9]+))?"); |
| 557 | |
| 558 | private static boolean isDcim(@NonNull File dir) { |
| 559 | while (dir != null) { |
| 560 | if (Objects.equals("DCIM", dir.getName())) { |
| 561 | return true; |
| 562 | } |
| 563 | dir = dir.getParentFile(); |
| 564 | } |
| 565 | return false; |
| 566 | } |
| 567 | |
| 568 | private static @NonNull Iterator<String> buildUniqueNameIterator(@NonNull File parent, |
| 569 | @NonNull String name) { |
| 570 | if (isDcim(parent)) { |
| 571 | final Matcher dcfStrict = PATTERN_DCF_STRICT.matcher(name); |
| 572 | if (dcfStrict.matches()) { |
| 573 | // Generate names like "IMG_1001" |
| 574 | final String prefix = dcfStrict.group(1); |
| 575 | return new Iterator<String>() { |
| 576 | int i = Integer.parseInt(dcfStrict.group(2)); |
| 577 | @Override |
| 578 | public String next() { |
Corina | 54fb8ba | 2020-11-27 13:38:09 +0000 | [diff] [blame] | 579 | final String res = String.format(Locale.US, "%s%04d", prefix, i); |
Jeff Sharkey | 06b38ca | 2019-12-17 15:51:12 -0700 | [diff] [blame] | 580 | i++; |
| 581 | return res; |
| 582 | } |
| 583 | @Override |
| 584 | public boolean hasNext() { |
| 585 | return i <= 9999; |
| 586 | } |
| 587 | }; |
| 588 | } |
| 589 | |
| 590 | final Matcher dcfRelaxed = PATTERN_DCF_RELAXED.matcher(name); |
| 591 | if (dcfRelaxed.matches()) { |
| 592 | // Generate names like "IMG_20190102_030405~2" |
| 593 | final String prefix = dcfRelaxed.group(1); |
| 594 | return new Iterator<String>() { |
Corina | 54fb8ba | 2020-11-27 13:38:09 +0000 | [diff] [blame] | 595 | int i = TextUtils.isEmpty(dcfRelaxed.group(2)) |
| 596 | ? 1 |
Jeff Sharkey | 06b38ca | 2019-12-17 15:51:12 -0700 | [diff] [blame] | 597 | : Integer.parseInt(dcfRelaxed.group(2)); |
| 598 | @Override |
| 599 | public String next() { |
Corina | 54fb8ba | 2020-11-27 13:38:09 +0000 | [diff] [blame] | 600 | final String res = (i == 1) |
| 601 | ? prefix |
| 602 | : String.format(Locale.US, "%s~%d", prefix, i); |
Jeff Sharkey | 06b38ca | 2019-12-17 15:51:12 -0700 | [diff] [blame] | 603 | i++; |
| 604 | return res; |
| 605 | } |
| 606 | @Override |
| 607 | public boolean hasNext() { |
| 608 | return i <= 99; |
| 609 | } |
| 610 | }; |
| 611 | } |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 612 | } |
| 613 | |
Jeff Sharkey | 06b38ca | 2019-12-17 15:51:12 -0700 | [diff] [blame] | 614 | // Generate names like "foo (2)" |
| 615 | return new Iterator<String>() { |
| 616 | int i = 0; |
| 617 | @Override |
| 618 | public String next() { |
| 619 | final String res = (i == 0) ? name : name + " (" + i + ")"; |
| 620 | i++; |
| 621 | return res; |
| 622 | } |
| 623 | @Override |
| 624 | public boolean hasNext() { |
| 625 | return i < 32; |
| 626 | } |
| 627 | }; |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 628 | } |
| 629 | |
| 630 | /** |
| 631 | * Generates a unique file name under the given parent directory. If the display name doesn't |
| 632 | * have an extension that matches the requested MIME type, the default extension for that MIME |
| 633 | * type is appended. If a file already exists, the name is appended with a numerical value to |
| 634 | * make it unique. |
| 635 | * |
| 636 | * For example, the display name 'example' with 'text/plain' MIME might produce |
| 637 | * 'example.txt' or 'example (1).txt', etc. |
| 638 | * |
| 639 | * @throws FileNotFoundException |
| 640 | * @hide |
| 641 | */ |
| 642 | public static File buildUniqueFile(File parent, String mimeType, String displayName) |
| 643 | throws FileNotFoundException { |
| 644 | final String[] parts = splitFileName(mimeType, displayName); |
| 645 | return buildUniqueFileWithExtension(parent, parts[0], parts[1]); |
| 646 | } |
| 647 | |
| 648 | /** {@hide} */ |
| 649 | public static File buildNonUniqueFile(File parent, String mimeType, String displayName) { |
| 650 | final String[] parts = splitFileName(mimeType, displayName); |
| 651 | return buildFile(parent, parts[0], parts[1]); |
| 652 | } |
| 653 | |
| 654 | /** |
| 655 | * Generates a unique file name under the given parent directory, keeping |
| 656 | * any extension intact. |
| 657 | * |
| 658 | * @hide |
| 659 | */ |
| 660 | public static File buildUniqueFile(File parent, String displayName) |
| 661 | throws FileNotFoundException { |
| 662 | final String name; |
| 663 | final String ext; |
| 664 | |
| 665 | // Extract requested extension from display name |
| 666 | final int lastDot = displayName.lastIndexOf('.'); |
| 667 | if (lastDot >= 0) { |
| 668 | name = displayName.substring(0, lastDot); |
| 669 | ext = displayName.substring(lastDot + 1); |
| 670 | } else { |
| 671 | name = displayName; |
| 672 | ext = null; |
| 673 | } |
| 674 | |
| 675 | return buildUniqueFileWithExtension(parent, name, ext); |
| 676 | } |
| 677 | |
| 678 | /** |
| 679 | * Splits file name into base name and extension. |
| 680 | * If the display name doesn't have an extension that matches the requested MIME type, the |
| 681 | * extension is regarded as a part of filename and default extension for that MIME type is |
| 682 | * appended. |
| 683 | * |
| 684 | * @hide |
| 685 | */ |
| 686 | public static String[] splitFileName(String mimeType, String displayName) { |
| 687 | String name; |
| 688 | String ext; |
| 689 | |
| 690 | { |
| 691 | String mimeTypeFromExt; |
| 692 | |
| 693 | // Extract requested extension from display name |
| 694 | final int lastDot = displayName.lastIndexOf('.'); |
Sahana Rao | f3c8a16 | 2020-05-15 21:58:36 +0100 | [diff] [blame] | 695 | if (lastDot > 0) { |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 696 | name = displayName.substring(0, lastDot); |
| 697 | ext = displayName.substring(lastDot + 1); |
| 698 | mimeTypeFromExt = MimeTypeMap.getSingleton().getMimeTypeFromExtension( |
Jeff Sharkey | 470b97e | 2019-10-15 16:32:04 -0600 | [diff] [blame] | 699 | ext.toLowerCase(Locale.ROOT)); |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 700 | } else { |
| 701 | name = displayName; |
| 702 | ext = null; |
| 703 | mimeTypeFromExt = null; |
| 704 | } |
| 705 | |
| 706 | if (mimeTypeFromExt == null) { |
| 707 | mimeTypeFromExt = ClipDescription.MIMETYPE_UNKNOWN; |
| 708 | } |
| 709 | |
| 710 | final String extFromMimeType; |
Jeff Sharkey | c4a5f81 | 2020-05-03 21:07:14 -0600 | [diff] [blame] | 711 | if (ClipDescription.MIMETYPE_UNKNOWN.equalsIgnoreCase(mimeType)) { |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 712 | extFromMimeType = null; |
| 713 | } else { |
| 714 | extFromMimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); |
| 715 | } |
| 716 | |
Jeff Sharkey | c4a5f81 | 2020-05-03 21:07:14 -0600 | [diff] [blame] | 717 | if (MimeUtils.equalIgnoreCase(mimeType, mimeTypeFromExt) |
| 718 | || MimeUtils.equalIgnoreCase(ext, extFromMimeType)) { |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 719 | // Extension maps back to requested MIME type; allow it |
| 720 | } else { |
| 721 | // No match; insist that create file matches requested MIME |
| 722 | name = displayName; |
| 723 | ext = extFromMimeType; |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | if (ext == null) { |
| 728 | ext = ""; |
| 729 | } |
| 730 | |
| 731 | return new String[] { name, ext }; |
| 732 | } |
| 733 | |
| 734 | /** {@hide} */ |
| 735 | private static File buildFile(File parent, String name, String ext) { |
| 736 | if (TextUtils.isEmpty(ext)) { |
| 737 | return new File(parent, name); |
| 738 | } else { |
| 739 | return new File(parent, name + "." + ext); |
| 740 | } |
| 741 | } |
Jeff Sharkey | e152d576 | 2019-10-11 17:14:51 -0600 | [diff] [blame] | 742 | |
| 743 | public static @Nullable String extractDisplayName(@Nullable String data) { |
| 744 | if (data == null) return null; |
Jeff Sharkey | e76c426 | 2019-12-06 14:46:00 -0700 | [diff] [blame] | 745 | if (data.indexOf('/') == -1) { |
| 746 | return data; |
| 747 | } |
Jeff Sharkey | e152d576 | 2019-10-11 17:14:51 -0600 | [diff] [blame] | 748 | if (data.endsWith("/")) { |
| 749 | data = data.substring(0, data.length() - 1); |
| 750 | } |
| 751 | return data.substring(data.lastIndexOf('/') + 1); |
| 752 | } |
| 753 | |
| 754 | public static @Nullable String extractFileName(@Nullable String data) { |
| 755 | if (data == null) return null; |
| 756 | data = extractDisplayName(data); |
| 757 | |
| 758 | final int lastDot = data.lastIndexOf('.'); |
| 759 | if (lastDot == -1) { |
| 760 | return data; |
| 761 | } else { |
| 762 | return data.substring(0, lastDot); |
| 763 | } |
| 764 | } |
| 765 | |
| 766 | public static @Nullable String extractFileExtension(@Nullable String data) { |
| 767 | if (data == null) return null; |
| 768 | data = extractDisplayName(data); |
| 769 | |
| 770 | final int lastDot = data.lastIndexOf('.'); |
| 771 | if (lastDot == -1) { |
| 772 | return null; |
| 773 | } else { |
| 774 | return data.substring(lastDot + 1); |
| 775 | } |
| 776 | } |
Jeff Sharkey | c5c3914 | 2019-12-15 22:46:03 -0700 | [diff] [blame] | 777 | |
| 778 | /** |
Jeff Sharkey | c55994b | 2019-12-20 19:43:59 -0700 | [diff] [blame] | 779 | * Return list of paths that should be scanned with |
| 780 | * {@link com.android.providers.media.scan.MediaScanner} for the given |
| 781 | * volume name. |
Jeff Sharkey | c5c3914 | 2019-12-15 22:46:03 -0700 | [diff] [blame] | 782 | */ |
| 783 | public static @NonNull Collection<File> getVolumeScanPaths(@NonNull Context context, |
| 784 | @NonNull String volumeName) throws FileNotFoundException { |
| 785 | final ArrayList<File> res = new ArrayList<>(); |
| 786 | switch (volumeName) { |
| 787 | case MediaStore.VOLUME_INTERNAL: { |
| 788 | res.addAll(Environment.getInternalMediaDirectories()); |
| 789 | break; |
| 790 | } |
| 791 | case MediaStore.VOLUME_EXTERNAL: { |
| 792 | for (String resolvedVolumeName : MediaStore.getExternalVolumeNames(context)) { |
| 793 | res.add(getVolumePath(context, resolvedVolumeName)); |
| 794 | } |
| 795 | break; |
| 796 | } |
| 797 | default: { |
| 798 | res.add(getVolumePath(context, volumeName)); |
| 799 | } |
| 800 | } |
| 801 | return res; |
| 802 | } |
| 803 | |
| 804 | /** |
| 805 | * Return path where the given volume name is mounted. |
| 806 | */ |
| 807 | public static @NonNull File getVolumePath(@NonNull Context context, |
| 808 | @NonNull String volumeName) throws FileNotFoundException { |
| 809 | switch (volumeName) { |
| 810 | case MediaStore.VOLUME_INTERNAL: |
| 811 | case MediaStore.VOLUME_EXTERNAL: |
| 812 | throw new FileNotFoundException(volumeName + " has no associated path"); |
| 813 | } |
| 814 | |
| 815 | final Uri uri = MediaStore.Files.getContentUri(volumeName); |
Zim | fb3b106 | 2020-09-10 10:29:47 +0100 | [diff] [blame] | 816 | File path = null; |
| 817 | |
| 818 | try { |
| 819 | path = context.getSystemService(StorageManager.class).getStorageVolume(uri) |
| 820 | .getDirectory(); |
| 821 | } catch (IllegalStateException e) { |
| 822 | Log.w("Ignoring volume not found exception", e); |
| 823 | } |
| 824 | |
Jeff Sharkey | f95b06f | 2020-06-02 11:10:35 -0600 | [diff] [blame] | 825 | if (path != null) { |
| 826 | return path; |
| 827 | } else { |
| 828 | throw new FileNotFoundException(volumeName + " has no associated path"); |
| 829 | } |
Jeff Sharkey | c5c3914 | 2019-12-15 22:46:03 -0700 | [diff] [blame] | 830 | } |
| 831 | |
| 832 | /** |
shafik | 536982a | 2020-05-14 17:54:05 +0100 | [diff] [blame] | 833 | * Returns the content URI for the volume that contains the given path. |
| 834 | * |
| 835 | * <p>{@link MediaStore.Files#getContentUriForPath(String)} can't detect public volumes and can |
| 836 | * only return the URI for the primary external storage, that's why this utility should be used |
| 837 | * instead. |
| 838 | */ |
| 839 | public static @NonNull Uri getContentUriForPath(@NonNull String path) { |
| 840 | Objects.requireNonNull(path); |
| 841 | return MediaStore.Files.getContentUri(extractVolumeName(path)); |
| 842 | } |
| 843 | |
| 844 | /** |
Jeff Sharkey | c5c3914 | 2019-12-15 22:46:03 -0700 | [diff] [blame] | 845 | * Return volume name which hosts the given path. |
| 846 | */ |
Martijn Coenen | 2bf49fa | 2020-11-02 11:46:32 +0100 | [diff] [blame] | 847 | public static @NonNull String getVolumeName(@NonNull Context context, @NonNull File path) |
| 848 | throws FileNotFoundException { |
Jeff Sharkey | c5c3914 | 2019-12-15 22:46:03 -0700 | [diff] [blame] | 849 | if (contains(Environment.getStorageDirectory(), path)) { |
Martijn Coenen | 2bf49fa | 2020-11-02 11:46:32 +0100 | [diff] [blame] | 850 | StorageVolume volume = context.getSystemService(StorageManager.class) |
| 851 | .getStorageVolume(path); |
| 852 | if (volume == null) { |
| 853 | throw new FileNotFoundException("Can't find volume for " + path.getPath()); |
| 854 | } |
| 855 | return volume.getMediaStoreVolumeName(); |
Jeff Sharkey | c5c3914 | 2019-12-15 22:46:03 -0700 | [diff] [blame] | 856 | } else { |
| 857 | return MediaStore.VOLUME_INTERNAL; |
| 858 | } |
| 859 | } |
Jeff Sharkey | 5ea5c28 | 2019-12-18 14:06:28 -0700 | [diff] [blame] | 860 | |
| 861 | public static final Pattern PATTERN_DOWNLOADS_FILE = Pattern.compile( |
Zim | 78ffeeb | 2020-09-22 20:15:25 +0100 | [diff] [blame] | 862 | "(?i)^/storage/[^/]+/(?:[0-9]+/)?Download/.+"); |
Jeff Sharkey | 5ea5c28 | 2019-12-18 14:06:28 -0700 | [diff] [blame] | 863 | public static final Pattern PATTERN_DOWNLOADS_DIRECTORY = Pattern.compile( |
Zim | 78ffeeb | 2020-09-22 20:15:25 +0100 | [diff] [blame] | 864 | "(?i)^/storage/[^/]+/(?:[0-9]+/)?Download/?"); |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 865 | public static final Pattern PATTERN_EXPIRES_FILE = Pattern.compile( |
Sahana Rao | ea587fc | 2020-06-03 15:56:23 +0100 | [diff] [blame] | 866 | "(?i)^\\.(pending|trashed)-(\\d+)-([^/]+)$"); |
| 867 | public static final Pattern PATTERN_PENDING_FILEPATH_FOR_SQL = Pattern.compile( |
| 868 | ".*/\\.pending-(\\d+)-([^/]+)$"); |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 869 | |
| 870 | /** |
| 871 | * File prefix indicating that the file {@link MediaColumns#IS_PENDING}. |
| 872 | */ |
| 873 | public static final String PREFIX_PENDING = "pending"; |
| 874 | |
| 875 | /** |
| 876 | * File prefix indicating that the file {@link MediaColumns#IS_TRASHED}. |
| 877 | */ |
| 878 | public static final String PREFIX_TRASHED = "trashed"; |
| 879 | |
| 880 | /** |
| 881 | * Default duration that {@link MediaColumns#IS_PENDING} items should be |
| 882 | * preserved for until automatically cleaned by {@link #runIdleMaintenance}. |
| 883 | */ |
Jeff Sharkey | 05c3a03 | 2020-04-09 16:57:04 -0600 | [diff] [blame] | 884 | public static final long DEFAULT_DURATION_PENDING = 7 * DateUtils.DAY_IN_MILLIS; |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 885 | |
| 886 | /** |
| 887 | * Default duration that {@link MediaColumns#IS_TRASHED} items should be |
| 888 | * preserved for until automatically cleaned by {@link #runIdleMaintenance}. |
| 889 | */ |
Jeff Sharkey | 05c3a03 | 2020-04-09 16:57:04 -0600 | [diff] [blame] | 890 | public static final long DEFAULT_DURATION_TRASHED = 30 * DateUtils.DAY_IN_MILLIS; |
Jeff Sharkey | 5ea5c28 | 2019-12-18 14:06:28 -0700 | [diff] [blame] | 891 | |
| 892 | public static boolean isDownload(@NonNull String path) { |
| 893 | return PATTERN_DOWNLOADS_FILE.matcher(path).matches(); |
| 894 | } |
| 895 | |
| 896 | public static boolean isDownloadDir(@NonNull String path) { |
| 897 | return PATTERN_DOWNLOADS_DIRECTORY.matcher(path).matches(); |
| 898 | } |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 899 | |
| 900 | /** |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 901 | * Regex that matches paths in all well-known package-specific directories, |
| 902 | * and which captures the package name as the first group. |
| 903 | */ |
| 904 | public static final Pattern PATTERN_OWNED_PATH = Pattern.compile( |
Zim | 78ffeeb | 2020-09-22 20:15:25 +0100 | [diff] [blame] | 905 | "(?i)^/storage/[^/]+/(?:[0-9]+/)?Android/(?:data|media|obb)/([^/]+)(/?.*)?"); |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 906 | |
| 907 | /** |
Ricky Wai | feb9d9b | 2020-04-06 19:14:46 +0100 | [diff] [blame] | 908 | * Regex that matches Android/obb or Android/data path. |
| 909 | */ |
| 910 | public static final Pattern PATTERN_DATA_OR_OBB_PATH = Pattern.compile( |
| 911 | "(?i)^/storage/[^/]+/(?:[0-9]+/)?Android/(?:data|obb)/?$"); |
| 912 | |
Sahana Rao | e44080f | 2020-09-25 11:13:55 +0100 | [diff] [blame] | 913 | @VisibleForTesting |
| 914 | public static final String[] DEFAULT_FOLDER_NAMES = { |
| 915 | Environment.DIRECTORY_MUSIC, |
| 916 | Environment.DIRECTORY_PODCASTS, |
| 917 | Environment.DIRECTORY_RINGTONES, |
| 918 | Environment.DIRECTORY_ALARMS, |
| 919 | Environment.DIRECTORY_NOTIFICATIONS, |
| 920 | Environment.DIRECTORY_PICTURES, |
| 921 | Environment.DIRECTORY_MOVIES, |
| 922 | Environment.DIRECTORY_DOWNLOADS, |
| 923 | Environment.DIRECTORY_DCIM, |
| 924 | Environment.DIRECTORY_DOCUMENTS, |
| 925 | Environment.DIRECTORY_AUDIOBOOKS, |
| 926 | }; |
| 927 | |
Ricky Wai | feb9d9b | 2020-04-06 19:14:46 +0100 | [diff] [blame] | 928 | /** |
Zim | 78ffeeb | 2020-09-22 20:15:25 +0100 | [diff] [blame] | 929 | * Regex that matches paths for {@link MediaColumns#RELATIVE_PATH} |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 930 | */ |
| 931 | private static final Pattern PATTERN_RELATIVE_PATH = Pattern.compile( |
Zim | 78ffeeb | 2020-09-22 20:15:25 +0100 | [diff] [blame] | 932 | "(?i)^/storage/(?:emulated/[0-9]+/|[^/]+/)"); |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 933 | |
| 934 | /** |
| 935 | * Regex that matches paths under well-known storage paths. |
| 936 | */ |
| 937 | private static final Pattern PATTERN_VOLUME_NAME = Pattern.compile( |
| 938 | "(?i)^/storage/([^/]+)"); |
| 939 | |
Sahana Rao | e44080f | 2020-09-25 11:13:55 +0100 | [diff] [blame] | 940 | private static final String CAMERA_RELATIVE_PATH = |
| 941 | String.format("%s/%s/", Environment.DIRECTORY_DCIM, "Camera"); |
| 942 | |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 943 | private static @Nullable String normalizeUuid(@Nullable String fsUuid) { |
Jeff Sharkey | c4a5f81 | 2020-05-03 21:07:14 -0600 | [diff] [blame] | 944 | return fsUuid != null ? fsUuid.toLowerCase(Locale.ROOT) : null; |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 945 | } |
| 946 | |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 947 | public static @Nullable String extractVolumePath(@Nullable String data) { |
| 948 | if (data == null) return null; |
| 949 | final Matcher matcher = PATTERN_RELATIVE_PATH.matcher(data); |
| 950 | if (matcher.find()) { |
| 951 | return data.substring(0, matcher.end()); |
| 952 | } else { |
| 953 | return null; |
| 954 | } |
| 955 | } |
| 956 | |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 957 | public static @Nullable String extractVolumeName(@Nullable String data) { |
| 958 | if (data == null) return null; |
| 959 | final Matcher matcher = PATTERN_VOLUME_NAME.matcher(data); |
| 960 | if (matcher.find()) { |
| 961 | final String volumeName = matcher.group(1); |
| 962 | if (volumeName.equals("emulated")) { |
| 963 | return MediaStore.VOLUME_EXTERNAL_PRIMARY; |
| 964 | } else { |
| 965 | return normalizeUuid(volumeName); |
| 966 | } |
| 967 | } else { |
| 968 | return MediaStore.VOLUME_INTERNAL; |
| 969 | } |
| 970 | } |
| 971 | |
| 972 | public static @Nullable String extractRelativePath(@Nullable String data) { |
| 973 | if (data == null) return null; |
| 974 | final Matcher matcher = PATTERN_RELATIVE_PATH.matcher(data); |
| 975 | if (matcher.find()) { |
| 976 | final int lastSlash = data.lastIndexOf('/'); |
| 977 | if (lastSlash == -1 || lastSlash < matcher.end()) { |
| 978 | // This is a file in the top-level directory, so relative path is "/" |
| 979 | // which is different than null, which means unknown path |
| 980 | return "/"; |
| 981 | } else { |
| 982 | return data.substring(matcher.end(), lastSlash + 1); |
| 983 | } |
| 984 | } else { |
| 985 | return null; |
| 986 | } |
| 987 | } |
| 988 | |
| 989 | /** |
| 990 | * Returns relative path for the directory. |
| 991 | */ |
| 992 | @VisibleForTesting |
| 993 | public static @Nullable String extractRelativePathForDirectory(@Nullable String directoryPath) { |
| 994 | if (directoryPath == null) return null; |
Sahana Rao | 54dafa3 | 2020-06-22 08:42:37 +0100 | [diff] [blame] | 995 | |
| 996 | if (directoryPath.equals("/storage/emulated") || |
| 997 | directoryPath.equals("/storage/emulated/")) { |
| 998 | // This path is not reachable for MediaProvider. |
| 999 | return null; |
| 1000 | } |
| 1001 | |
| 1002 | // We are extracting relative path for the directory itself, we add "/" so that we can use |
| 1003 | // same PATTERN_RELATIVE_PATH to match relative path for directory. For example, relative |
| 1004 | // path of '/storage/<volume_name>' is null where as relative path for directory is "/", for |
| 1005 | // PATTERN_RELATIVE_PATH to match '/storage/<volume_name>', it should end with "/". |
| 1006 | if (!directoryPath.endsWith("/")) { |
| 1007 | // Relative path for directory should end with "/". |
| 1008 | directoryPath += "/"; |
| 1009 | } |
| 1010 | |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 1011 | final Matcher matcher = PATTERN_RELATIVE_PATH.matcher(directoryPath); |
| 1012 | if (matcher.find()) { |
Sahana Rao | 54dafa3 | 2020-06-22 08:42:37 +0100 | [diff] [blame] | 1013 | if (matcher.end() == directoryPath.length()) { |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 1014 | // This is the top-level directory, so relative path is "/" |
| 1015 | return "/"; |
| 1016 | } |
Sahana Rao | 54dafa3 | 2020-06-22 08:42:37 +0100 | [diff] [blame] | 1017 | return directoryPath.substring(matcher.end()); |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 1018 | } |
| 1019 | return null; |
| 1020 | } |
| 1021 | |
| 1022 | public static @Nullable String extractPathOwnerPackageName(@Nullable String path) { |
| 1023 | if (path == null) return null; |
| 1024 | final Matcher m = PATTERN_OWNED_PATH.matcher(path); |
| 1025 | if (m.matches()) { |
| 1026 | return m.group(1); |
| 1027 | } else { |
| 1028 | return null; |
| 1029 | } |
| 1030 | } |
| 1031 | |
| 1032 | /** |
Ricky Wai | feb9d9b | 2020-04-06 19:14:46 +0100 | [diff] [blame] | 1033 | * Returns true if relative path is Android/data or Android/obb path. |
| 1034 | */ |
| 1035 | public static boolean isDataOrObbPath(String path) { |
| 1036 | if (path == null) return false; |
| 1037 | final Matcher m = PATTERN_DATA_OR_OBB_PATH.matcher(path); |
| 1038 | return m.matches(); |
| 1039 | } |
| 1040 | |
| 1041 | /** |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 1042 | * Returns the name of the top level directory, or null if the path doesn't go through the |
| 1043 | * external storage directory. |
| 1044 | */ |
| 1045 | @Nullable |
| 1046 | public static String extractTopLevelDir(String path) { |
Sahana Rao | 920f666 | 2020-04-30 15:13:42 +0100 | [diff] [blame] | 1047 | final String relativePath = extractRelativePath(path); |
| 1048 | if (relativePath == null) { |
| 1049 | return null; |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 1050 | } |
Sahana Rao | 920f666 | 2020-04-30 15:13:42 +0100 | [diff] [blame] | 1051 | final String[] relativePathSegments = relativePath.split("/"); |
| 1052 | return relativePathSegments.length > 0 ? relativePathSegments[0] : null; |
Jeff Sharkey | 1f6ad1a | 2019-12-20 14:26:34 -0700 | [diff] [blame] | 1053 | } |
Jeff Sharkey | c55994b | 2019-12-20 19:43:59 -0700 | [diff] [blame] | 1054 | |
Sahana Rao | e44080f | 2020-09-25 11:13:55 +0100 | [diff] [blame] | 1055 | public static boolean isDefaultDirectoryName(@Nullable String dirName) { |
| 1056 | for (String defaultDirName : DEFAULT_FOLDER_NAMES) { |
| 1057 | if (defaultDirName.equalsIgnoreCase(dirName)) { |
| 1058 | return true; |
| 1059 | } |
| 1060 | } |
| 1061 | return false; |
| 1062 | } |
| 1063 | |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1064 | /** |
Jeff Sharkey | 05c3a03 | 2020-04-09 16:57:04 -0600 | [diff] [blame] | 1065 | * Compute the value of {@link MediaColumns#DATE_EXPIRES} based on other |
| 1066 | * columns being modified by this operation. |
| 1067 | */ |
| 1068 | public static void computeDateExpires(@NonNull ContentValues values) { |
| 1069 | // External apps have no ability to change this field |
| 1070 | values.remove(MediaColumns.DATE_EXPIRES); |
| 1071 | |
| 1072 | // Only define the field when this modification is actually adjusting |
| 1073 | // one of the flags that should influence the expiration |
Jeff Sharkey | a9473e9 | 2020-04-17 15:54:30 -0600 | [diff] [blame] | 1074 | final Object pending = values.get(MediaColumns.IS_PENDING); |
Jeff Sharkey | 05c3a03 | 2020-04-09 16:57:04 -0600 | [diff] [blame] | 1075 | if (pending != null) { |
Jeff Sharkey | a9473e9 | 2020-04-17 15:54:30 -0600 | [diff] [blame] | 1076 | if (parseBoolean(pending, false)) { |
Jeff Sharkey | 05c3a03 | 2020-04-09 16:57:04 -0600 | [diff] [blame] | 1077 | values.put(MediaColumns.DATE_EXPIRES, |
| 1078 | (System.currentTimeMillis() + DEFAULT_DURATION_PENDING) / 1000); |
| 1079 | } else { |
| 1080 | values.putNull(MediaColumns.DATE_EXPIRES); |
| 1081 | } |
| 1082 | } |
Jeff Sharkey | a9473e9 | 2020-04-17 15:54:30 -0600 | [diff] [blame] | 1083 | final Object trashed = values.get(MediaColumns.IS_TRASHED); |
Jeff Sharkey | 05c3a03 | 2020-04-09 16:57:04 -0600 | [diff] [blame] | 1084 | if (trashed != null) { |
Jeff Sharkey | a9473e9 | 2020-04-17 15:54:30 -0600 | [diff] [blame] | 1085 | if (parseBoolean(trashed, false)) { |
Jeff Sharkey | 05c3a03 | 2020-04-09 16:57:04 -0600 | [diff] [blame] | 1086 | values.put(MediaColumns.DATE_EXPIRES, |
| 1087 | (System.currentTimeMillis() + DEFAULT_DURATION_TRASHED) / 1000); |
| 1088 | } else { |
| 1089 | values.putNull(MediaColumns.DATE_EXPIRES); |
| 1090 | } |
| 1091 | } |
| 1092 | } |
| 1093 | |
| 1094 | /** |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1095 | * Compute several scattered {@link MediaColumns} values from |
| 1096 | * {@link MediaColumns#DATA}. This method performs no enforcement of |
| 1097 | * argument validity. |
| 1098 | */ |
Sahana Rao | ea587fc | 2020-06-03 15:56:23 +0100 | [diff] [blame] | 1099 | public static void computeValuesFromData(@NonNull ContentValues values, boolean isForFuse) { |
Jeff Sharkey | c55994b | 2019-12-20 19:43:59 -0700 | [diff] [blame] | 1100 | // Worst case we have to assume no bucket details |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1101 | values.remove(MediaColumns.VOLUME_NAME); |
| 1102 | values.remove(MediaColumns.RELATIVE_PATH); |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1103 | values.remove(MediaColumns.IS_TRASHED); |
| 1104 | values.remove(MediaColumns.DATE_EXPIRES); |
| 1105 | values.remove(MediaColumns.DISPLAY_NAME); |
| 1106 | values.remove(MediaColumns.BUCKET_ID); |
| 1107 | values.remove(MediaColumns.BUCKET_DISPLAY_NAME); |
Jeff Sharkey | c55994b | 2019-12-20 19:43:59 -0700 | [diff] [blame] | 1108 | |
| 1109 | final String data = values.getAsString(MediaColumns.DATA); |
| 1110 | if (TextUtils.isEmpty(data)) return; |
| 1111 | |
| 1112 | final File file = new File(data); |
| 1113 | final File fileLower = new File(data.toLowerCase(Locale.ROOT)); |
| 1114 | |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1115 | values.put(MediaColumns.VOLUME_NAME, extractVolumeName(data)); |
| 1116 | values.put(MediaColumns.RELATIVE_PATH, extractRelativePath(data)); |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1117 | final String displayName = extractDisplayName(data); |
| 1118 | final Matcher matcher = FileUtils.PATTERN_EXPIRES_FILE.matcher(displayName); |
| 1119 | if (matcher.matches()) { |
| 1120 | values.put(MediaColumns.IS_PENDING, |
| 1121 | matcher.group(1).equals(FileUtils.PREFIX_PENDING) ? 1 : 0); |
| 1122 | values.put(MediaColumns.IS_TRASHED, |
| 1123 | matcher.group(1).equals(FileUtils.PREFIX_TRASHED) ? 1 : 0); |
| 1124 | values.put(MediaColumns.DATE_EXPIRES, Long.parseLong(matcher.group(2))); |
| 1125 | values.put(MediaColumns.DISPLAY_NAME, matcher.group(3)); |
| 1126 | } else { |
Sahana Rao | ea587fc | 2020-06-03 15:56:23 +0100 | [diff] [blame] | 1127 | if (isForFuse) { |
| 1128 | // Allow Fuse thread to set IS_PENDING when using DATA column. |
| 1129 | // TODO(b/156867379) Unset IS_PENDING when Fuse thread doesn't explicitly specify |
| 1130 | // IS_PENDING. It can't be done now because we scan after create. Scan doesn't |
| 1131 | // explicitly specify the value of IS_PENDING. |
| 1132 | } else { |
| 1133 | values.put(MediaColumns.IS_PENDING, 0); |
| 1134 | } |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1135 | values.put(MediaColumns.IS_TRASHED, 0); |
| 1136 | values.putNull(MediaColumns.DATE_EXPIRES); |
| 1137 | values.put(MediaColumns.DISPLAY_NAME, displayName); |
| 1138 | } |
Jeff Sharkey | c55994b | 2019-12-20 19:43:59 -0700 | [diff] [blame] | 1139 | |
| 1140 | // Buckets are the parent directory |
| 1141 | final String parent = fileLower.getParent(); |
| 1142 | if (parent != null) { |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1143 | values.put(MediaColumns.BUCKET_ID, parent.hashCode()); |
Jeff Sharkey | c55994b | 2019-12-20 19:43:59 -0700 | [diff] [blame] | 1144 | // The relative path for files in the top directory is "/" |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1145 | if (!"/".equals(values.getAsString(MediaColumns.RELATIVE_PATH))) { |
| 1146 | values.put(MediaColumns.BUCKET_DISPLAY_NAME, file.getParentFile().getName()); |
Jeff Sharkey | c55994b | 2019-12-20 19:43:59 -0700 | [diff] [blame] | 1147 | } |
| 1148 | } |
| 1149 | } |
Sahana Rao | f21671d | 2020-03-09 16:49:26 +0000 | [diff] [blame] | 1150 | |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1151 | /** |
| 1152 | * Compute {@link MediaColumns#DATA} from several scattered |
| 1153 | * {@link MediaColumns} values. This method performs no enforcement of |
| 1154 | * argument validity. |
| 1155 | */ |
| 1156 | public static void computeDataFromValues(@NonNull ContentValues values, |
Sahana Rao | ea587fc | 2020-06-03 15:56:23 +0100 | [diff] [blame] | 1157 | @NonNull File volumePath, boolean isForFuse) { |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1158 | values.remove(MediaColumns.DATA); |
| 1159 | |
| 1160 | final String displayName = values.getAsString(MediaColumns.DISPLAY_NAME); |
| 1161 | final String resolvedDisplayName; |
Sahana Rao | ea587fc | 2020-06-03 15:56:23 +0100 | [diff] [blame] | 1162 | // Pending file path shouldn't be rewritten for files inserted via filepath. |
| 1163 | if (!isForFuse && getAsBoolean(values, MediaColumns.IS_PENDING, false)) { |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1164 | final long dateExpires = getAsLong(values, MediaColumns.DATE_EXPIRES, |
| 1165 | (System.currentTimeMillis() + DEFAULT_DURATION_PENDING) / 1000); |
Corina | 54fb8ba | 2020-11-27 13:38:09 +0000 | [diff] [blame] | 1166 | resolvedDisplayName = String.format( |
| 1167 | Locale.US, ".%s-%d-%s", FileUtils.PREFIX_PENDING, dateExpires, displayName); |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1168 | } else if (getAsBoolean(values, MediaColumns.IS_TRASHED, false)) { |
| 1169 | final long dateExpires = getAsLong(values, MediaColumns.DATE_EXPIRES, |
| 1170 | (System.currentTimeMillis() + DEFAULT_DURATION_TRASHED) / 1000); |
Corina | 54fb8ba | 2020-11-27 13:38:09 +0000 | [diff] [blame] | 1171 | resolvedDisplayName = String.format( |
| 1172 | Locale.US, ".%s-%d-%s", FileUtils.PREFIX_TRASHED, dateExpires, displayName); |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1173 | } else { |
| 1174 | resolvedDisplayName = displayName; |
| 1175 | } |
| 1176 | |
| 1177 | final File filePath = buildPath(volumePath, |
| 1178 | values.getAsString(MediaColumns.RELATIVE_PATH), resolvedDisplayName); |
| 1179 | values.put(MediaColumns.DATA, filePath.getAbsolutePath()); |
| 1180 | } |
| 1181 | |
Sahana Rao | 76b8b5b | 2020-04-17 20:21:59 +0100 | [diff] [blame] | 1182 | public static void sanitizeValues(@NonNull ContentValues values, |
| 1183 | boolean rewriteHiddenFileName) { |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1184 | final String[] relativePath = values.getAsString(MediaColumns.RELATIVE_PATH).split("/"); |
| 1185 | for (int i = 0; i < relativePath.length; i++) { |
Sahana Rao | 76b8b5b | 2020-04-17 20:21:59 +0100 | [diff] [blame] | 1186 | relativePath[i] = sanitizeDisplayName(relativePath[i], rewriteHiddenFileName); |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1187 | } |
| 1188 | values.put(MediaColumns.RELATIVE_PATH, |
| 1189 | String.join("/", relativePath) + "/"); |
Sahana Rao | 76b8b5b | 2020-04-17 20:21:59 +0100 | [diff] [blame] | 1190 | |
| 1191 | final String displayName = values.getAsString(MediaColumns.DISPLAY_NAME); |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1192 | values.put(MediaColumns.DISPLAY_NAME, |
Sahana Rao | 76b8b5b | 2020-04-17 20:21:59 +0100 | [diff] [blame] | 1193 | sanitizeDisplayName(displayName, rewriteHiddenFileName)); |
Jeff Sharkey | 89149b6 | 2020-03-29 22:03:44 -0600 | [diff] [blame] | 1194 | } |
| 1195 | |
Sahana Rao | f21671d | 2020-03-09 16:49:26 +0000 | [diff] [blame] | 1196 | /** {@hide} **/ |
| 1197 | @Nullable |
| 1198 | public static String getAbsoluteSanitizedPath(String path) { |
| 1199 | final String[] pathSegments = sanitizePath(path); |
| 1200 | if (pathSegments.length == 0) { |
| 1201 | return null; |
| 1202 | } |
| 1203 | return path = "/" + String.join("/", |
| 1204 | Arrays.copyOfRange(pathSegments, 1, pathSegments.length)); |
| 1205 | } |
| 1206 | |
| 1207 | /** {@hide} */ |
| 1208 | public static @NonNull String[] sanitizePath(@Nullable String path) { |
| 1209 | if (path == null) { |
| 1210 | return new String[0]; |
| 1211 | } else { |
| 1212 | final String[] segments = path.split("/"); |
| 1213 | // If the path corresponds to the top level directory, then we return an empty path |
| 1214 | // which denotes the top level directory |
| 1215 | if (segments.length == 0) { |
| 1216 | return new String[] { "" }; |
| 1217 | } |
| 1218 | for (int i = 0; i < segments.length; i++) { |
| 1219 | segments[i] = sanitizeDisplayName(segments[i]); |
| 1220 | } |
| 1221 | return segments; |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | /** |
Sahana Rao | 76b8b5b | 2020-04-17 20:21:59 +0100 | [diff] [blame] | 1226 | * Sanitizes given name by mutating the file name to make it valid for a FAT filesystem. |
Sahana Rao | f21671d | 2020-03-09 16:49:26 +0000 | [diff] [blame] | 1227 | * @hide |
| 1228 | */ |
| 1229 | public static @Nullable String sanitizeDisplayName(@Nullable String name) { |
Sahana Rao | 76b8b5b | 2020-04-17 20:21:59 +0100 | [diff] [blame] | 1230 | return sanitizeDisplayName(name, /*rewriteHiddenFileName*/ false); |
| 1231 | } |
| 1232 | |
| 1233 | /** |
| 1234 | * Sanitizes given name by appending '_' to make it non-hidden and mutating the file name to |
| 1235 | * make it valid for a FAT filesystem. |
| 1236 | * @hide |
| 1237 | */ |
| 1238 | public static @Nullable String sanitizeDisplayName(@Nullable String name, |
| 1239 | boolean rewriteHiddenFileName) { |
Sahana Rao | f21671d | 2020-03-09 16:49:26 +0000 | [diff] [blame] | 1240 | if (name == null) { |
| 1241 | return null; |
Sahana Rao | 76b8b5b | 2020-04-17 20:21:59 +0100 | [diff] [blame] | 1242 | } else if (rewriteHiddenFileName && name.startsWith(".")) { |
Sahana Rao | f21671d | 2020-03-09 16:49:26 +0000 | [diff] [blame] | 1243 | // The resulting file must not be hidden. |
Sahana Rao | 76b8b5b | 2020-04-17 20:21:59 +0100 | [diff] [blame] | 1244 | return "_" + name; |
Sahana Rao | f21671d | 2020-03-09 16:49:26 +0000 | [diff] [blame] | 1245 | } else { |
| 1246 | return buildValidFatFilename(name); |
| 1247 | } |
| 1248 | } |
shafik | a202fdd | 2020-05-11 20:19:27 +0100 | [diff] [blame] | 1249 | |
| 1250 | /** |
Martijn Coenen | 070bce1 | 2020-06-08 21:18:24 +0200 | [diff] [blame] | 1251 | * Test if this given directory should be considered hidden. |
| 1252 | */ |
| 1253 | @VisibleForTesting |
| 1254 | public static boolean isDirectoryHidden(@NonNull File dir) { |
| 1255 | final String name = dir.getName(); |
| 1256 | if (name.startsWith(".")) { |
| 1257 | return true; |
| 1258 | } |
| 1259 | |
| 1260 | final File nomedia = new File(dir, ".nomedia"); |
Sahana Rao | e44080f | 2020-09-25 11:13:55 +0100 | [diff] [blame] | 1261 | |
Martijn Coenen | 070bce1 | 2020-06-08 21:18:24 +0200 | [diff] [blame] | 1262 | // check for .nomedia presence |
Sahana Rao | e44080f | 2020-09-25 11:13:55 +0100 | [diff] [blame] | 1263 | if (!nomedia.exists()) { |
| 1264 | return false; |
Martijn Coenen | 070bce1 | 2020-06-08 21:18:24 +0200 | [diff] [blame] | 1265 | } |
Sahana Rao | e44080f | 2020-09-25 11:13:55 +0100 | [diff] [blame] | 1266 | |
| 1267 | // Handle top-level default directories. These directories should always be visible, |
| 1268 | // regardless of .nomedia presence. |
| 1269 | final String[] relativePath = sanitizePath(extractRelativePath(dir.getAbsolutePath())); |
| 1270 | final boolean isTopLevelDir = |
| 1271 | relativePath.length == 1 && TextUtils.isEmpty(relativePath[0]); |
| 1272 | if (isTopLevelDir && isDefaultDirectoryName(name)) { |
| 1273 | nomedia.delete(); |
| 1274 | return false; |
| 1275 | } |
| 1276 | |
| 1277 | // DCIM/Camera should always be visible regardless of .nomedia presence. |
| 1278 | if (CAMERA_RELATIVE_PATH.equalsIgnoreCase( |
| 1279 | extractRelativePathForDirectory(dir.getAbsolutePath()))) { |
| 1280 | nomedia.delete(); |
| 1281 | return false; |
| 1282 | } |
| 1283 | |
| 1284 | // .nomedia is present which makes this directory as hidden directory |
| 1285 | Logging.logPersistent("Observed non-standard " + nomedia); |
| 1286 | return true; |
Martijn Coenen | 070bce1 | 2020-06-08 21:18:24 +0200 | [diff] [blame] | 1287 | } |
| 1288 | |
| 1289 | /** |
| 1290 | * Test if this given file should be considered hidden. |
| 1291 | */ |
| 1292 | @VisibleForTesting |
| 1293 | public static boolean isFileHidden(@NonNull File file) { |
| 1294 | final String name = file.getName(); |
| 1295 | |
| 1296 | // Handle well-known file names that are pending or trashed; they |
| 1297 | // normally appear hidden, but we give them special treatment |
| 1298 | if (PATTERN_EXPIRES_FILE.matcher(name).matches()) { |
| 1299 | return false; |
| 1300 | } |
| 1301 | |
| 1302 | // Otherwise fall back to file name |
| 1303 | if (name.startsWith(".")) { |
| 1304 | return true; |
| 1305 | } |
| 1306 | return false; |
| 1307 | } |
| 1308 | |
| 1309 | /** |
shafik | a202fdd | 2020-05-11 20:19:27 +0100 | [diff] [blame] | 1310 | * Clears all app's external cache directories, i.e. for each app we delete |
| 1311 | * /sdcard/Android/data/app/cache/* but we keep the directory itself. |
| 1312 | * |
| 1313 | * @return 0 in case of success, or {@link OsConstants#EIO} if any error occurs. |
| 1314 | * |
| 1315 | * <p>This method doesn't perform any checks, so make sure that the calling package is allowed |
| 1316 | * to clear cache directories first. |
| 1317 | * |
| 1318 | * <p>If this method returned {@link OsConstants#EIO}, then we can't guarantee whether all, none |
| 1319 | * or part of the directories were cleared. |
| 1320 | */ |
| 1321 | public static int clearAppCacheDirectories() { |
| 1322 | int status = 0; |
| 1323 | Log.i(TAG, "Clearing cache for all apps"); |
| 1324 | final File rootDataDir = buildPath(Environment.getExternalStorageDirectory(), |
| 1325 | "Android", "data"); |
| 1326 | for (File appDataDir : rootDataDir.listFiles()) { |
| 1327 | try { |
| 1328 | final File appCacheDir = new File(appDataDir, "cache"); |
| 1329 | if (appCacheDir.isDirectory()) { |
| 1330 | FileUtils.deleteContents(appCacheDir); |
| 1331 | } |
| 1332 | } catch (Exception e) { |
| 1333 | // We want to avoid crashing MediaProvider at all costs, so we handle all "generic" |
| 1334 | // exceptions here, and just report to the caller that an IO exception has occurred. |
| 1335 | // We still try to clear the rest of the directories. |
| 1336 | Log.e(TAG, "Couldn't delete all app cache dirs!", e); |
| 1337 | status = OsConstants.EIO; |
| 1338 | } |
| 1339 | } |
| 1340 | return status; |
| 1341 | } |
Zim | 7e730f3 | 2020-09-30 11:38:50 +0100 | [diff] [blame] | 1342 | |
| 1343 | /** |
| 1344 | * @return {@code true} if {@code dir} is dirty and should be scanned, {@code false} otherwise. |
| 1345 | */ |
| 1346 | public static boolean isDirectoryDirty(File dir) { |
| 1347 | File nomedia = new File(dir, ".nomedia"); |
| 1348 | if (nomedia.exists()) { |
| 1349 | try { |
| 1350 | Optional<String> expectedPath = readString(nomedia); |
| 1351 | // Returns true If .nomedia file is empty or content doesn't match |dir| |
| 1352 | // Returns false otherwise |
| 1353 | return !expectedPath.isPresent() |
| 1354 | || !expectedPath.get().equals(dir.getPath()); |
| 1355 | } catch (IOException e) { |
| 1356 | Log.w(TAG, "Failed to read directory dirty" + dir); |
| 1357 | } |
| 1358 | } |
| 1359 | return true; |
| 1360 | } |
| 1361 | |
| 1362 | /** |
| 1363 | * {@code isDirty} == {@code true} will force {@code dir} scanning even if it's hidden |
| 1364 | * {@code isDirty} == {@code false} will skip {@code dir} scanning on next scan. |
| 1365 | */ |
| 1366 | public static void setDirectoryDirty(File dir, boolean isDirty) { |
| 1367 | File nomedia = new File(dir, ".nomedia"); |
| 1368 | if (nomedia.exists()) { |
| 1369 | try { |
| 1370 | writeString(nomedia, isDirty ? Optional.of("") : Optional.of(dir.getPath())); |
| 1371 | } catch (IOException e) { |
| 1372 | Log.w(TAG, "Failed to change directory dirty: " + dir + ". isDirty: " + isDirty); |
| 1373 | } |
| 1374 | } |
| 1375 | } |
| 1376 | |
| 1377 | /** |
| 1378 | * @return the folder containing the top-most .nomedia in {@code file} hierarchy. |
| 1379 | * E.g input as /sdcard/foo/bar/ will return /sdcard/foo |
| 1380 | * even if foo and bar contain .nomedia files. |
| 1381 | * |
| 1382 | * Returns {@code null} if there's no .nomedia in hierarchy |
| 1383 | */ |
| 1384 | public static File getTopLevelNoMedia(@NonNull File file) { |
Sahana Rao | 7abc52c | 2020-12-07 16:02:03 +0000 | [diff] [blame^] | 1385 | File topNoMediaDir = null; |
Zim | 7e730f3 | 2020-09-30 11:38:50 +0100 | [diff] [blame] | 1386 | |
| 1387 | File parent = file; |
| 1388 | while (parent != null) { |
| 1389 | File nomedia = new File(parent, ".nomedia"); |
| 1390 | if (nomedia.exists()) { |
Sahana Rao | 7abc52c | 2020-12-07 16:02:03 +0000 | [diff] [blame^] | 1391 | topNoMediaDir = parent; |
Zim | 7e730f3 | 2020-09-30 11:38:50 +0100 | [diff] [blame] | 1392 | } |
| 1393 | parent = parent.getParentFile(); |
| 1394 | } |
| 1395 | |
Sahana Rao | 7abc52c | 2020-12-07 16:02:03 +0000 | [diff] [blame^] | 1396 | return topNoMediaDir; |
Zim | 7e730f3 | 2020-09-30 11:38:50 +0100 | [diff] [blame] | 1397 | } |
Jeff Sharkey | 7ea24f2 | 2019-08-22 10:14:18 -0600 | [diff] [blame] | 1398 | } |