public static int getUriType(Uri uri) {
   assertNonRelative(uri);
   String scheme = uri.getScheme();
   if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
     return URI_TYPE_CONTENT;
   }
   if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
     return URI_TYPE_RESOURCE;
   }
   if (ContentResolver.SCHEME_FILE.equals(scheme)) {
     if (uri.getPath().startsWith("/android_asset/")) {
       return URI_TYPE_ASSET;
     }
     return URI_TYPE_FILE;
   }
   if ("data".equals(scheme)) {
     return URI_TYPE_DATA;
   }
   if ("http".equals(scheme)) {
     return URI_TYPE_HTTP;
   }
   if ("https".equals(scheme)) {
     return URI_TYPE_HTTPS;
   }
   return URI_TYPE_UNKNOWN;
 }
예제 #2
0
 private boolean isSharable() {
   // We cannot grant read permission to the receiver since we put
   // the data URI in EXTRA_STREAM instead of the data part of an intent
   // And there are issues in MediaUploader and Bluetooth file sender to
   // share a general image data. So, we only share for local file.
   return ContentResolver.SCHEME_FILE.equals(mUri.getScheme());
 }
예제 #3
0
 static GifInfoHandle openUri(ContentResolver resolver, Uri uri, boolean justDecodeMetaData)
     throws IOException {
   if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) { // workaround for #128
     return new GifInfoHandle(uri.getPath(), justDecodeMetaData);
   }
   return new GifInfoHandle(resolver.openAssetFileDescriptor(uri, "r"), justDecodeMetaData);
 }
예제 #4
0
  public static InputStream openInputStream(Uri uri) {

    if (uri == null) return null;

    String scheme = uri.getScheme();
    InputStream stream = null;

    if (scheme == null || ContentResolver.SCHEME_FILE.equals(scheme)) {

      // from file
      stream = openFileInputStream(uri.getPath());

    } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {

      // from content
      stream = openContentInputStream(uri);

    } else if (Constants.SCHEME_HTTP.equals(scheme) || Constants.SCHEME_HTTPS.equals(scheme)) {

      // from remote uri
      stream = openRemoteInputStream(uri);

    } else if (Constants.SCHEME_RESOURCE.equals(scheme)) {

      stream = openResourceStream(uri);

    } else if (Constants.SCHEME_ASSETS.equals(scheme)) {

      stream = openAssetsStream(uri);
    }

    return stream;
  }
예제 #5
0
 public static String getRealFilePath(Context context, final Uri uri) {
   if (uri == null) {
     return null;
   }
   final String scheme = uri.getScheme();
   String path = null;
   if (scheme == null) {
     path = uri.getPath();
   } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
     path = uri.getPath();
   } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
     Cursor cursor =
         context
             .getContentResolver()
             .query(uri, new String[] {ImageColumns.DATA}, null, null, null);
     if (null != cursor) {
       if (cursor.moveToFirst()) {
         int index = cursor.getColumnIndex(ImageColumns.DATA);
         if (index > -1) {
           path = cursor.getString(index);
         }
       }
       cursor.close();
     }
   }
   return path;
 }
예제 #6
0
  /**
   * Try to get the exif orientation of the passed image uri
   *
   * @param context
   * @param uri
   * @return
   */
  public static int getExifOrientation(Context context, Uri uri) {

    final String scheme = uri.getScheme();

    ContentProviderClient provider = null;
    if (scheme == null || ContentResolver.SCHEME_FILE.equals(scheme)) {
      return getExifOrientation(uri.getPath());
    } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
      try {
        provider = context.getContentResolver().acquireContentProviderClient(uri);
      } catch (SecurityException e) {
        return 0;
      }

      if (provider != null) {
        Cursor result;
        try {
          result =
              provider.query(
                  uri,
                  new String[] {Images.ImageColumns.ORIENTATION, Images.ImageColumns.DATA},
                  null,
                  null,
                  null);
        } catch (Exception e) {
          e.printStackTrace();
          return 0;
        }

        if (result == null) {
          return 0;
        }

        int orientationColumnIndex = result.getColumnIndex(Images.ImageColumns.ORIENTATION);
        int dataColumnIndex = result.getColumnIndex(Images.ImageColumns.DATA);

        try {
          if (result.getCount() > 0) {
            result.moveToFirst();

            int rotation = 0;

            if (orientationColumnIndex > -1) {
              rotation = result.getInt(orientationColumnIndex);
            }

            if (dataColumnIndex > -1) {
              String path = result.getString(dataColumnIndex);
              rotation |= getExifOrientation(path);
            }
            return rotation;
          }
        } finally {
          result.close();
        }
      }
    }
    return 0;
  }
