Sumbitting gif and video posts is now available.

This commit is contained in:
Alex Ning 2019-07-14 21:29:10 +08:00
parent 9d1e53b585
commit e0212985f8
13 changed files with 657 additions and 26 deletions

Binary file not shown.

Binary file not shown.

View File

@ -19,6 +19,11 @@
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/AppTheme" android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"> android:usesCleartextTraffic="true">
<activity
android:name=".PostVideoActivity"
android:label="@string/post_video_activity_label"
android:parentActivityName=".MainActivity"
android:windowSoftInputMode="adjustResize" />
<activity <activity
android:name=".PostImageActivity" android:name=".PostImageActivity"
android:label="@string/post_image_activity_label" android:label="@string/post_image_activity_label"

View File

@ -21,4 +21,5 @@ interface AppComponent {
void inject(SubscribedSubredditsListingFragment subscribedSubredditsListingFragment); void inject(SubscribedSubredditsListingFragment subscribedSubredditsListingFragment);
void inject(PostLinkActivity postLinkActivity); void inject(PostLinkActivity postLinkActivity);
void inject(PostImageActivity postImageActivity); void inject(PostImageActivity postImageActivity);
void inject(PostVideoActivity postVideoActivity);
} }

View File

@ -49,6 +49,15 @@ class AppModule {
.build(); .build();
} }
@Provides @Named("upload_video")
@Singleton
Retrofit provideUploadVideoRetrofit() {
return new Retrofit.Builder()
.baseUrl(RedditUtils.API_UPLOAD_VIDEO_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
}
@Provides @Provides
@Singleton @Singleton
OkHttpClient provideOkHttpClient(@Named("no_oauth") Retrofit retrofit, @Named("auth_info") SharedPreferences sharedPreferences) { OkHttpClient provideOkHttpClient(@Named("no_oauth") Retrofit retrofit, @Named("auth_info") SharedPreferences sharedPreferences) {

View File

@ -11,7 +11,6 @@ import android.view.View;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.ActionBarDrawerToggle;
@ -256,7 +255,8 @@ public class MainActivity extends AppCompatActivity {
}); });
videoTypeLinearLayout.setOnClickListener(view -> { videoTypeLinearLayout.setOnClickListener(view -> {
Toast.makeText(this, "Not implemented yet", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(MainActivity.this, PostVideoActivity.class);
startActivity(intent);
dialog.dismiss(); dialog.dismiss();
}); });

View File

@ -163,7 +163,7 @@ public class PostImageActivity extends AppCompatActivity {
selectFromLibraryFab.setOnClickListener(view -> { selectFromLibraryFab.setOnClickListener(view -> {
Intent intent = new Intent(); Intent intent = new Intent();
intent.setType("image/*"); intent.setType("image/*");
intent.setAction(Intent.ACTION_OPEN_DOCUMENT); intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,getResources().getString(R.string.select_from_gallery)), PICK_IMAGE_REQUEST_CODE); startActivityForResult(Intent.createChooser(intent,getResources().getString(R.string.select_from_gallery)), PICK_IMAGE_REQUEST_CODE);
}); });

View File

