Sharing is now fully implemented

This commit is contained in:
staccatomamba
2017-11-04 19:46:17 +01:00
parent cf5873e47f
commit b90d266d9b
12 changed files with 130 additions and 186 deletions

View File

@@ -23,4 +23,6 @@ public interface AppPrefsConstants {
String USER_PASSWORD = "user_password";
String USER_NAME = "user_name";
String VERIFY_CHAT_CODE_ERROR_MESSAGE = "verify_chat_code_error_message";
String IS_COMING_FROM_SHARING_ACTIVITY = "is_coming_from_sharing_activity";
String PATH_TO_FILE_TO_SHARE = "path_to_file_to_share";
}

View File

@@ -76,10 +76,6 @@ public class HandleMessagesService extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage) {
InjectionHelper.getMessagingComponent(this).inject(HandleMessagesService.this);
// if (mLoggedOutUtils.checkLoggedOutPrefs()) {
// return;
// }
customizeNotification(remoteMessage.getData());
}
@@ -244,6 +240,7 @@ public class HandleMessagesService extends FirebaseMessagingService {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
return null;
}
Intent replyIntent = ReplyNotificationReceiver.createReplyIntent(context, bundle, noOfUsers, groupId);
PendingIntent replyPendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
@@ -283,9 +280,11 @@ public class HandleMessagesService extends FirebaseMessagingService {
public static CharSequence getReplyMessage(Intent intent) {
Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
if (remoteInput != null) {
return remoteInput.getCharSequence(Constants.KEY_TEXT_REPLY);
}
return null;
}
}

View File

@@ -55,6 +55,20 @@ public class AppPrefsModule {
return new BooleanPreference(sharedPreferences, AppPrefsConstants.SAVE_PASSWORD);
}
@Provides
@ApplicationScope
@Named(AppPrefsConstants.IS_COMING_FROM_SHARING_ACTIVITY)
BooleanPreference provideIsComingFromSharingActivity(@AppPrefs SecurePreferences sharedPreferences) {
return new BooleanPreference(sharedPreferences, AppPrefsConstants.IS_COMING_FROM_SHARING_ACTIVITY);
}
@Provides
@ApplicationScope
@Named(AppPrefsConstants.PATH_TO_FILE_TO_SHARE)
StringPreference providePathToFileToShare(@AppPrefs SecurePreferences sharedPreferences) {
return new StringPreference(sharedPreferences, AppPrefsConstants.PATH_TO_FILE_TO_SHARE);
}
@Provides
@ApplicationScope
@Named(AppPrefsConstants.VERIFY_CHAT_CODE_ERROR_MESSAGE)

View File