예제 #7
0
 public static boolean weOwnFile(Context context, Uri uri) {
   if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
     return false;
   } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
     return fileIsInFilesDir(context, uri);
   } else {
     return weOwnFileLollipop(uri);
   }
 }
예제 #8
0
 @Override
 public MediaDetails getDetails() {
   MediaDetails details = super.getDetails();
   if (mWidth != 0 && mHeight != 0) {
     details.addDetail(MediaDetails.INDEX_WIDTH, mWidth);
     details.addDetail(MediaDetails.INDEX_HEIGHT, mHeight);
   }
   if (mContentType != null) {
     details.addDetail(MediaDetails.INDEX_MIMETYPE, mContentType);
   }
   if (ContentResolver.SCHEME_FILE.equals(mUri.getScheme())) {
     String filePath = mUri.getPath();
     details.addDetail(MediaDetails.INDEX_PATH, filePath);
     MediaDetails.extractExifInfo(details, filePath);
   }
   return details;
 }
예제 #9
0
  public static String getFilePathFromUrl(Context context, Uri uri) {
    String path = null;
    String scheme = uri.getScheme();
    if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
      String projection[] = {
        ImageColumns.DATA,
      };
      Cursor c = context.getContentResolver().query(uri, projection, null, null, null);
      if (c != null && c.moveToFirst()) {
        path = c.getString(0);
      }
      if (c != null) c.close();
    } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
      path = uri.getPath();
    }

    return path;
  }
예제 #10
0
파일: ImageUtils.java 프로젝트: qylk/base
 public static String getPathFromUri(Context context, Uri uri) {
   String path = null;
   String uriScheme = uri.getScheme();
   if (ContentResolver.SCHEME_FILE.equals(uriScheme)) {
     path = uri.getSchemeSpecificPart();
   } else if (ContentResolver.SCHEME_CONTENT.equals(uriScheme)) {
     String[] projection = {MediaStore.Images.Media.DATA};
     Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
     if (cursor != null) {
       if (cursor.moveToFirst()) {
         path = cursor.getString(0);
       }
       cursor.close();
     }
   } else {
     path = uri.getPath();
   }
   return path;
 }
예제 #11
0
 private int openOrDownloadInner(JobContext jc) {
   String scheme = mUri.getScheme();
   if (ContentResolver.SCHEME_CONTENT.equals(scheme)
       || ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)
       || ContentResolver.SCHEME_FILE.equals(scheme)) {
     try {
       if (MIME_TYPE_JPEG.equalsIgnoreCase(mContentType)) {
         InputStream is = mApplication.getContentResolver().openInputStream(mUri);
         mRotation = Exif.getOrientation(is);
         Utils.closeSilently(is);
       }
       mFileDescriptor = mApplication.getContentResolver().openFileDescriptor(mUri, "r");
       if (jc.isCancelled()) return STATE_INIT;
       return STATE_DOWNLOADED;
     } catch (FileNotFoundException e) {
       Log.w(TAG, "fail to open: " + mUri, e);
       return STATE_ERROR;
     }
   } else {
     try {
       URL url = new URI(mUri.toString()).toURL();
       mCacheEntry = mApplication.getDownloadCache().download(jc, url);
       if (jc.isCancelled()) return STATE_INIT;
       if (mCacheEntry == null) {
         Log.w(TAG, "download failed " + url);
         return STATE_ERROR;
       }
       if (MIME_TYPE_JPEG.equalsIgnoreCase(mContentType)) {
         InputStream is = new FileInputStream(mCacheEntry.cacheFile);
         mRotation = Exif.getOrientation(is);
         Utils.closeSilently(is);
       }
       mFileDescriptor =
           ParcelFileDescriptor.open(mCacheEntry.cacheFile, ParcelFileDescriptor.MODE_READ_ONLY);
       return STATE_DOWNLOADED;
     } catch (Throwable t) {
       Log.w(TAG, "download error", t);
       return STATE_ERROR;
     }
   }
 }
