예제 #1
0
  private void uploadLink(
      @Nullable String title, @Nullable String description, @NonNull String url) {
    LogUtil.v(TAG, "Received URL to upload");
    ApiClient client = new ApiClient(Endpoints.UPLOAD.getUrl(), ApiClient.HttpRequest.POST);

    FormEncodingBuilder builder = new FormEncodingBuilder().add("image", url).add("type", "URL");

    if (!TextUtils.isEmpty(title)) {
      builder.add("title", title);
    }

    if (!TextUtils.isEmpty(description)) {
      builder.add("description", description);
    }

    RequestBody body = builder.build();

    try {
      if (mNotificationId <= 0) mNotificationId = url.hashCode();
      onUploadStarted();
      JSONObject json = client.doWork(body);
      int status = json.getInt(ApiClient.KEY_STATUS);

      if (status == ApiClient.STATUS_OK) {
        handleResponse(json.getJSONObject(ApiClient.KEY_DATA));
      } else {
        onUploadFailed(title, description, url, false);
      }
    } catch (IOException | JSONException e) {
      LogUtil.e(TAG, "Error uploading url", e);
      onUploadFailed(title, description, url, false);
    }
  }
예제 #2
0
  private void handleArgs(@Nullable Bundle args) {
    if (args == null) {
      mMultiView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
      return;
    }

    List<Upload> uploads = null;

    if (args.containsKey(KEY_PASSED_FILE)) {
      LogUtil.v(TAG, "Received file from bundle");
      uploads = new ArrayList<>(1);
      uploads.add(new Upload(args.getString(KEY_PASSED_FILE)));
    } else if (args.containsKey(KEY_PASSED_LINK)) {
      mMultiView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
      String link = args.getString(KEY_PASSED_LINK);
      getChildFragmentManager()
          .beginTransaction()
          .add(UploadLinkDialogFragment.newInstance(link), UploadLinkDialogFragment.TAG)
          .commit();
    } else if (args.containsKey(KEY_PASSED_URIS)) {
      ArrayList<Uri> photoUris = args.getParcelableArrayList(KEY_PASSED_URIS);

      if (photoUris != null && !photoUris.isEmpty()) {
        LogUtil.v(TAG, "Received " + photoUris.size() + " images via Share intent");
        new DecodeImagesTask(this).execute(photoUris);
        mMultiView.setViewState(MultiStateView.VIEW_STATE_LOADING);
      }
    }

    if (uploads != null && !uploads.isEmpty()) {
      mAdapter = new UploadPhotoAdapter(getActivity(), uploads, this);
      mRecyclerView.setAdapter(mAdapter);
      mMultiView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
    }
  }
예제 #3
0
    @Override
    protected List<Upload> doInBackground(List<Uri>... params) {
      if (params != null && params[0] != null && !params[0].isEmpty()) {
        Activity activity = mFragment.get().getActivity();
        ContentResolver resolver = activity.getContentResolver();
        photoUris = params[0];
        List<Upload> uploads = new ArrayList<>(photoUris.size());
        boolean hasReadPermission =
            PermissionUtils.hasPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);

        for (Uri uri : photoUris) {
          try {
            // Check if the URI is a file as we will need read permissions for it
            if (!hasReadPermission && "file".equals(uri.getScheme())) {
              LogUtil.v("DecodeImageTask", "Received a File URI and don't have permissions");
              needsPermission = true;
              return null;
            }

            File file = FileUtil.createFile(uri, resolver);
            if (FileUtil.isFileValid(file)) uploads.add(new Upload(file.getAbsolutePath()));
          } catch (Throwable ex) {
            LogUtil.e("DecodeImageTask", "Unable to decode image", ex);
          }
        }

        return uploads;
      }

      return null;
    }