@ -0,0 +1,328 @@
package ml.docilealligator.infinityforreddit;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
public class PostVideoActivity extends AppCompatActivity {
static final String EXTRA_SUBREDDIT_NAME = "ESN";
static final String EXTRA_SUBREDDIT_ICON = "ESI";
private static final String SUBREDDIT_NAME_STATE = "SNS";
private static final String SUBREDDIT_ICON_STATE = "SIS";
private static final String SUBREDDIT_SELECTED_STATE = "SSS";
private static final String SUBREDDIT_IS_USER_STATE = "SIUS";
private static final String VIDEO_URI_STATE = "IUS";
private static final int SUBREDDIT_SELECTION_REQUEST_CODE = 0;
private static final int PICK_VIDEO_REQUEST_CODE = 1;
@BindView(R.id.coordinator_layout_post_video_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.subreddit_icon_gif_image_view_post_video_activity) GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_post_video_activity) TextView subreditNameTextView;
@BindView(R.id.rules_button_post_video_activity) Button rulesButton;
@BindView(R.id.post_title_edit_text_post_video_activity) EditText titleEditText;
@BindView(R.id.select_video_constraint_layout_post_video_activity) ConstraintLayout constraintLayout;
@BindView(R.id.capture_fab_post_video_activity) FloatingActionButton captureFab;
@BindView(R.id.select_from_library_fab_post_video_activity) FloatingActionButton selectFromLibraryFab;
@BindView(R.id.select_again_text_view_post_video_activity) TextView selectAgainTextView;
@BindView(R.id.image_view_post_video_activity) ImageView imageView;
private String iconUrl;
private String subredditName;
private boolean subredditSelected = false;
private boolean subredditIsUser;
private Uri videoUri;
private RequestManager mGlide;
private Locale mLocale;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("upload_media")
Retrofit mUploadMediaRetrofit;
@Inject
@Named("upload_video")
Retrofit mUploadVideoRetrofit;
@Inject
@Named("user_info")
SharedPreferences mUserInfoSharedPreferences;
@Inject
@Named("auth_info")
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_video);
ButterKnife.bind(this);
((Infinity) getApplication()).getmAppComponent().inject(this);
ActionBar actionBar = getSupportActionBar();
Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
actionBar.setHomeAsUpIndicator(upArrow);
mGlide = Glide.with(this);
mLocale = getResources().getConfiguration().locale;
if(savedInstanceState != null) {
subredditName = savedInstanceState.getString(SUBREDDIT_NAME_STATE);
iconUrl = savedInstanceState.getString(SUBREDDIT_ICON_STATE);
subredditSelected = savedInstanceState.getBoolean(SUBREDDIT_SELECTED_STATE);
subredditIsUser = savedInstanceState.getBoolean(SUBREDDIT_IS_USER_STATE);
if(savedInstanceState.getString(VIDEO_URI_STATE) != null) {
videoUri = Uri.parse(savedInstanceState.getString(VIDEO_URI_STATE));
loadImage();
}
if(subredditName != null) {
subreditNameTextView.setText(subredditName);
}
if(iconUrl != null && !iconUrl.equals("")) {
mGlide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(iconGifImageView);
} else {
mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(iconGifImageView);
}
} else {
if(getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
subredditName = getIntent().getExtras().getString(EXTRA_SUBREDDIT_NAME);
iconUrl = getIntent().getExtras().getString(EXTRA_SUBREDDIT_ICON);
subreditNameTextView.setText(subredditName);
} else {
mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(iconGifImageView);
}
}
iconGifImageView.setOnClickListener(view -> {
Intent intent = new Intent(this, SubredditSelectionActivity.class);
startActivityForResult(intent, SUBREDDIT_SELECTION_REQUEST_CODE);
});
subreditNameTextView.setOnClickListener(view -> {
Intent intent = new Intent(this, SubredditSelectionActivity.class);
startActivityForResult(intent, SUBREDDIT_SELECTION_REQUEST_CODE);
});
captureFab.setOnClickListener(view -> {
});
selectFromLibraryFab.setOnClickListener(view -> {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,getResources().getString(R.string.select_from_gallery)), PICK_VIDEO_REQUEST_CODE);
});
selectAgainTextView.setOnClickListener(view -> {
videoUri = null;
selectAgainTextView.setVisibility(View.GONE);
mGlide.clear(imageView);
constraintLayout.setVisibility(View.VISIBLE);
});
}
private void loadImage() {
constraintLayout.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
selectAgainTextView.setVisibility(View.VISIBLE);
mGlide.asBitmap().load(videoUri).into(imageView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.post_image_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_send_post_image_activity:
if(!subredditSelected) {
Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
return true;
}
if(videoUri == null) {
Snackbar.make(coordinatorLayout, R.string.select_an_image, Snackbar.LENGTH_SHORT).show();
return true;
}
item.setEnabled(false);
item.getIcon().setAlpha(130);
Snackbar postingSnackbar = Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_INDEFINITE);
postingSnackbar.show();
String subredditName;
if(subredditIsUser) {
subredditName = "u_" + subreditNameTextView.getText().toString();
} else {
subredditName = subreditNameTextView.getText().toString();
}
try (ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(videoUri, "r")) {
FileInputStream in = new FileInputStream(pfd.getFileDescriptor());
byte[] buffer;
buffer = new byte[in.available()];
while (in.read(buffer) != -1);
Glide.with(this)
.asBitmap()
.load(videoUri)
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
SubmitPost.submitVideoPost(mOauthRetrofit, mUploadMediaRetrofit, mUploadVideoRetrofit,
sharedPreferences, mLocale, subredditName, titleEditText.getText().toString(),
buffer, getContentResolver().getType(videoUri), resource, false,
new SubmitPost.SubmitPostListener() {
@Override
public void submitSuccessful(Post post) {
Toast.makeText(PostVideoActivity.this, R.string.video_is_processing, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(PostVideoActivity.this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY,
mUserInfoSharedPreferences.getString(SharedPreferencesUtils.USER_KEY, ""));
startActivity(intent);
finish();
}
@Override
public void submitFailed(@Nullable String errorMessage) {
postingSnackbar.dismiss();
item.setEnabled(true);
item.getIcon().setAlpha(255);
if (errorMessage == null || errorMessage.equals("")) {
Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(coordinatorLayout, errorMessage, Snackbar.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
} catch (IOException e) {
e.printStackTrace();
Snackbar.make(coordinatorLayout, R.string.error_processing_video, Snackbar.LENGTH_SHORT).show();
}
return true;
}
return false;
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SUBREDDIT_NAME_STATE, subredditName);
outState.putString(SUBREDDIT_ICON_STATE, iconUrl);
outState.putBoolean(SUBREDDIT_SELECTED_STATE, subredditSelected);
outState.putBoolean(SUBREDDIT_IS_USER_STATE, subredditIsUser);
if(videoUri != null) {
outState.putString(VIDEO_URI_STATE, videoUri.toString());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
subredditName = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_NAME_KEY);
iconUrl = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_ICON_URL_KEY);
subredditSelected = true;
subredditIsUser = data.getExtras().getBoolean(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_IS_USER_KEY);
subreditNameTextView.setTextColor(getResources().getColor(R.color.primaryTextColor));
subreditNameTextView.setText(subredditName);
if(!iconUrl.equals("")) {
mGlide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(iconGifImageView);
} else {
mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(iconGifImageView);
}
}
} else if(requestCode == PICK_VIDEO_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if(data == null) {
Snackbar.make(coordinatorLayout, R.string.error_getting_image, Snackbar.LENGTH_SHORT).show();
return;
}
videoUri = data.getData();
loadImage();
}
}
}
}