예제 #12
0
  /**
   * Fetch the file name from URI
   *
   * @param context Context
   * @param file URI
   * @return fileName String
   * @throws IllegalArgumentException
   */
  public static String getFileName(Context context, Uri file) throws IllegalArgumentException {
    Cursor cursor = null;
    try {
      cursor = context.getContentResolver().query(file, null, null, null, null);
      if (ContentResolver.SCHEME_CONTENT.equals(file.getScheme())) {
        if (cursor != null && cursor.moveToFirst()) {
          return cursor.getString(cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
        } else {
          throw new IllegalArgumentException("Error in retrieving file name from the URI");
        }
      } else if (ContentResolver.SCHEME_FILE.equals(file.getScheme())) {
        return file.getLastPathSegment();
      }
      throw new IllegalArgumentException("Unsupported URI scheme");

    } finally {
      if (cursor != null) {
        cursor.close();
      }
    }
  }
예제 #13
0
  /**
   * Fetch the file size from URI
   *
   * @param context Context
   * @param file URI
   * @return fileSize long
   * @throws IllegalArgumentException
   */
  public static long getFileSize(Context context, Uri file) throws IllegalArgumentException {
    Cursor cursor = null;
    try {
      cursor = context.getContentResolver().query(file, null, null, null, null);
      if (ContentResolver.SCHEME_CONTENT.equals(file.getScheme())) {
        if (cursor != null && cursor.moveToFirst()) {
          return Long.valueOf(cursor.getString(cursor.getColumnIndexOrThrow(OpenableColumns.SIZE)));
        } else {
          throw new IllegalArgumentException("Error in retrieving file size form the URI");
        }
      } else if (ContentResolver.SCHEME_FILE.equals(file.getScheme())) {
        return (new File(file.getPath())).length();
      }
      throw new IllegalArgumentException("Unsupported URI scheme");

    } finally {
      if (cursor != null) {
        cursor.close();
      }
    }
  }
예제 #14
0
 /** 通过Uri获得文件路径* */
 public static String getRealFilePath(final Context context, final Uri uri) {
   if (null == uri) return null;
   final String scheme = uri.getScheme();
   String data = null;
   if (scheme == null) data = uri.getPath();
   else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
     data = uri.getPath();
   } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
     Cursor cursor =
         context
             .getContentResolver()
             .query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
     if (null != cursor) {
       if (cursor.moveToFirst()) {
         int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
         if (index > -1) {
           data = cursor.getString(index);
         }
       }
       cursor.close();
     }
   }
   return data;
 }
예제 #15
0
 private boolean isLocalUri(String scheme) {
   return ContentResolver.SCHEME_FILE.equals(scheme)
       || ContentResolver.SCHEME_CONTENT.equals(scheme)
       || ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme);
 }