예제 #4
0
  /**
   * Checks if the needed permissions are available
   *
   * @return If the permissions are available. If false is returned, the necessary prompts will be
   *     shown
   */
  private boolean checkWritePermissions() {
    @PermissionUtils.PermissionLevel
    int permissionLevel =
        PermissionUtils.getPermissionLevel(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    switch (permissionLevel) {
      case PermissionUtils.PERMISSION_AVAILABLE:
        LogUtil.v(TAG, "Permissions available");
        return true;

      case PermissionUtils.PERMISSION_DENIED:
        new AlertDialog.Builder(getActivity(), app.getImgurTheme().getAlertDialogTheme())
            .setTitle(R.string.permission_title)
            .setMessage(R.string.permission_rationale_upload)
            .setNegativeButton(
                R.string.cancel,
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialogInterface, int i) {
                    Snackbar.make(mMultiView, R.string.permission_denied, Snackbar.LENGTH_LONG)
                        .show();
                  }
                })
            .setPositiveButton(
                R.string.okay,
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialogInterface, int i) {
                    ActivityCompat.requestPermissions(
                        getActivity(),
                        new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        RequestCodes.REQUEST_PERMISSION_WRITE);
                  }
                })
            .setOnCancelListener(
                new DialogInterface.OnCancelListener() {
                  @Override
                  public void onCancel(DialogInterface dialogInterface) {
                    Snackbar.make(mMultiView, R.string.permission_denied, Snackbar.LENGTH_LONG)
                        .show();
                  }
                })
            .show();
        break;

      case PermissionUtils.PERMISSION_NEVER_ASKED:
      default:
        LogUtil.v(TAG, "Prompting for permissions");
        ActivityCompat.requestPermissions(
            getActivity(),
            new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
            RequestCodes.REQUEST_PERMISSION_WRITE);
        break;
    }

    return false;
  }
예제 #5
0
 @Override
 public void onDestroy() {
   mManager = null;
   mBuilder = null;
   LogUtil.v(TAG, "Finishing service");
   super.onDestroy();
 }
예제 #6
0
  @Nullable
  private String refreshToken(OpengurApp app) {
    try {
      OAuthResponse response =
          ApiClient.getService()
              .refreshToken(
                  ApiClient.CLIENT_ID,
                  ApiClient.CLIENT_SECRET,
                  app.getUser().getRefreshToken(),
                  "refresh_token");

      if (!TextUtils.isEmpty(response.access_token) && !TextUtils.isEmpty(response.refresh_token)) {
        app.getUser().setTokens(response.access_token, response.refresh_token, response.expires_in);
        app.getSql()
            .updateUserTokens(response.access_token, response.refresh_token, response.expires_in);
        return response.access_token;
      }

      app.onLogout();
      return null;
    } catch (RetrofitError error) {
      LogUtil.e(TAG, "Error while refreshing token, logging out user", error);
      app.onLogout();
    }

    return null;
  }
예제 #7
0
  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Response response = chain.proceed(request);

    if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED
        || response.code() == HttpURLConnection.HTTP_FORBIDDEN) {
      String token = ApiClient.getAccessToken();

      if (!TextUtils.isEmpty(token)) {
        LogUtil.v(TAG, "Token is no longer valid");

        synchronized (sLock) {
          String currentToken = ApiClient.getAccessToken();

          // Check if our current token has been updated, if it hasn't fetch a new one.
          if (!TextUtils.isEmpty(currentToken) && currentToken.equals(token)) {
            ApiClient.setAccessToken(refreshToken(OpengurApp.getInstance()));
          }
        }

        if (!TextUtils.isEmpty(ApiClient.getAccessToken())) {
          Request newRequest =
              request
                  .newBuilder()
                  .removeHeader(ApiClient.AUTHORIZATION_HEADER)
                  .addHeader(ApiClient.AUTHORIZATION_HEADER, "Bearer " + ApiClient.getAccessToken())
                  .build();

          return chain.proceed(newRequest);
        }
      } else {
        LogUtil.w(TAG, "Received unauthorized status from API but no access token present... wat?");
      }
    }

    return response;
  }