@@ -97,6 +97,12 @@ public interface ApplicationComponent {
@Named(AppPrefsConstants.USER_PASSWORD)
StringPreference providePassword();
@Named(AppPrefsConstants.PATH_TO_FILE_TO_SHARE)
StringPreference providePathToFileToShare();
@Named(AppPrefsConstants.IS_COMING_FROM_SHARING_ACTIVITY)
BooleanPreference provideIsComingFromSharingActivity();
NotificationManager provideNotificationManager();
GroupRealmRepository provideGroupRealmRepository();

View File

@@ -6,6 +6,7 @@ import de.beyondsoft.ownchat.data.events.InvalidTokenEvent;
import de.beyondsoft.ownchat.data.events.LogoutDirectlyEvent;
import de.beyondsoft.ownchat.data.prefs.BooleanPreference;
import de.beyondsoft.ownchat.data.prefs.LongPreference;
import de.beyondsoft.ownchat.data.prefs.StringPreference;
import de.beyondsoft.ownchat.di.InjectionHelper;
import de.beyondsoft.ownchat.filepicker.FilePickerBuilder;
import de.beyondsoft.ownchat.filepicker.FilePickerConst;
@@ -16,6 +17,7 @@ import de.beyondsoft.ownchat.page.common.RuntimePermissionActivity;
import de.beyondsoft.ownchat.page.fileconfirmation.FileConfirmationActivity;
import de.beyondsoft.ownchat.page.login.LoginPresenter;
import de.beyondsoft.ownchat.page.main.LogoutNavigation;
import de.beyondsoft.ownchat.page.main.MainActivity;
import de.beyondsoft.ownchat.utils.Constants;
import de.beyondsoft.ownchat.utils.EndlessScrollListener;
import de.beyondsoft.ownchat.utils.FileUtils;
@@ -128,6 +130,14 @@ abstract class BaseChatActivity extends RuntimePermissionActivity implements Cha
@Inject
LoginPresenter mLoginPresenter;
@Inject
@Named(AppPrefsConstants.PATH_TO_FILE_TO_SHARE)
StringPreference mSelectedFilePath;
@Inject
@Named(AppPrefsConstants.IS_COMING_FROM_SHARING_ACTIVITY)
BooleanPreference mIsComingFromSharingActivity;
protected Group mGroup;
protected ChatView.Callback mCallback;
protected EndlessScrollListener mEndlessScrollListener;
@@ -161,6 +171,8 @@ abstract class BaseChatActivity extends RuntimePermissionActivity implements Cha
showLoading();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mKeyboardListener);
}
private void setupRecyclerView() {
@@ -218,6 +230,42 @@ abstract class BaseChatActivity extends RuntimePermissionActivity implements Cha
mBaseChatAdapter.addMessages(messages);
}
private void shareFile(int requestCode) {
mIsComingFromSharingActivity.set(false);
final Uri uri = Uri.parse(mSelectedFilePath.get());
final File file = FileUtils.getFile(this, uri);
String filePath = file.getPath();
mSelectedFilePath.delete();
String test = mSelectedFilePath.get();
if (Build.VERSION.SDK_INT >= 19) {
final int takeFlags = (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
try {
//noinspection WrongConstant
getContentResolver().takePersistableUriPermission(uri, takeFlags);
} catch (Exception e) {
e.printStackTrace();
}
}
if (!mChatPresenter.isAttached()) {
mChatPresenter.attachView(this);
}
Bundle bundle = new Bundle();
bundle.putString(Constants.FILENAME, filePath);
Intent intent = new Intent(this, FileConfirmationActivity.class);
intent.putExtras(bundle);
intent.putExtra(Constants.EXTRA_GROUP, mGroup);
startActivityForResult(intent, 666);
}
@Override
public void showError(@StringRes int errorRes) {
if (mSnackbar == null) {
@@ -247,6 +295,13 @@ abstract class BaseChatActivity extends RuntimePermissionActivity implements Cha
@Override
public void hideMessagesLoading() {
mBaseChatAdapter.setLoading(false);
if(mIsComingFromSharingActivity.get()) {
requestAppPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
R.string.permission_storage_explained,
STORAGE_REQUEST_CODE,
this::shareFile);
}
}
@Override
@@ -568,4 +623,9 @@ abstract class BaseChatActivity extends RuntimePermissionActivity implements Cha
}
}
};
@Override
public void onBackPressed() {
startActivity(new Intent(this, MainActivity.class));
}
}

View File

@@ -102,6 +102,10 @@ public class ChatPresenter extends MVPAbstractPresenter<ChatView> implements Cha
@Named(AppPrefsConstants.UPLOAD_MAX_SIZE)
LongPreference mUploadMaxSizePreference;
@Inject
@Named(AppPrefsConstants.VERIFY_CHAT_CODE_ERROR_MESSAGE)
StringPreference mVerifyChatCodeErrorMessage;
@Inject
RealmProvider mRealmProvider;

View File

@@ -38,8 +38,10 @@ public class SingleChatActivity extends BaseChatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mChatPresenter.attachView(this);
mCallback.resetMessages();
if (getIntent().hasExtra(MESSAGE_ARG)) {
Bundle bundle = getIntent().getBundleExtra(MESSAGE_ARG);
mGroup = new Group();
@@ -53,6 +55,7 @@ public class SingleChatActivity extends BaseChatActivity {
} else {
mCallback.loadMessagesFromServerByGroupId(mGroup.id);
}
mCallback.findGroupById();
} else {
setGroupFromArguments();

View File

@@ -187,6 +187,7 @@ public class ContactsFragment extends BaseFragment
if (TextUtils.isEmpty(mSearchView.getQuery())) {
mSearchView.setIconified(true);
}
startActivity(GroupChatActivity.createIntent(getActivity(), group));
}

View File