View File

@ -17,6 +17,7 @@ public class RedditUtils {
static final String OAUTH_API_BASE_URI = "https://oauth.reddit.com"; static final String OAUTH_API_BASE_URI = "https://oauth.reddit.com";
static final String API_BASE_URI = "https://www.reddit.com"; static final String API_BASE_URI = "https://www.reddit.com";
static final String API_UPLOAD_MEDIA_URI = "https://reddit-uploaded-media.s3-accelerate.amazonaws.com"; static final String API_UPLOAD_MEDIA_URI = "https://reddit-uploaded-media.s3-accelerate.amazonaws.com";
static final String API_UPLOAD_VIDEO_URI = "https://reddit-uploaded-video.s3-accelerate.amazonaws.com";
static final String CLIENT_ID_KEY = "client_id"; static final String CLIENT_ID_KEY = "client_id";
static final String CLIENT_ID = ""; static final String CLIENT_ID = "";
@ -57,6 +58,7 @@ public class RedditUtils {
static final String RETURN_RTJSON_KEY = "return_rtjson"; static final String RETURN_RTJSON_KEY = "return_rtjson";
static final String TEXT_KEY = "text"; static final String TEXT_KEY = "text";
static final String URL_KEY = "url"; static final String URL_KEY = "url";
static final String VIDEO_POSTER_URL_KEY = "video_poster_url";
static final String THING_ID_KEY = "thing_id"; static final String THING_ID_KEY = "thing_id";
static final String SR_KEY = "sr"; static final String SR_KEY = "sr";
@ -67,6 +69,8 @@ public class RedditUtils {
static final String KIND_SELF = "self"; static final String KIND_SELF = "self";
static final String KIND_LINK = "link"; static final String KIND_LINK = "link";
static final String KIND_IMAGE = "image"; static final String KIND_IMAGE = "image";
static final String KIND_VIDEO = "video";
static final String KIND_VIDEOGIF = "videogif";
static final String FILEPATH_KEY = "filepath"; static final String FILEPATH_KEY = "filepath";
static final String MIMETYPE_KEY = "mimetype"; static final String MIMETYPE_KEY = "mimetype";

View File

@ -36,9 +36,140 @@ class SubmitPost {
void submitFailed(@Nullable String errorMessage); void submitFailed(@Nullable String errorMessage);
} }
private interface UploadImageListener {
void uploaded(String imageUrl);
void uploadFailed(@Nullable String errorMessage);
}
static void submitTextOrLinkPost(Retrofit oauthRetrofit, SharedPreferences authInfoSharedPreferences, static void submitTextOrLinkPost(Retrofit oauthRetrofit, SharedPreferences authInfoSharedPreferences,
Locale locale, String subredditName, String title, String content, boolean isNSFW, Locale locale, String subredditName, String title, String content, boolean isNSFW,
String kind, SubmitPostListener submitPostListener) { String kind, SubmitPostListener submitPostListener) {
submitPost(oauthRetrofit, authInfoSharedPreferences, locale, subredditName, title, content,
isNSFW, kind, null, submitPostListener);
}
static void submitImagePost(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit,
SharedPreferences authInfoSharedPreferences, Locale locale,
String subredditName, String title, Bitmap image, boolean isNSFW,
SubmitPostListener submitPostListener) {
uploadImage(oauthRetrofit, uploadMediaRetrofit, authInfoSharedPreferences, image,
new UploadImageListener() {
@Override
public void uploaded(String imageUrl) {
submitPost(oauthRetrofit, authInfoSharedPreferences, locale,
subredditName, title, imageUrl, isNSFW, RedditUtils.KIND_IMAGE,
null, submitPostListener);
}
@Override
public void uploadFailed(@Nullable String errorMessage) {
submitPostListener.submitFailed(errorMessage);
}
});
}
static void submitVideoPost(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit,
Retrofit uploadVideoRetrofit, SharedPreferences authInfoSharedPreferences,
Locale locale, String subredditName, String title, byte[] buffer, String mimeType,
Bitmap posterBitmap, boolean isNSFW, SubmitPostListener submitPostListener) {
RedditAPI api = oauthRetrofit.create(RedditAPI.class);
String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, "");
String fileType = mimeType.substring(mimeType.indexOf("/") + 1);
Map<String, String> uploadImageParams = new HashMap<>();
uploadImageParams.put(RedditUtils.FILEPATH_KEY, "post_video." + fileType);
uploadImageParams.put(RedditUtils.MIMETYPE_KEY, mimeType);
Log.i("map", RedditUtils.getOAuthHeader(accessToken).toString());
Call<String> uploadImageCall = api.uploadImage(RedditUtils.getOAuthHeader(accessToken), uploadImageParams);
uploadImageCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
new ParseJSONResponseFromAWSAsyncTask(response.body(), new ParseJSONResponseFromAWSAsyncTask.ParseJSONResponseFromAWSListener() {
@Override
public void parseSuccessful(Map<String, RequestBody> nameValuePairsMap) {
RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), buffer);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", "post_video." + fileType, fileBody);
RedditAPI uploadVideoToAWSApi;
if(fileType.equals("gif")) {
uploadVideoToAWSApi = uploadMediaRetrofit.create(RedditAPI.class);
} else {
uploadVideoToAWSApi = uploadVideoRetrofit.create(RedditAPI.class);
}
Call<String> uploadMediaToAWS = uploadVideoToAWSApi.uploadMediaToAWS(nameValuePairsMap, fileToUpload);
uploadMediaToAWS.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
Log.i("responsesese", "aws" + response.body());
if(response.isSuccessful()) {
new ParseXMLReponseFromAWSAsyncTask(response.body(), new ParseXMLReponseFromAWSAsyncTask.ParseXMLResponseFromAWSListener() {
@Override
public void parseSuccessful(String url) {
uploadImage(oauthRetrofit, uploadMediaRetrofit, authInfoSharedPreferences,
posterBitmap, new UploadImageListener() {
@Override
public void uploaded(String imageUrl) {
if(fileType.equals("gif")) {
submitPost(oauthRetrofit, authInfoSharedPreferences, locale,
subredditName, title, url, isNSFW, RedditUtils.KIND_VIDEOGIF,
imageUrl, submitPostListener);
} else {
submitPost(oauthRetrofit, authInfoSharedPreferences, locale,
subredditName, title, url, isNSFW, RedditUtils.KIND_VIDEO,
imageUrl, submitPostListener);
}
}
@Override
public void uploadFailed(@Nullable String errorMessage) {
submitPostListener.submitFailed(errorMessage);
}
});
}
@Override
public void parseFailed() {
submitPostListener.submitFailed(null);
}
}).execute();
} else {
submitPostListener.submitFailed("Error: " + response.code());
}
}
@Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
Log.i("asfasdfsd", "failedddddddddd" + t.getMessage());
submitPostListener.submitFailed(t.getMessage());
}
});
}
@Override
public void parseFailed() {
submitPostListener.submitFailed("Parse from aws failed");
}
}).execute();
} else {
submitPostListener.submitFailed(response.message());
}
Log.i("image", "dddd" + response.code());
}
@Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
submitPostListener.submitFailed(t.getMessage());
}
});
}
private static void submitPost(Retrofit oauthRetrofit, SharedPreferences authInfoSharedPreferences,
Locale locale, String subredditName, String title, String content, boolean isNSFW,
String kind, @Nullable String posterUrl, SubmitPostListener submitPostListener) {
RedditAPI api = oauthRetrofit.create(RedditAPI.class); RedditAPI api = oauthRetrofit.create(RedditAPI.class);
String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, "");
@ -47,10 +178,23 @@ class SubmitPost {
params.put(RedditUtils.SR_KEY, subredditName); params.put(RedditUtils.SR_KEY, subredditName);
params.put(RedditUtils.TITLE_KEY, title); params.put(RedditUtils.TITLE_KEY, title);
params.put(RedditUtils.KIND_KEY, kind); params.put(RedditUtils.KIND_KEY, kind);
if(kind.equals(RedditUtils.KIND_SELF)) { switch (kind) {
params.put(RedditUtils.TEXT_KEY, content); case RedditUtils.KIND_SELF:
} else if(kind.equals(RedditUtils.KIND_LINK) || kind.equals(RedditUtils.KIND_IMAGE)) { params.put(RedditUtils.TEXT_KEY, content);
params.put(RedditUtils.URL_KEY, content); break;
case RedditUtils.KIND_LINK:
case RedditUtils.KIND_IMAGE:
params.put(RedditUtils.URL_KEY, content);
break;
case RedditUtils.KIND_VIDEOGIF:
params.put(RedditUtils.KIND_KEY, RedditUtils.KIND_IMAGE);
params.put(RedditUtils.URL_KEY, content);
params.put(RedditUtils.VIDEO_POSTER_URL_KEY, posterUrl);
break;
case RedditUtils.KIND_VIDEO:
params.put(RedditUtils.URL_KEY, content);
params.put(RedditUtils.VIDEO_POSTER_URL_KEY, posterUrl);
break;
} }
params.put(RedditUtils.NSFW_KEY, Boolean.toString(isNSFW)); params.put(RedditUtils.NSFW_KEY, Boolean.toString(isNSFW));
@ -81,15 +225,14 @@ class SubmitPost {
}); });
} }
static void submitImagePost(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit, private static void uploadImage(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit,
SharedPreferences authInfoSharedPreferences, Locale locale, SharedPreferences authInfoSharedPreferences, Bitmap image,
String subredditName, String title, Bitmap image, boolean isNSFW, UploadImageListener uploadImageListener) {
SubmitPostListener submitPostListener) {
RedditAPI api = oauthRetrofit.create(RedditAPI.class); RedditAPI api = oauthRetrofit.create(RedditAPI.class);
String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, "");
Map<String, String> uploadImageParams = new HashMap<>(); Map<String, String> uploadImageParams = new HashMap<>();
uploadImageParams.put(RedditUtils.FILEPATH_KEY, "tetestst.jpg"); uploadImageParams.put(RedditUtils.FILEPATH_KEY, "post_image.jpg");
uploadImageParams.put(RedditUtils.MIMETYPE_KEY, "image/jpeg"); uploadImageParams.put(RedditUtils.MIMETYPE_KEY, "image/jpeg");
Log.i("map", RedditUtils.getOAuthHeader(accessToken).toString()); Log.i("map", RedditUtils.getOAuthHeader(accessToken).toString());
@ -101,13 +244,12 @@ class SubmitPost {
new ParseJSONResponseFromAWSAsyncTask(response.body(), new ParseJSONResponseFromAWSAsyncTask.ParseJSONResponseFromAWSListener() { new ParseJSONResponseFromAWSAsyncTask(response.body(), new ParseJSONResponseFromAWSAsyncTask.ParseJSONResponseFromAWSListener() {
@Override @Override
public void parseSuccessful(Map<String, RequestBody> nameValuePairsMap) { public void parseSuccessful(Map<String, RequestBody> nameValuePairsMap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream(); ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream); image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray(); byte[] byteArray = stream.toByteArray();
RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), byteArray); RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), byteArray);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", "testing.jpg", fileBody); MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", "post_image.jpg", fileBody);
RedditAPI uploadMediaToAWSApi = uploadMediaRetrofit.create(RedditAPI.class); RedditAPI uploadMediaToAWSApi = uploadMediaRetrofit.create(RedditAPI.class);
Call<String> uploadMediaToAWS = uploadMediaToAWSApi.uploadMediaToAWS(nameValuePairsMap, fileToUpload); Call<String> uploadMediaToAWS = uploadMediaToAWSApi.uploadMediaToAWS(nameValuePairsMap, fileToUpload);
@ -119,45 +261,43 @@ class SubmitPost {
if(response.isSuccessful()) { if(response.isSuccessful()) {
new ParseXMLReponseFromAWSAsyncTask(response.body(), new ParseXMLReponseFromAWSAsyncTask.ParseXMLResponseFromAWSListener() { new ParseXMLReponseFromAWSAsyncTask(response.body(), new ParseXMLReponseFromAWSAsyncTask.ParseXMLResponseFromAWSListener() {
@Override @Override
public void parseSuccessful(String imageUrl) { public void parseSuccessful(String url) {
submitTextOrLinkPost(oauthRetrofit, authInfoSharedPreferences, locale, uploadImageListener.uploaded(url);
subredditName, title, imageUrl, isNSFW, RedditUtils.KIND_IMAGE,
submitPostListener);
} }
@Override @Override
public void parseFailed() { public void parseFailed() {
submitPostListener.submitFailed(null); uploadImageListener.uploadFailed(null);
} }
}).execute(); }).execute();
} else { } else {
Log.i("asfasdfsd", "failedddddddddd" + response.code()); Log.i("asfasdfsd", "failedddddddddd" + response.code());
submitPostListener.submitFailed("Error: " + response.code()); uploadImageListener.uploadFailed("Error: " + response.code());
} }
} }
@Override @Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
Log.i("asfasdfsd", "failedddddddddd" + t.getMessage()); Log.i("asfasdfsd", "failedddddddddd" + t.getMessage());
submitPostListener.submitFailed(t.getMessage()); uploadImageListener.uploadFailed(t.getMessage());
} }
}); });
} }
@Override @Override
public void parseFailed() { public void parseFailed() {
submitPostListener.submitFailed("Parse from aws failed"); uploadImageListener.uploadFailed("Parse from aws failed");
} }
}).execute(); }).execute();
} else { } else {
submitPostListener.submitFailed(response.message()); uploadImageListener.uploadFailed(response.message());
} }
Log.i("image", "dddd" + response.body()); Log.i("image", "dddd" + response.body());
} }
@Override @Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
submitPostListener.submitFailed(t.getMessage()); uploadImageListener.uploadFailed(t.getMessage());
} }
}); });
} }
@ -213,7 +353,7 @@ class SubmitPost {
private static class ParseXMLReponseFromAWSAsyncTask extends AsyncTask<Void, Void, Void> { private static class ParseXMLReponseFromAWSAsyncTask extends AsyncTask<Void, Void, Void> {
interface ParseXMLResponseFromAWSListener { interface ParseXMLResponseFromAWSListener {
void parseSuccessful(String imageUrl); void parseSuccessful(String url);
void parseFailed(); void parseFailed();
} }
@ -293,7 +433,7 @@ class SubmitPost {
return; return;
} }
if(!kind.equals(RedditUtils.KIND_IMAGE)) { if(!kind.equals(RedditUtils.KIND_IMAGE) && !kind.equals(RedditUtils.KIND_VIDEO) && !kind.equals(RedditUtils.KIND_VIDEOGIF)) {
String postId = responseObject.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.ID_KEY); String postId = responseObject.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.ID_KEY);
RedditAPI api = oauthRetrofit.create(RedditAPI.class); RedditAPI api = oauthRetrofit.create(RedditAPI.class);

View File

@ -0,0 +1,130 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/coordinator_layout_post_video_activity"
tools:context=".PostImageActivity">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:paddingStart="16dp"
android:paddingEnd="16dp">
<pl.droidsonroids.gif.GifImageView
android:id="@+id/subreddit_icon_gif_image_view_post_video_activity"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentStart="true"
android:layout_centerVertical="true" />
<TextView
android:id="@+id/subreddit_name_text_view_post_video_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toStartOf="@id/rules_button_post_video_activity"
android:layout_toEndOf="@id/subreddit_icon_gif_image_view_post_video_activity"
android:layout_centerVertical="true"
android:layout_marginStart="32dp"
android:layout_marginEnd="16dp"
android:text="@string/choose_a_subreddit" />
<Button
android:id="@+id/rules_button_post_video_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:text="@string/rules"
android:textColor="@color/colorAccent" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/dividerColor" />
<EditText
android:id="@+id/post_title_edit_text_post_video_activity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:padding="16dp"
android:hint="@string/post_title_hint"
android:inputType="textCapSentences|textMultiLine"
android:textSize="18sp"
android:background="#00000000"
android:textColor="@color/primaryTextColor" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/dividerColor" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/select_video_constraint_layout_post_video_activity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="32dp">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/capture_fab_post_video_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_outline_add_a_photo_24px"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="@+id/select_from_library_fab_post_video_activity"
app:layout_constraintHorizontal_chainStyle="spread" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/select_from_library_fab_post_video_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_outline_select_photo_24px"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="@+id/capture_fab_post_video_activity"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_chainStyle="spread" />
</androidx.constraintlayout.widget.ConstraintLayout>
<TextView
android:id="@+id/select_again_text_view_post_video_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="@string/select_again"
android:textColor="@color/colorAccent"
android:visibility="gone" />
<ImageView
android:id="@+id/image_view_post_video_activity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitStart"
android:adjustViewBounds="true"
android:visibility="gone" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_send_post_video_activity"
android:orderInCategory="1"
android:title="@string/action_send"
android:icon="@drawable/ic_send_white_24dp"
app:showAsAction="ifRoom" />
</menu>

View File

@ -8,6 +8,7 @@
<string name="subreddit_selection_activity_label">Select a Subreddit</string> <string name="subreddit_selection_activity_label">Select a Subreddit</string>
<string name="post_link_activity_label">Link Post</string> <string name="post_link_activity_label">Link Post</string>
<string name="post_image_activity_label">Image Post</string> <string name="post_image_activity_label">Image Post</string>
<string name="post_video_activity_label">Video Post</string>
<string name="navigation_drawer_open">Open navigation drawer</string> <string name="navigation_drawer_open">Open navigation drawer</string>
<string name="navigation_drawer_close">Close navigation drawer</string> <string name="navigation_drawer_close">Close navigation drawer</string>
@ -86,6 +87,7 @@
<string name="select_an_image">Please select an image first</string> <string name="select_an_image">Please select an image first</string>
<string name="posting">Posting</string> <string name="posting">Posting</string>
<string name="post_failed">Could not post it</string> <string name="post_failed">Could not post it</string>
<string name="error_processing_video">Error processing this video</string>
<string name="download_completed">Download completed</string> <string name="download_completed">Download completed</string>
<string name="download_failed">Download Failed</string> <string name="download_failed">Download Failed</string>
@ -114,4 +116,6 @@
<string name="select_from_gallery">Select a picture</string> <string name="select_from_gallery">Select a picture</string>
<string name="select_again">Select again</string> <string name="select_again">Select again</string>
<string name="error_getting_image">Error getting the image</string> <string name="error_getting_image">Error getting the image</string>
<string name="video_is_processing">Video is processing. Please wait.</string>
</resources> </resources>