예제 #8
0
  @Override
  protected void onHandleIntent(Intent intent) {
    String filePath = intent.getStringExtra(KEY_FILE);
    String url = intent.getStringExtra(KEY_URL);

    if (TextUtils.isEmpty(filePath) && TextUtils.isEmpty(url)) {
      LogUtil.w(TAG, "Nothing passed to upload, bailing");
      return;
    }

    String title = intent.getStringExtra(KEY_TITLE);
    String desc = intent.getStringExtra(KEY_DESC);
    mNotificationId = intent.getIntExtra(KEY_NOTIF_ID, -1);

    if (!TextUtils.isEmpty(filePath)) {
      uploadPhoto(title, desc, filePath);
    } else {
      uploadLink(title, desc, url);
    }
  }
예제 #9
0
  public static ImgurMessage createMessage(String message, int senderId) {
    JSONObject json = new JSONObject();
    long currentTime = System.currentTimeMillis() / DateUtils.SECOND_IN_MILLIS;

    try {
      json.put(KEY_SENDER_ID, senderId);
      json.put(KEY_BODY, message);
      json.put(KEY_ID, String.valueOf(currentTime));
      json.put(KEY_DATE, currentTime);
      json.put(KEY_IS_SENDING, true);
    } catch (JSONException ex) {
      LogUtil.e("ImgurMessage", "Error creating json object", ex);
      json = null;
    }

    if (json != null) {
      return new ImgurMessage(json);
    }

    return null;
  }
예제 #10
0
  public ImgurMessage(JSONObject json) {
    super(json);

    try {
      if (!json.isNull(KEY_BODY)) {
        mBody = json.getString(KEY_BODY);
      }

      if (!json.isNull(KEY_SENDER_ID)) {
        mSenderId = json.getInt(KEY_SENDER_ID);
      }

      if (!json.isNull(KEY_FROM)) {
        mFrom = json.getString(KEY_FROM);
      }

      if (!json.isNull(KEY_IS_SENDING)) {
        mIsSending = json.getBoolean(KEY_IS_SENDING);
      }
    } catch (JSONException ex) {
      LogUtil.e(TAG, "Error Decoding JSON", ex);
    }
  }
예제 #11
0
  private void uploadPhoto(
      @Nullable String title, @Nullable String description, @NonNull String filePath) {
    final File file = new File(filePath);

    if (!FileUtil.isFileValid(file)) {
      LogUtil.w(TAG, "File is invalid, bailing");
      return;
    }

    LogUtil.v(TAG, "Received File to upload");
    ApiClient client = new ApiClient(Endpoints.UPLOAD.getUrl(), ApiClient.HttpRequest.POST);
    MediaType type;

    if (file.getAbsolutePath().endsWith("png")) {
      type = MediaType.parse("image/png");
    } else if (file.getAbsolutePath().endsWith("gif")) {
      type = MediaType.parse("image/gif");
    } else {
      type = MediaType.parse("image/jpeg");
    }

    MultipartBuilder builder =
        new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addPart(
                Headers.of("Content-Disposition", "form-data; name=\"image\""),
                new ProgressRequestBody(file, type, this));

    builder.addPart(
        Headers.of("Content-Disposition", "form-data; name=\"type\""),
        RequestBody.create(null, "file"));

    if (!TextUtils.isEmpty(title)) {
      builder.addPart(
          Headers.of("Content-Disposition", "form-data; name=\"title\""),
          RequestBody.create(null, title));
    }

    if (!TextUtils.isEmpty(description)) {
      builder.addPart(
          Headers.of("Content-Disposition", "form-data; name=\"description\""),
          RequestBody.create(null, description));
    }

    RequestBody body = builder.build();

    try {
      if (mNotificationId <= 0) mNotificationId = file.hashCode();
      onUploadStarted();
      JSONObject json = client.doWork(body);
      int status = json.getInt(ApiClient.KEY_STATUS);

      if (status == ApiClient.STATUS_OK) {
        handleResponse(json.getJSONObject(ApiClient.KEY_DATA));
      } else {
        onUploadFailed(title, description, filePath, true);
      }
    } catch (IOException | JSONException e) {
      LogUtil.e(TAG, "Error uploading file", e);
      onUploadFailed(title, description, filePath, true);
    }
  }