예제 #16
0
  /**
   * Downloads a file form a given URL and saves it to the specified directory.
   *
   * @param source URL of the server to receive the file
   * @param target Full path of the file on the file system
   */
  private void download(
      final String source, final String target, JSONArray args, CallbackContext callbackContext)
      throws JSONException {
    Log.d(LOG_TAG, "download " + source + " to " + target);

    final boolean trustEveryone = args.optBoolean(2);
    final String objectId = args.getString(3);
    final JSONObject headers = args.optJSONObject(4);

    final URL url;
    try {
      url = new URL(source);
    } catch (MalformedURLException e) {
      JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
      Log.e(LOG_TAG, error.toString(), e);
      callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
      return;
    }
    final String sourceProtocol = url.getProtocol();
    final boolean useHttps = "https".equals(sourceProtocol);
    final boolean useResolvers =
        ContentResolver.SCHEME_FILE.equals(sourceProtocol)
            || ContentResolver.SCHEME_CONTENT.equals(sourceProtocol)
            || ContentResolver.SCHEME_ANDROID_RESOURCE.equals(sourceProtocol);

    // TODO: refactor to also allow resources & content:
    if (!useResolvers && !Config.isUrlWhiteListed(source)) {
      Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'");
      JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401);
      callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
      return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
      activeRequests.put(objectId, context);
    }

    cordova
        .getThreadPool()
        .execute(
            new Runnable() {
              public void run() {
                if (context.aborted) {
                  return;
                }
                URLConnection connection = null;
                HostnameVerifier oldHostnameVerifier = null;
                SSLSocketFactory oldSocketFactory = null;
                File file = null;
                PluginResult result = null;

                try {
                  UriResolver sourceResolver = null;
                  UriResolver targetResolver = webView.resolveUri(Uri.parse(target));
                  TrackingInputStream inputStream = null;

                  file = targetResolver.getLocalFile();
                  context.targetFile = file;

                  Log.d(LOG_TAG, "Download file:" + url);

                  FileProgressResult progress = new FileProgressResult();

                  if (useResolvers) {
                    sourceResolver = webView.resolveUri(Uri.parse(source));
                    long len = sourceResolver.computeLength();
                    if (len != -1) {
                      progress.setLengthComputable(true);
                      progress.setTotal(len);
                    }
                    inputStream = new SimpleTrackingInputStream(sourceResolver.getInputStream());
                  } else {
                    // connect to server
                    // Open a HTTP connection to the URL based on protocol
                    if (useHttps) {
                      // Using standard HTTPS connection. Will not allow self signed certificate
                      if (!trustEveryone) {
                        connection = (HttpsURLConnection) httpClient.open(url);
                      }
                      // Use our HTTPS connection that blindly trusts everyone.
                      // This should only be used in debug environments
                      else {
                        // Setup the HTTPS connection class to trust everyone
                        HttpsURLConnection https = (HttpsURLConnection) httpClient.open(url);
                        oldSocketFactory = trustAllHosts(https);
                        // Save the current hostnameVerifier
                        oldHostnameVerifier = https.getHostnameVerifier();
                        // Setup the connection not to verify hostnames
                        https.setHostnameVerifier(DO_NOT_VERIFY);
                        connection = https;
                      }
                    }
                    // Return a standard HTTP connection
                    else {
                      connection = httpClient.open(url);
                    }

                    if (connection instanceof HttpURLConnection) {
                      ((HttpURLConnection) connection).setRequestMethod("GET");
                    }

                    // Add cookie support
                    String cookie = CookieManager.getInstance().getCookie(source);
                    if (cookie != null) {
                      connection.setRequestProperty("cookie", cookie);
                    }

                    // This must be explicitly set for gzip progress tracking to work.
                    connection.setRequestProperty("Accept-Encoding", "gzip");

                    // Handle the other headers
                    if (headers != null) {
                      addHeadersToRequest(connection, headers);
                    }

                    connection.connect();

                    if (connection.getContentEncoding() == null
                        || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
                      // Only trust content-length header if we understand
                      // the encoding -- identity or gzip
                      progress.setLengthComputable(true);
                      progress.setTotal(connection.getContentLength());
                    }
                    inputStream = getInputStream(connection);
                  }

                  OutputStream outputStream = null;

                  try {
                    outputStream = targetResolver.getOutputStream();
                    synchronized (context) {
                      if (context.aborted) {
                        return;
                      }
                      context.currentInputStream = inputStream;
                    }

                    // write bytes to file
                    byte[] buffer = new byte[MAX_BUFFER_SIZE];
                    int bytesRead = 0;
                    while ((bytesRead = inputStream.read(buffer)) > 0) {
                      outputStream.write(buffer, 0, bytesRead);
                      // Send a progress event.
                      progress.setLoaded(inputStream.getTotalRawBytesRead());
                      PluginResult progressResult =
                          new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
                      progressResult.setKeepCallback(true);
                      context.sendPluginResult(progressResult);
                    }
                  } finally {
                    context.currentInputStream = null;
                    safeClose(inputStream);
                    safeClose(outputStream);
                  }

                  Log.d(LOG_TAG, "Saved file: " + target);

                  // create FileEntry object
                  JSONObject fileEntry = FileUtils.getEntry(file);

                  result = new PluginResult(PluginResult.Status.OK, fileEntry);
                } catch (FileNotFoundException e) {
                  JSONObject error =
                      createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection);
                  Log.e(LOG_TAG, error.toString(), e);
                  result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
                } catch (IOException e) {
                  JSONObject error =
                      createFileTransferError(CONNECTION_ERR, source, target, connection);
                  Log.e(LOG_TAG, error.toString(), e);
                  result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
                } catch (JSONException e) {
                  Log.e(LOG_TAG, e.getMessage(), e);
                  result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
                } catch (Throwable e) {
                  JSONObject error =
                      createFileTransferError(CONNECTION_ERR, source, target, connection);
                  Log.e(LOG_TAG, error.toString(), e);
                  result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
                } finally {
                  synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                  }

                  if (connection != null) {
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                      HttpsURLConnection https = (HttpsURLConnection) connection;
                      https.setHostnameVerifier(oldHostnameVerifier);
                      https.setSSLSocketFactory(oldSocketFactory);
                    }
                  }

                  if (result == null) {
                    result =
                        new PluginResult(
                            PluginResult.Status.ERROR,
                            createFileTransferError(CONNECTION_ERR, source, target, connection));
                  }
                  // Remove incomplete download.
                  if (result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) {
                    file.delete();
                  }
                  context.sendPluginResult(result);
                }
              }
            });
  }
 @Override
 public TileImageLoader.Result loadInBackground() {
   if (mUri == null) {
     return Result.nullInstance();
   }
   final String scheme = mUri.getScheme();
   if ("http".equals(scheme) || "https".equals(scheme)) {
     final String url = mUri.toString();
     if (url == null) return Result.nullInstance();
     File cacheFile = mDiskCache.get(url);
     if (cacheFile != null) {
       final int cachedValidity = ImageValidator.checkImageValidity(cacheFile);
       if (ImageValidator.isValid(cachedValidity)) {
         // The file is corrupted, so we remove it from
         // cache.
         return decodeBitmapOnly(
             cacheFile, ImageValidator.isValidForRegionDecoder(cachedValidity));
       }
     }
     try {
       // from SD cache
       final InputStream is = mDownloader.getStream(url, new AccountExtra(mAccountId));
       if (is == null) return Result.nullInstance();
       try {
         final long length = is.available();
         mHandler.post(new DownloadStartRunnable(this, mListener, length));
         mDiskCache.save(
             url,
             is,
             new IoUtils.CopyListener() {
               @Override
               public boolean onBytesCopied(int current, int total) {
                 mHandler.post(new ProgressUpdateRunnable(mListener, current));
                 return !isAbandoned();
               }
             });
         mHandler.post(new DownloadFinishRunnable(this, mListener));
       } finally {
         IoUtils.closeSilently(is);
       }
       cacheFile = mDiskCache.get(url);
       final int downloadedValidity = ImageValidator.checkImageValidity(cacheFile);
       if (ImageValidator.isValid(downloadedValidity)) {
         // The file is corrupted, so we remove it from
         // cache.
         return decodeBitmapOnly(
             cacheFile, ImageValidator.isValidForRegionDecoder(downloadedValidity));
       } else {
         mDiskCache.remove(url);
         throw new IOException();
       }
     } catch (final Exception e) {
       mHandler.post(new DownloadErrorRunnable(this, mListener, e));
       return Result.getInstance(cacheFile, e);
     }
   } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
     final File file = new File(mUri.getPath());
     try {
       return decodeBitmapOnly(
           file, ImageValidator.isValidForRegionDecoder(ImageValidator.checkImageValidity(file)));
     } catch (final Exception e) {
       return Result.getInstance(file, e);
     }
   }
   return Result.nullInstance();
 }