@@ -27,10 +27,11 @@ import butterknife.BindView;
import butterknife.ButterKnife;
import de.beyondsoft.ownchat.R;
import de.beyondsoft.ownchat.data.AppPrefsConstants;
import de.beyondsoft.ownchat.data.prefs.BooleanPreference;
import de.beyondsoft.ownchat.data.prefs.LongPreference;
import de.beyondsoft.ownchat.data.prefs.StringPreference;
import de.beyondsoft.ownchat.di.InjectionHelper;
import de.beyondsoft.ownchat.model.Group;
import de.beyondsoft.ownchat.page.chat.BaseChatActivity;
import de.beyondsoft.ownchat.page.chat.GroupChatActivity;
import de.beyondsoft.ownchat.page.chat.SingleChatActivity;
import de.beyondsoft.ownchat.page.fileconfirmation.FileConfirmationActivity;
@@ -65,19 +66,18 @@ public class SharingActivity extends AppCompatActivity implements SharingView, S
@BindView(R.id.chat_toolbar_single_title)
TextView mSingleChatTitleTextView;
@BindView(R.id.chat_toolbar_image_view)
ImageView mChatImageView;
@Inject
@Named(AppPrefsConstants.PATH_TO_FILE_TO_SHARE)
StringPreference mSelectedFilePath;
@BindView(R.id.chat_toolbar_extra_image)
ImageView mExtraImageView;
@Inject
@Named(AppPrefsConstants.IS_COMING_FROM_SHARING_ACTIVITY)
BooleanPreference mIsComingFromSharingActivity;
private SharingView.Callback mCallback;
private SharingContactsAdapter mContactsAdapter;
private RecyclerView.ItemDecoration mHorizontalDividerItemDecoration;
private Snackbar mSnackbar;
private Uri selectedFileUri = null;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -89,9 +89,7 @@ public class SharingActivity extends AppCompatActivity implements SharingView, S
mSharingPresenter.attachView(this);
mHorizontalDividerItemDecoration = new HorizontalDividerItemDecoration.Builder(this).colorResId(R.color.colorFill).build();
mContactsRecyclerView.addItemDecoration(mHorizontalDividerItemDecoration);
mContactsRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).colorResId(R.color.colorFill).build());
mContactsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mContactsAdapter = new SharingContactsAdapter(this, mUserIdPreference.get());
@@ -117,7 +115,8 @@ public class SharingActivity extends AppCompatActivity implements SharingView, S
Uri fileUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (fileUri != null) {
selectedFileUri = fileUri;
mSelectedFilePath.set(fileUri.toString());
mIsComingFromSharingActivity.set(true);
}
}
@@ -140,16 +139,13 @@ public class SharingActivity extends AppCompatActivity implements SharingView, S
}
@Override
public void onConfirmSharingFile(Group contact) {
Bundle bundle = new Bundle();
bundle.putString(Constants.FILENAME, FileUtils.getPath(this, selectedFileUri));
public void onOpenGroupMessage(Group group) {
startActivity(GroupChatActivity.createIntent(this, group));
}
Intent intent = new Intent(this, FileConfirmationActivity.class);
intent.putExtras(bundle);
intent.putExtra(Constants.EXTRA_GROUP, contact);
startActivityForResult(intent, 666);
@Override
public void onOpenPrivateMessage(Group contact) {
startActivity(SingleChatActivity.createIntent(this, contact));
}
@Override
@@ -203,6 +199,6 @@ public class SharingActivity extends AppCompatActivity implements SharingView, S
@Override
public void showToastMessage(@StringRes int message) {
Toast.makeText(BaseChatActivity.this, message, Toast.LENGTH_SHORT).show();
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}

View File

@@ -32,7 +32,9 @@ public class SharingContactsAdapter extends RecyclerView.Adapter<RecyclerView.Vi
private long mUserId;
interface OnOpenClickListener {
void onConfirmSharingFile(Group contact);
void onOpenGroupMessage(Group group);
void onOpenPrivateMessage(Group contact);
}
SharingContactsAdapter(OnOpenClickListener openClickListener, long userId) {
@@ -115,17 +117,14 @@ public class SharingContactsAdapter extends RecyclerView.Adapter<RecyclerView.Vi
@OnClick(R.id.sharing_contact_container)
void onClickContact() {
// int type = getItemViewType();
//
// if (type == GROUP_TYPE) {
// mItemClickListener.onOpenGroupMessage(mGroups.get(getAdapterPosition()));
// return;
// }
//
// mItemClickListener.onOpenPrivateMessage(mGroups.get(getAdapterPosition()));
int type = getItemViewType();
mItemClickListener.onConfirmSharingFile(mGroups.get(getAdapterPosition()));
// TODO: open file confirmation!
if (type == GROUP_TYPE) {
mItemClickListener.onOpenGroupMessage(mGroups.get(getAdapterPosition()));
return;
}
mItemClickListener.onOpenPrivateMessage(mGroups.get(getAdapterPosition()));
}
}
}

View File

@@ -165,6 +165,11 @@ public class SharingPresenter extends MVPAbstractPresenter<SharingView> implemen
.subscribe(this::loadGroupsFromDBSuccessful, this::loadGroupsError);
}
@Override
public void sendFile(Uri fileUri, String messageText) {
}
private void loadGroupsFromDBSuccessful(ArrayList<Group> groups) {
if (!isAttached()) {
return;
@@ -177,151 +182,4 @@ public class SharingPresenter extends MVPAbstractPresenter<SharingView> implemen
private void loadGroupsError(Throwable throwable) {
Log.e(SharingPresenter.class.getSimpleName(), throwable.getMessage(), throwable);
}
@Override
public void sendFile(Uri fileUri, String messageText, long groupId) {
File file = getView().getFile(fileUri);
final String mimeType = FileUtils.getMimeType(file);
if (file == null || !file.exists()) {
getView().showToastMessage(R.string.error_file_not_found);
return;
}
if(mUploadMaxSizePreference.get() > 0 && file.length() > mUploadMaxSizePreference.get()) {
getView().showError(R.string.error_file_is_too_large);
return;
}
if(mimeType != null && (mimeType.equals(Constants.MIME_TYPE_JPEG) || mimeType.equals(Constants.MIME_TYPE_PNG)) && (file.length() > (1000L * 1024L))) {
FileUtils.clearTmpFilesDir(mContext);
file = FileUtils.scaleImageDown(file, mContext);
}
final File fileToSend = file;
String[] split = fileToSend.getAbsolutePath().split("/");
Message message = new Message(findUniqueRandomId(mRealmProvider, mUserIdReference.get()),
groupId,
System.currentTimeMillis() / 1000,
messageText,
fileToSend.getPath(),
fileToSend.getPath(),
split[split.length - 1],
fileUri.toString(),
mUserIdReference.get(),
mProfileNamePreference.get(),
mAvatarPreference.get(),
Message.Status.PENDING,
true,
mUserIdReference.get(),
false);
storeMessageLocally(message).subscribe(new Subscriber<Object>() {
@Override
public void onCompleted() {
if (mSystemUtils.isNetworkUnavailable()) {
getView().showError(R.string.error_no_internet_connection);
message.status = Message.Status.FAILED;
message.isRead = true;
storeMessageLocally(message, message.id, true);
storeGroupLocally(groupId, message);
return;
}
checkForEmptyMessageAndHideIt();
message.createdAt *= 1000;
getView().addOneMessage(message);
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(getView().getMediaType(mimeType), fileToSend);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("file", fileToSend.getName(), requestFile);
// add another part within the multipart request
String groupIdString = String.valueOf(groupId);
RequestBody groupIdBody = RequestBody.create(okhttp3.MultipartBody.FORM, groupIdString);
RequestBody textBody = RequestBody.create(okhttp3.MultipartBody.FORM, message.message == null ? "" : message.message);
mChatService.sendFile(groupIdBody, body, textBody)
.compose(RxUtils.provideDefaultTransformer())
.flatMap(new ErrorHandlingResponseConverter<>())
.subscribe(new Subscriber<MessageResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
FileUtils.clearTmpFilesDir(mContext);
Log.e("sendFile", "onError", e);
@SuppressWarnings("UnnecessaryLocalVariable") Message newMessage = message;
newMessage.createdAt /= 1000;
newMessage.status = Message.Status.FAILED;
newMessage.isRead = true;
storeMessageLocally(newMessage, message.id, false);
storeGroupLocally(groupId, message);
if (!isAttached()) {
return;
}
if (mSystemUtils.isNetworkUnavailable()) {
getView().showError(R.string.error_no_internet_connection);
return;
}
getView().showError(R.string.error_something_went_wrong);
}
@Override
public void onNext(MessageResponse baseResponse) {
FileUtils.clearTmpFilesDir(mContext);
deleteLocalMessage(message);
baseResponse.response.message.status = Message.Status.DELIVERED;
baseResponse.response.message.isRead = true;
storeMessageLocally(baseResponse.response.message, message.id, false);
storeGroupLocally(groupId, baseResponse.response.message);
}
});
}
@Override
public void onError(Throwable e) {
Log.e("sendFile", "onError", e);
}
@Override
public void onNext(Object o) {
}
});
}
private Completable storeMessageLocally(Message message) {
MessageByIdSpecification messageByIdSpecification = new MessageByIdSpecification(mUserIdReference.get());
messageByIdSpecification.setMessageId(message.id);
return mMessageRealmRepository.update(message, messageByIdSpecification)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
private void storeGroupLocally(long groupId, Message message) {
Group group = new Group();
group.id = groupId;
group.lastMessage = message;
mGroupRealmRepository.updateGroupMessage(group, new GroupByIdSpecification(mUserIdReference.get()))
.subscribe(() -> {
if (!isAttached()) {
EventBus.getDefault().post(new GroupUpdatedEvent());
}
});
}
}

View File

@@ -3,13 +3,15 @@
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/sharing_contacts_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="match_parent"
>
<include layout="@layout/chat_toolbar" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize">
<android.support.v7.widget.RecyclerView
android:id="@+id/sharing_contacts_recycler_view"