Reformatting

Signed-off-by: Mario Danic <mario@lovelyhq.com>
This commit is contained in:
Mario Danic 2019-10-17 13:12:29 +02:00
parent 8441fd2475
commit fd44934b98
234 changed files with 18720 additions and 17790 deletions

View File

@ -76,8 +76,11 @@ open class BaseActivity : AppCompatActivity() {
} }
} }
fun showCertificateDialog(cert: X509Certificate, magicTrustManager: MagicTrustManager, fun showCertificateDialog(
sslErrorHandler: SslErrorHandler?) { cert: X509Certificate,
magicTrustManager: MagicTrustManager,
sslErrorHandler: SslErrorHandler?
) {
val formatter = DateFormat.getDateInstance(DateFormat.LONG) val formatter = DateFormat.getDateInstance(DateFormat.LONG)
val validFrom = formatter.format(cert.notBefore) val validFrom = formatter.format(cert.notBefore)
val validUntil = formatter.format(cert.notAfter) val validUntil = formatter.format(cert.notAfter)
@ -93,7 +96,11 @@ open class BaseActivity : AppCompatActivity() {
val type = list[0] as Int val type = list[0] as Int
if (type == 2) { if (type == 2) {
val name = list[1] as String val name = list[1] as String
stringBuilder.append("[").append(type).append("]").append(name).append(" ") stringBuilder.append("[")
.append(type)
.append("]")
.append(name)
.append(" ")
} }
} }
issuedFor = stringBuilder.toString() issuedFor = stringBuilder.toString()
@ -101,9 +108,11 @@ open class BaseActivity : AppCompatActivity() {
issuedFor = cert.subjectDN.name issuedFor = cert.subjectDN.name
} }
@SuppressLint("StringFormatMatches") val dialogText = String.format(resources @SuppressLint("StringFormatMatches") val dialogText = String.format(
resources
.getString(R.string.nc_certificate_dialog_text), .getString(R.string.nc_certificate_dialog_text),
issuedBy, issuedFor, validFrom, validUntil) issuedBy, issuedFor, validFrom, validUntil
)
LovelyStandardDialog(this) LovelyStandardDialog(this)
.setTopColorRes(R.color.nc_darkRed) .setTopColorRes(R.color.nc_darkRed)

View File

@ -53,10 +53,12 @@ class MagicCallActivity : BaseActivity() {
NextcloudTalkApplication.sharedApplication!!.componentApplication.inject(this) NextcloudTalkApplication.sharedApplication!!.componentApplication.inject(this)
requestWindowFeature(Window.FEATURE_NO_TITLE) requestWindowFeature(Window.FEATURE_NO_TITLE)
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN or window.addFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN or
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON) WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
)
window.decorView.systemUiVisibility = systemUiVisibility window.decorView.systemUiVisibility = systemUiVisibility
setContentView(R.layout.activity_magic_call) setContentView(R.layout.activity_magic_call)
@ -67,13 +69,17 @@ class MagicCallActivity : BaseActivity() {
if (!router!!.hasRootController()) { if (!router!!.hasRootController()) {
if (intent.getBooleanExtra(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL, false)) { if (intent.getBooleanExtra(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL, false)) {
router!!.setRoot(RouterTransaction.with(CallNotificationController(intent.extras)) router!!.setRoot(
RouterTransaction.with(CallNotificationController(intent.extras))
.pushChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler())) .popChangeHandler(HorizontalChangeHandler())
)
} else { } else {
router!!.setRoot(RouterTransaction.with(CallController(intent.extras)) router!!.setRoot(
RouterTransaction.with(CallController(intent.extras))
.pushChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler())) .popChangeHandler(HorizontalChangeHandler())
)
} }
} }
} }

View File

@ -39,7 +39,6 @@ import com.google.android.material.appbar.MaterialToolbar
import com.nextcloud.talk.R import com.nextcloud.talk.R
import com.nextcloud.talk.application.NextcloudTalkApplication import com.nextcloud.talk.application.NextcloudTalkApplication
import com.nextcloud.talk.controllers.CallNotificationController import com.nextcloud.talk.controllers.CallNotificationController
import com.nextcloud.talk.controllers.ConversationsListController
import com.nextcloud.talk.controllers.LockedController import com.nextcloud.talk.controllers.LockedController
import com.nextcloud.talk.controllers.ServerSelectionController import com.nextcloud.talk.controllers.ServerSelectionController
import com.nextcloud.talk.controllers.base.providers.ActionBarProvider import com.nextcloud.talk.controllers.base.providers.ActionBarProvider
@ -92,26 +91,34 @@ class MainActivity : BaseActivity(), ActionBarProvider {
if (intent.hasExtra(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL)) { if (intent.hasExtra(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL)) {
if (!router!!.hasRootController()) { if (!router!!.hasRootController()) {
router!!.setRoot(RouterTransaction.with(ConversationsListView()) router!!.setRoot(
RouterTransaction.with(ConversationsListView())
.pushChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler())) .popChangeHandler(HorizontalChangeHandler())
)
} }
onNewIntent(intent) onNewIntent(intent)
} else if (!router!!.hasRootController()) { } else if (!router!!.hasRootController()) {
if (hasDb) { if (hasDb) {
if (userUtils.anyUserExists()) { if (userUtils.anyUserExists()) {
router!!.setRoot(RouterTransaction.with(ConversationsListView()) router!!.setRoot(
RouterTransaction.with(ConversationsListView())
.pushChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler())) .popChangeHandler(HorizontalChangeHandler())
)
} else { } else {
router!!.setRoot(RouterTransaction.with(ServerSelectionController()) router!!.setRoot(
RouterTransaction.with(ServerSelectionController())
.pushChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler())) .popChangeHandler(HorizontalChangeHandler())
)
} }
} else { } else {
router!!.setRoot(RouterTransaction.with(ServerSelectionController()) router!!.setRoot(
RouterTransaction.with(ServerSelectionController())
.pushChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler())) .popChangeHandler(HorizontalChangeHandler())
)
} }
} }
@ -124,34 +131,38 @@ class MainActivity : BaseActivity(), ActionBarProvider {
} }
} }
@RequiresApi(api = Build.VERSION_CODES.M) @RequiresApi(api = Build.VERSION_CODES.M)
fun checkIfWeAreSecure() { fun checkIfWeAreSecure() {
val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
if (keyguardManager.isKeyguardSecure && appPreferences.isScreenLocked) { if (keyguardManager.isKeyguardSecure && appPreferences.isScreenLocked) {
if (!SecurityUtils.checkIfWeAreAuthenticated(appPreferences.screenLockTimeout)) { if (!SecurityUtils.checkIfWeAreAuthenticated(appPreferences.screenLockTimeout)) {
if (router != null && router!!.getControllerWithTag(LockedController.TAG) == null) { if (router != null && router!!.getControllerWithTag(LockedController.TAG) == null) {
router!!.pushController(RouterTransaction.with(LockedController()) router!!.pushController(
RouterTransaction.with(LockedController())
.pushChangeHandler(VerticalChangeHandler()) .pushChangeHandler(VerticalChangeHandler())
.popChangeHandler(VerticalChangeHandler()) .popChangeHandler(VerticalChangeHandler())
.tag(LockedController.TAG)) .tag(LockedController.TAG)
)
} }
} }
} }
} }
override fun onNewIntent(intent: Intent) { override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent) super.onNewIntent(intent)
if (intent.hasExtra(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL)) { if (intent.hasExtra(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL)) {
if (intent.getBooleanExtra(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL, false)) { if (intent.getBooleanExtra(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL, false)) {
router!!.pushController(RouterTransaction.with(CallNotificationController(intent.extras)) router!!.pushController(
RouterTransaction.with(CallNotificationController(intent.extras))
.pushChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler())) .popChangeHandler(HorizontalChangeHandler())
)
} else { } else {
ConductorRemapping.remapChatController(router!!, intent.getLongExtra(BundleKeys.KEY_INTERNAL_USER_ID, -1), ConductorRemapping.remapChatController(
intent.getStringExtra(BundleKeys.KEY_ROOM_TOKEN), intent.extras!!, false) router!!, intent.getLongExtra(BundleKeys.KEY_INTERNAL_USER_ID, -1),
intent.getStringExtra(BundleKeys.KEY_ROOM_TOKEN), intent.extras!!, false
)
} }
} }
} }

View File

@ -48,7 +48,8 @@ import eu.davidea.viewholders.FlexibleViewHolder;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.UserItemViewHolder> implements public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.UserItemViewHolder>
implements
IFilterable<String> { IFilterable<String> {
private Participant participant; private Participant participant;
@ -56,7 +57,8 @@ public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.User
@Nullable @Nullable
private Account account; private Account account;
public AdvancedUserItem(Participant participant, UserEntity userEntity, @Nullable Account account) { public AdvancedUserItem(Participant participant, UserEntity userEntity,
@Nullable Account account) {
this.participant = participant; this.participant = participant;
this.userEntity = userEntity; this.userEntity = userEntity;
this.account = account; this.account = account;
@ -104,12 +106,14 @@ public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.User
} }
@Override @Override
public void bindViewHolder(FlexibleAdapter adapter, UserItemViewHolder holder, int position, List payloads) { public void bindViewHolder(FlexibleAdapter adapter, UserItemViewHolder holder, int position,
List payloads) {
holder.avatarImageView.setController(null); holder.avatarImageView.setController(null);
if (adapter.hasFilter()) { if (adapter.hasFilter()) {
FlexibleUtils.highlightText(holder.contactDisplayName, participant.getName(), FlexibleUtils.highlightText(holder.contactDisplayName, participant.getName(),
String.valueOf(adapter.getFilter(String.class)), NextcloudTalkApplication.Companion.getSharedApplication() String.valueOf(adapter.getFilter(String.class)),
NextcloudTalkApplication.Companion.getSharedApplication()
.getResources().getColor(R.color.colorPrimary)); .getResources().getColor(R.color.colorPrimary));
} else { } else {
holder.contactDisplayName.setText(participant.getName()); holder.contactDisplayName.setText(participant.getName());
@ -117,21 +121,24 @@ public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.User
holder.serverUrl.setText(userEntity.getBaseUrl()); holder.serverUrl.setText(userEntity.getBaseUrl());
if (userEntity != null && userEntity.getBaseUrl() != null && userEntity.getBaseUrl().startsWith("http://") || userEntity.getBaseUrl().startsWith("https://")) { if (userEntity != null && userEntity.getBaseUrl() != null && userEntity.getBaseUrl()
.startsWith("http://") || userEntity.getBaseUrl().startsWith("https://")) {
holder.avatarImageView.setVisibility(View.VISIBLE); holder.avatarImageView.setVisibility(View.VISIBLE);
DraweeController draweeController = Fresco.newDraweeControllerBuilder() DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(holder.avatarImageView.getController()) .setOldController(holder.avatarImageView.getController())
.setAutoPlayAnimations(true) .setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(), .setImageRequest(DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(),
participant.getUserId(), R.dimen.avatar_size), null)) participant.getUserId(), R.dimen.avatar_size), null))
.build(); .build();
holder.avatarImageView.setController(draweeController); holder.avatarImageView.setController(draweeController);
} else { } else {
holder.avatarImageView.setVisibility(View.GONE); holder.avatarImageView.setVisibility(View.GONE);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) holder.linearLayout.getLayoutParams(); RelativeLayout.LayoutParams layoutParams =
layoutParams.setMarginStart((int) NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext() (RelativeLayout.LayoutParams) holder.linearLayout.getLayoutParams();
layoutParams.setMarginStart(
(int) NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext()
.getResources().getDimension(R.dimen.activity_horizontal_margin)); .getResources().getDimension(R.dimen.activity_horizontal_margin));
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START);
holder.linearLayout.setLayoutParams(layoutParams); holder.linearLayout.setLayoutParams(layoutParams);
@ -141,10 +148,11 @@ public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.User
@Override @Override
public boolean filter(String constraint) { public boolean filter(String constraint) {
return participant.getName() != null && return participant.getName() != null &&
Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL).matcher(participant.getName().trim()).find(); Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
.matcher(participant.getName().trim())
.find();
} }
static class UserItemViewHolder extends FlexibleViewHolder { static class UserItemViewHolder extends FlexibleViewHolder {
@BindView(R.id.name_text) @BindView(R.id.name_text)

View File

@ -56,7 +56,9 @@ public class AppItem extends AbstractFlexibleItem<AppItem.AppItemViewHolder> {
public boolean equals(Object o) { public boolean equals(Object o) {
if (o instanceof AppItem) { if (o instanceof AppItem) {
AppItem inItem = (AppItem) o; AppItem inItem = (AppItem) o;
return title.equals(inItem.getTitle()) && packageName.equals(inItem.getPackageName()) && name.equals(inItem return title.equals(inItem.getTitle())
&& packageName.equals(inItem.getPackageName())
&& name.equals(inItem
.getName()); .getName());
} }
@ -81,7 +83,8 @@ public class AppItem extends AbstractFlexibleItem<AppItem.AppItemViewHolder> {
} }
@Override @Override
public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, AppItemViewHolder holder, int position, List<Object> payloads) { public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, AppItemViewHolder holder,
int position, List<Object> payloads) {
if (drawable != null) { if (drawable != null) {
holder.iconImageView.setVisibility(View.VISIBLE); holder.iconImageView.setVisibility(View.VISIBLE);
holder.iconImageView.setImageDrawable(drawable); holder.iconImageView.setImageDrawable(drawable);
@ -91,7 +94,8 @@ public class AppItem extends AbstractFlexibleItem<AppItem.AppItemViewHolder> {
if (position == 0) { if (position == 0) {
Spannable spannableString = new SpannableString(title); Spannable spannableString = new SpannableString(title);
spannableString.setSpan(new ForegroundColorSpan(NextcloudTalkApplication.Companion.getSharedApplication() spannableString.setSpan(
new ForegroundColorSpan(NextcloudTalkApplication.Companion.getSharedApplication()
.getResources().getColor(R.color.grey_600)), 0, .getResources().getColor(R.color.grey_600)), 0,
spannableString.length(), spannableString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
@ -120,5 +124,4 @@ public class AppItem extends AbstractFlexibleItem<AppItem.AppItemViewHolder> {
ButterKnife.bind(this, view); ButterKnife.bind(this, view);
} }
} }
} }

View File

@ -48,7 +48,8 @@ import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
public class CallItem extends AbstractFlexibleItem<CallItem.RoomItemViewHolder> implements IFilterable<String> { public class CallItem extends AbstractFlexibleItem<CallItem.RoomItemViewHolder>
implements IFilterable<String> {
private Conversation conversation; private Conversation conversation;
private UserEntity userEntity; private UserEntity userEntity;
@ -95,10 +96,12 @@ public class CallItem extends AbstractFlexibleItem<CallItem.RoomItemViewHolder>
} }
@Override @Override
public void bindViewHolder(final FlexibleAdapter adapter, RoomItemViewHolder holder, int position, List payloads) { public void bindViewHolder(final FlexibleAdapter adapter, RoomItemViewHolder holder, int position,
List payloads) {
if (adapter.hasFilter()) { if (adapter.hasFilter()) {
FlexibleUtils.highlightText(holder.roomDisplayName, conversation.getDisplayName(), FlexibleUtils.highlightText(holder.roomDisplayName, conversation.getDisplayName(),
String.valueOf(adapter.getFilter(String.class)), NextcloudTalkApplication.Companion.getSharedApplication() String.valueOf(adapter.getFilter(String.class)),
NextcloudTalkApplication.Companion.getSharedApplication()
.getResources().getColor(R.color.colorPrimary)); .getResources().getColor(R.color.colorPrimary));
} else { } else {
holder.roomDisplayName.setText(conversation.getDisplayName()); holder.roomDisplayName.setText(conversation.getDisplayName());
@ -107,7 +110,8 @@ public class CallItem extends AbstractFlexibleItem<CallItem.RoomItemViewHolder>
if (conversation.getLastPing() == 0) { if (conversation.getLastPing() == 0) {
holder.roomLastPing.setText(R.string.nc_never); holder.roomLastPing.setText(R.string.nc_never);
} else { } else {
holder.roomLastPing.setText(DateUtils.getRelativeTimeSpanString(conversation.getLastPing() * 1000L, holder.roomLastPing.setText(
DateUtils.getRelativeTimeSpanString(conversation.getLastPing() * 1000L,
System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE)); System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
} }
@ -129,7 +133,8 @@ public class CallItem extends AbstractFlexibleItem<CallItem.RoomItemViewHolder>
DraweeController draweeController = Fresco.newDraweeControllerBuilder() DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(holder.avatarImageView.getController()) .setOldController(holder.avatarImageView.getController())
.setAutoPlayAnimations(true) .setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(), .setImageRequest(DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(),
conversation.getName(), conversation.getName(),
R.dimen.avatar_size), null)) R.dimen.avatar_size), null))
.build(); .build();
@ -152,16 +157,18 @@ public class CallItem extends AbstractFlexibleItem<CallItem.RoomItemViewHolder>
break; break;
default: default:
holder.avatarImageView.setVisibility(View.GONE); holder.avatarImageView.setVisibility(View.GONE);
} }
holder.moreMenuButton.setOnClickListener(view -> EventBus.getDefault().post(new MoreMenuClickEvent(conversation))); holder.moreMenuButton.setOnClickListener(
view -> EventBus.getDefault().post(new MoreMenuClickEvent(conversation)));
} }
@Override @Override
public boolean filter(String constraint) { public boolean filter(String constraint) {
return conversation.getDisplayName() != null && return conversation.getDisplayName() != null &&
Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL).matcher(conversation.getDisplayName().trim()).find(); Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
.matcher(conversation.getDisplayName().trim())
.find();
} }
static class RoomItemViewHolder extends FlexibleViewHolder { static class RoomItemViewHolder extends FlexibleViewHolder {

View File

@ -35,11 +35,11 @@ import butterknife.ButterKnife;
import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.drawee.view.SimpleDraweeView;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.chat.ChatMessage; import com.nextcloud.talk.models.json.chat.ChatMessage;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.DisplayUtils; import com.nextcloud.talk.utils.DisplayUtils;
import eu.davidea.flexibleadapter.FlexibleAdapter; import eu.davidea.flexibleadapter.FlexibleAdapter;
@ -51,10 +51,10 @@ import eu.davidea.viewholders.FlexibleViewHolder;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class ConversationItem extends AbstractFlexibleItem<ConversationItem.ConversationItemViewHolder> implements public class ConversationItem
extends AbstractFlexibleItem<ConversationItem.ConversationItemViewHolder> implements
IFilterable<String> { IFilterable<String> {
private Conversation conversation; private Conversation conversation;
private UserEntity userEntity; private UserEntity userEntity;
private Context context; private Context context;
@ -90,12 +90,14 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
} }
@Override @Override
public ConversationItemViewHolder createViewHolder(View view, FlexibleAdapter<IFlexible> adapter) { public ConversationItemViewHolder createViewHolder(View view,
FlexibleAdapter<IFlexible> adapter) {
return new ConversationItemViewHolder(view, adapter); return new ConversationItemViewHolder(view, adapter);
} }
@Override @Override
public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, ConversationItemViewHolder holder, int position, List<Object> payloads) { public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, ConversationItemViewHolder holder,
int position, List<Object> payloads) {
Context appContext = Context appContext =
NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext(); NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext();
@ -103,7 +105,8 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
if (adapter.hasFilter()) { if (adapter.hasFilter()) {
FlexibleUtils.highlightText(holder.dialogName, conversation.getDisplayName(), FlexibleUtils.highlightText(holder.dialogName, conversation.getDisplayName(),
String.valueOf(adapter.getFilter(String.class)), NextcloudTalkApplication.Companion.getSharedApplication() String.valueOf(adapter.getFilter(String.class)),
NextcloudTalkApplication.Companion.getSharedApplication()
.getResources().getColor(R.color.colorPrimary)); .getResources().getColor(R.color.colorPrimary));
} else { } else {
holder.dialogName.setText(conversation.getDisplayName()); holder.dialogName.setText(conversation.getDisplayName());
@ -118,15 +121,16 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
} }
if (conversation.isUnreadMention()) { if (conversation.isUnreadMention()) {
holder.dialogUnreadBubble.setBackground(context.getDrawable(R.drawable.bubble_circle_unread_mention)); holder.dialogUnreadBubble.setBackground(
context.getDrawable(R.drawable.bubble_circle_unread_mention));
} else { } else {
holder.dialogUnreadBubble.setBackground(context.getDrawable(R.drawable.bubble_circle_unread)); holder.dialogUnreadBubble.setBackground(
context.getDrawable(R.drawable.bubble_circle_unread));
} }
} else { } else {
holder.dialogUnreadBubble.setVisibility(View.GONE); holder.dialogUnreadBubble.setVisibility(View.GONE);
} }
if (conversation.isHasPassword()) { if (conversation.isHasPassword()) {
holder.passwordProtectedRoomImageView.setVisibility(View.VISIBLE); holder.passwordProtectedRoomImageView.setVisibility(View.VISIBLE);
} else { } else {
@ -141,23 +145,29 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
if (conversation.getLastMessage() != null) { if (conversation.getLastMessage() != null) {
holder.dialogDate.setVisibility(View.VISIBLE); holder.dialogDate.setVisibility(View.VISIBLE);
holder.dialogDate.setText(DateUtils.getRelativeTimeSpanString(conversation.getLastActivity() * 1000L, holder.dialogDate.setText(
DateUtils.getRelativeTimeSpanString(conversation.getLastActivity() * 1000L,
System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE)); System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
if (!TextUtils.isEmpty(conversation.getLastMessage().getSystemMessage()) || Conversation.ConversationType.ROOM_SYSTEM.equals(conversation.getType())) { if (!TextUtils.isEmpty(conversation.getLastMessage().getSystemMessage())
|| Conversation.ConversationType.ROOM_SYSTEM.equals(conversation.getType())) {
holder.dialogLastMessage.setText(conversation.getLastMessage().getText()); holder.dialogLastMessage.setText(conversation.getLastMessage().getText());
} else { } else {
String authorDisplayName = ""; String authorDisplayName = "";
conversation.getLastMessage().setActiveUser(userEntity); conversation.getLastMessage().setActiveUser(userEntity);
String text; String text;
if (conversation.getLastMessage().getMessageType().equals(ChatMessage.MessageType.REGULAR_TEXT_MESSAGE)) { if (conversation.getLastMessage()
.getMessageType()
.equals(ChatMessage.MessageType.REGULAR_TEXT_MESSAGE)) {
if (conversation.getLastMessage().getActorId().equals(userEntity.getUserId())) { if (conversation.getLastMessage().getActorId().equals(userEntity.getUserId())) {
text = String.format(appContext.getString(R.string.nc_formatted_message_you), text = String.format(appContext.getString(R.string.nc_formatted_message_you),
conversation.getLastMessage().getLastMessageDisplayText()); conversation.getLastMessage().getLastMessageDisplayText());
} else { } else {
authorDisplayName = !TextUtils.isEmpty(conversation.getLastMessage().getActorDisplayName()) ? authorDisplayName =
!TextUtils.isEmpty(conversation.getLastMessage().getActorDisplayName()) ?
conversation.getLastMessage().getActorDisplayName() : conversation.getLastMessage().getActorDisplayName() :
"guests".equals(conversation.getLastMessage().getActorType()) ? appContext.getString(R.string.nc_guest) : ""; "guests".equals(conversation.getLastMessage().getActorType())
? appContext.getString(R.string.nc_guest) : "";
text = String.format(appContext.getString(R.string.nc_formatted_message), text = String.format(appContext.getString(R.string.nc_formatted_message),
authorDisplayName, authorDisplayName,
conversation.getLastMessage().getLastMessageDisplayText()); conversation.getLastMessage().getLastMessageDisplayText());
@ -202,7 +212,8 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground); layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground);
LayerDrawable layerDrawable = new LayerDrawable(layers); LayerDrawable layerDrawable = new LayerDrawable(layers);
holder.dialogAvatar.getHierarchy().setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable)); holder.dialogAvatar.getHierarchy()
.setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable));
shouldLoadAvatar = false; shouldLoadAvatar = false;
} }
@ -214,7 +225,9 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
DraweeController draweeController = Fresco.newDraweeControllerBuilder() DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(holder.dialogAvatar.getController()) .setOldController(holder.dialogAvatar.getController())
.setAutoPlayAnimations(true) .setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(), conversation.getName(), R.dimen.avatar_size), null)) .setImageRequest(DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(),
conversation.getName(), R.dimen.avatar_size), null))
.build(); .build();
holder.dialogAvatar.setController(draweeController); holder.dialogAvatar.setController(draweeController);
} else { } else {
@ -222,7 +235,10 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
} }
break; break;
case ROOM_GROUP_CALL: case ROOM_GROUP_CALL:
holder.dialogAvatar.getHierarchy().setImage(new BitmapDrawable(DisplayUtils.getRoundedBitmapFromVectorDrawableResource(context.getResources(), R.drawable.ic_people_group_white_24px)), 100, true); holder.dialogAvatar.getHierarchy()
.setImage(new BitmapDrawable(
DisplayUtils.getRoundedBitmapFromVectorDrawableResource(context.getResources(),
R.drawable.ic_people_group_white_24px)), 100, true);
break; break;
case ROOM_PUBLIC_CALL: case ROOM_PUBLIC_CALL:
holder.dialogAvatar.getHierarchy().setImage(new BitmapDrawable(DisplayUtils holder.dialogAvatar.getHierarchy().setImage(new BitmapDrawable(DisplayUtils
@ -238,7 +254,9 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
@Override @Override
public boolean filter(String constraint) { public boolean filter(String constraint) {
return conversation.getDisplayName() != null && return conversation.getDisplayName() != null &&
Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL).matcher(conversation.getDisplayName().trim()).find(); Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
.matcher(conversation.getDisplayName().trim())
.find();
} }
static class ConversationItemViewHolder extends FlexibleViewHolder { static class ConversationItemViewHolder extends FlexibleViewHolder {

View File

@ -32,7 +32,8 @@ import eu.davidea.flexibleadapter.items.IFlexible;
import eu.davidea.viewholders.FlexibleViewHolder; import eu.davidea.viewholders.FlexibleViewHolder;
import java.util.List; import java.util.List;
public class GenericTextHeaderItem extends AbstractHeaderItem<GenericTextHeaderItem.HeaderViewHolder> { public class GenericTextHeaderItem
extends AbstractHeaderItem<GenericTextHeaderItem.HeaderViewHolder> {
private static final String TAG = "GenericTextHeaderItem"; private static final String TAG = "GenericTextHeaderItem";
private String title; private String title;
@ -63,13 +64,13 @@ public class GenericTextHeaderItem extends AbstractHeaderItem<GenericTextHeaderI
} }
@Override @Override
public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, HeaderViewHolder holder, int position, List<Object> payloads) { public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, HeaderViewHolder holder,
int position, List<Object> payloads) {
if (payloads.size() > 0) { if (payloads.size() > 0) {
Log.d(TAG, "We have payloads, so ignoring!"); Log.d(TAG, "We have payloads, so ignoring!");
} else { } else {
holder.titleTextView.setText(title); holder.titleTextView.setText(title);
} }
} }
@Override @Override
@ -90,5 +91,4 @@ public class GenericTextHeaderItem extends AbstractHeaderItem<GenericTextHeaderI
ButterKnife.bind(this, view); ButterKnife.bind(this, view);
} }
} }
} }

View File

@ -45,7 +45,8 @@ public class MentionAutocompleteItem extends AbstractFlexibleItem<UserItem.UserI
private String source; private String source;
private UserEntity currentUser; private UserEntity currentUser;
public MentionAutocompleteItem(String objectId, String displayName, String source, UserEntity currentUser) { public MentionAutocompleteItem(String objectId, String displayName, String source,
UserEntity currentUser) {
this.objectId = objectId; this.objectId = objectId;
this.displayName = displayName; this.displayName = displayName;
this.source = source; this.source = source;
@ -84,22 +85,25 @@ public class MentionAutocompleteItem extends AbstractFlexibleItem<UserItem.UserI
} }
@Override @Override
public UserItem.UserItemViewHolder createViewHolder(View view, FlexibleAdapter<IFlexible> adapter) { public UserItem.UserItemViewHolder createViewHolder(View view,
FlexibleAdapter<IFlexible> adapter) {
return new UserItem.UserItemViewHolder(view, adapter); return new UserItem.UserItemViewHolder(view, adapter);
} }
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
@Override @Override
public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, UserItem.UserItemViewHolder holder, int position, List<Object> payloads) { public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, UserItem.UserItemViewHolder holder,
int position, List<Object> payloads) {
if (adapter.hasFilter()) { if (adapter.hasFilter()) {
FlexibleUtils.highlightText(holder.contactDisplayName, displayName, FlexibleUtils.highlightText(holder.contactDisplayName, displayName,
String.valueOf(adapter.getFilter(String.class)), NextcloudTalkApplication.Companion.getSharedApplication() String.valueOf(adapter.getFilter(String.class)),
NextcloudTalkApplication.Companion.getSharedApplication()
.getResources().getColor(R.color.colorPrimary)); .getResources().getColor(R.color.colorPrimary));
if (holder.contactMentionId != null) { if (holder.contactMentionId != null) {
FlexibleUtils.highlightText(holder.contactMentionId, "@" + objectId, FlexibleUtils.highlightText(holder.contactMentionId, "@" + objectId,
String.valueOf(adapter.getFilter(String.class)), NextcloudTalkApplication.Companion.getSharedApplication() String.valueOf(adapter.getFilter(String.class)),
NextcloudTalkApplication.Companion.getSharedApplication()
.getResources().getColor(R.color.colorPrimary)); .getResources().getColor(R.color.colorPrimary));
} }
} else { } else {
@ -110,7 +114,10 @@ public class MentionAutocompleteItem extends AbstractFlexibleItem<UserItem.UserI
} }
if (source.equals("calls")) { if (source.equals("calls")) {
holder.simpleDraweeView.getHierarchy().setPlaceholderImage(DisplayUtils.getRoundedBitmapDrawableFromVectorDrawableResource(NextcloudTalkApplication.Companion.getSharedApplication().getResources(), R.drawable.ic_people_group_white_24px)); holder.simpleDraweeView.getHierarchy()
.setPlaceholderImage(DisplayUtils.getRoundedBitmapDrawableFromVectorDrawableResource(
NextcloudTalkApplication.Companion.getSharedApplication().getResources(),
R.drawable.ic_people_group_white_24px));
} else { } else {
String avatarId = objectId; String avatarId = objectId;
String avatarUrl = ApiUtils.getUrlForAvatarWithName(currentUser.getBaseUrl(), String avatarUrl = ApiUtils.getUrlForAvatarWithName(currentUser.getBaseUrl(),
@ -118,7 +125,8 @@ public class MentionAutocompleteItem extends AbstractFlexibleItem<UserItem.UserI
if (source.equals("guests")) { if (source.equals("guests")) {
avatarId = displayName; avatarId = displayName;
avatarUrl = ApiUtils.getUrlForAvatarWithNameForGuests(currentUser.getBaseUrl(), avatarId, R.dimen.avatar_size_big); avatarUrl = ApiUtils.getUrlForAvatarWithNameForGuests(currentUser.getBaseUrl(), avatarId,
R.dimen.avatar_size_big);
} }
holder.simpleDraweeView.setController(null); holder.simpleDraweeView.setController(null);
@ -135,6 +143,7 @@ public class MentionAutocompleteItem extends AbstractFlexibleItem<UserItem.UserI
public boolean filter(String constraint) { public boolean filter(String constraint) {
return objectId != null && Pattern.compile(constraint, return objectId != null && Pattern.compile(constraint,
Pattern.CASE_INSENSITIVE | Pattern.LITERAL).matcher(objectId).find() Pattern.CASE_INSENSITIVE | Pattern.LITERAL).matcher(objectId).find()
|| displayName != null && Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL).matcher(displayName).find(); || displayName != null && Pattern.compile(constraint,
Pattern.CASE_INSENSITIVE | Pattern.LITERAL).matcher(displayName).find();
} }
} }

View File

@ -76,10 +76,12 @@ public class MenuItem extends AbstractFlexibleItem<MenuItem.MenuItemViewHolder>
} }
@Override @Override
public void bindViewHolder(FlexibleAdapter adapter, MenuItem.MenuItemViewHolder holder, int position, List payloads) { public void bindViewHolder(FlexibleAdapter adapter, MenuItem.MenuItemViewHolder holder,
int position, List payloads) {
if (position == 0) { if (position == 0) {
Spannable spannableString = new SpannableString(title); Spannable spannableString = new SpannableString(title);
spannableString.setSpan(new ForegroundColorSpan(NextcloudTalkApplication.Companion.getSharedApplication() spannableString.setSpan(
new ForegroundColorSpan(NextcloudTalkApplication.Companion.getSharedApplication()
.getResources().getColor(R.color.grey_600)), 0, .getResources().getColor(R.color.grey_600)), 0,
spannableString.length(), spannableString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

View File

@ -36,7 +36,8 @@ import eu.davidea.flexibleadapter.items.IFlexible;
import eu.davidea.viewholders.FlexibleViewHolder; import eu.davidea.viewholders.FlexibleViewHolder;
import java.util.List; import java.util.List;
public class NotificationSoundItem extends AbstractFlexibleItem<NotificationSoundItem.NotificationSoundItemViewHolder> { public class NotificationSoundItem
extends AbstractFlexibleItem<NotificationSoundItem.NotificationSoundItemViewHolder> {
private String notificationSoundName; private String notificationSoundName;
private String notificationSoundUri; private String notificationSoundUri;
@ -65,12 +66,14 @@ public class NotificationSoundItem extends AbstractFlexibleItem<NotificationSoun
} }
@Override @Override
public NotificationSoundItemViewHolder createViewHolder(View view, FlexibleAdapter<IFlexible> adapter) { public NotificationSoundItemViewHolder createViewHolder(View view,
FlexibleAdapter<IFlexible> adapter) {
return new NotificationSoundItemViewHolder(view, adapter); return new NotificationSoundItemViewHolder(view, adapter);
} }
@Override @Override
public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, NotificationSoundItemViewHolder holder, int position, List<Object> payloads) { public void bindViewHolder(FlexibleAdapter<IFlexible> adapter,
NotificationSoundItemViewHolder holder, int position, List<Object> payloads) {
holder.notificationName.setText(notificationSoundName); holder.notificationName.setText(notificationSoundName);
if (adapter.isSelected(position)) { if (adapter.isSelected(position)) {
@ -80,12 +83,15 @@ public class NotificationSoundItem extends AbstractFlexibleItem<NotificationSoun
} }
Resources resources = NextcloudTalkApplication.Companion.getSharedApplication().getResources(); Resources resources = NextcloudTalkApplication.Companion.getSharedApplication().getResources();
holder.simpleDraweeView.getHierarchy().setBackgroundImage(new ColorDrawable(resources.getColor(R.color.colorPrimary))); holder.simpleDraweeView.getHierarchy()
.setBackgroundImage(new ColorDrawable(resources.getColor(R.color.colorPrimary)));
if (position == 0) { if (position == 0) {
holder.simpleDraweeView.getHierarchy().setImage(resources.getDrawable(R.drawable.ic_stop_white_24dp), 100, holder.simpleDraweeView.getHierarchy()
.setImage(resources.getDrawable(R.drawable.ic_stop_white_24dp), 100,
true); true);
} else { } else {
holder.simpleDraweeView.getHierarchy().setImage(resources.getDrawable(R.drawable.ic_play_circle_outline_white_24dp), 100, holder.simpleDraweeView.getHierarchy()
.setImage(resources.getDrawable(R.drawable.ic_play_circle_outline_white_24dp), 100,
true); true);
} }
} }
@ -106,6 +112,4 @@ public class NotificationSoundItem extends AbstractFlexibleItem<NotificationSoun
ButterKnife.bind(this, view); ButterKnife.bind(this, view);
} }
} }
} }

View File

@ -68,7 +68,8 @@ public class ProgressItem extends AbstractFlexibleItem<ProgressItem.ProgressView
} }
@Override @Override
public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, ProgressViewHolder holder, int position, List<Object> payloads) { public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, ProgressViewHolder holder,
int position, List<Object> payloads) {
Context context = holder.itemView.getContext(); Context context = holder.itemView.getContext();
holder.progressBar.setVisibility(View.GONE); holder.progressBar.setVisibility(View.GONE);
holder.progressMessage.setVisibility(View.VISIBLE); holder.progressMessage.setVisibility(View.VISIBLE);
@ -111,7 +112,6 @@ public class ProgressItem extends AbstractFlexibleItem<ProgressItem.ProgressView
return new ProgressViewHolder(view, adapter); return new ProgressViewHolder(view, adapter);
} }
public enum StatusEnum { public enum StatusEnum {
MORE_TO_LOAD, //Default = should have an empty Payload MORE_TO_LOAD, //Default = should have an empty Payload
DISABLE_ENDLESS, //Endless is disabled because user has set limits DISABLE_ENDLESS, //Endless is disabled because user has set limits
@ -133,9 +133,9 @@ public class ProgressItem extends AbstractFlexibleItem<ProgressItem.ProgressView
} }
@Override @Override
public void scrollAnimators(@NonNull List<Animator> animators, int position, boolean isForward) { public void scrollAnimators(@NonNull List<Animator> animators, int position,
boolean isForward) {
AnimatorHelper.scaleAnimator(animators, itemView, 0f); AnimatorHelper.scaleAnimator(animators, itemView, 0f);
} }
} }
} }

View File

@ -52,11 +52,11 @@ import javax.annotation.Nullable;
public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder> implements public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder> implements
ISectionable<UserItem.UserItemViewHolder, GenericTextHeaderItem>, IFilterable<String> { ISectionable<UserItem.UserItemViewHolder, GenericTextHeaderItem>, IFilterable<String> {
public boolean isOnline = true;
private Participant participant; private Participant participant;
private UserEntity userEntity; private UserEntity userEntity;
private GenericTextHeaderItem header; private GenericTextHeaderItem header;
private Context activityContext; private Context activityContext;
public boolean isOnline = true;
public UserItem(Participant participant, UserEntity userEntity, public UserItem(Participant participant, UserEntity userEntity,
GenericTextHeaderItem genericTextHeaderItem, Context activityContext) { GenericTextHeaderItem genericTextHeaderItem, Context activityContext) {
@ -92,7 +92,6 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
return userEntity; return userEntity;
} }
@Override @Override
public int getLayoutRes() { public int getLayoutRes() {
if (header != null) { if (header != null) {
@ -108,7 +107,8 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
} }
@Override @Override
public void bindViewHolder(FlexibleAdapter adapter, UserItemViewHolder holder, int position, List payloads) { public void bindViewHolder(FlexibleAdapter adapter, UserItemViewHolder holder, int position,
List payloads) {
holder.simpleDraweeView.setController(null); holder.simpleDraweeView.setController(null);
@ -136,20 +136,25 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
if (adapter.hasFilter()) { if (adapter.hasFilter()) {
FlexibleUtils.highlightText(holder.contactDisplayName, participant.getDisplayName(), FlexibleUtils.highlightText(holder.contactDisplayName, participant.getDisplayName(),
String.valueOf(adapter.getFilter(String.class)), activityContext.getResources().getColor(R.color.colorPrimary)); String.valueOf(adapter.getFilter(String.class)),
activityContext.getResources().getColor(R.color.colorPrimary));
} }
holder.contactDisplayName.setText(participant.getDisplayName()); holder.contactDisplayName.setText(participant.getDisplayName());
if (TextUtils.isEmpty(participant.getDisplayName()) && if (TextUtils.isEmpty(participant.getDisplayName()) &&
(participant.getType().equals(Participant.ParticipantType.GUEST) || participant.getType().equals(Participant.ParticipantType.USER_FOLLOWING_LINK))) { (participant.getType().equals(Participant.ParticipantType.GUEST) || participant.getType()
holder.contactDisplayName.setText(NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest)); .equals(Participant.ParticipantType.USER_FOLLOWING_LINK))) {
holder.contactDisplayName.setText(
NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest));
} }
if (TextUtils.isEmpty(participant.getSource()) || participant.getSource().equals("users")) { if (TextUtils.isEmpty(participant.getSource()) || participant.getSource().equals("users")) {
if (Participant.ParticipantType.GUEST.equals(participant.getType()) || if (Participant.ParticipantType.GUEST.equals(participant.getType()) ||
Participant.ParticipantType.USER_FOLLOWING_LINK.equals(participant.getType())) { Participant.ParticipantType.USER_FOLLOWING_LINK.equals(participant.getType())) {
String displayName = NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_guest); String displayName = NextcloudTalkApplication.Companion.getSharedApplication()
.getResources()
.getString(R.string.nc_guest);
if (!TextUtils.isEmpty(participant.getDisplayName())) { if (!TextUtils.isEmpty(participant.getDisplayName())) {
displayName = participant.getDisplayName(); displayName = participant.getDisplayName();
@ -158,24 +163,26 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
DraweeController draweeController = Fresco.newDraweeControllerBuilder() DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(holder.simpleDraweeView.getController()) .setOldController(holder.simpleDraweeView.getController())
.setAutoPlayAnimations(true) .setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithNameForGuests(userEntity.getBaseUrl(), .setImageRequest(DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithNameForGuests(userEntity.getBaseUrl(),
displayName, R.dimen.avatar_size), null)) displayName, R.dimen.avatar_size), null))
.build(); .build();
holder.simpleDraweeView.setController(draweeController); holder.simpleDraweeView.setController(draweeController);
} else { } else {
DraweeController draweeController = Fresco.newDraweeControllerBuilder() DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(holder.simpleDraweeView.getController()) .setOldController(holder.simpleDraweeView.getController())
.setAutoPlayAnimations(true) .setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(), .setImageRequest(DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(),
participant.getUserId(), R.dimen.avatar_size), null)) participant.getUserId(), R.dimen.avatar_size), null))
.build(); .build();
holder.simpleDraweeView.setController(draweeController); holder.simpleDraweeView.setController(draweeController);
} }
} else if ("groups".equals(participant.getSource())) { } else if ("groups".equals(participant.getSource())) {
holder.simpleDraweeView.getHierarchy().setImage(new BitmapDrawable(DisplayUtils.getRoundedBitmapFromVectorDrawableResource(activityContext.getResources(), R.drawable.ic_people_group_white_24px)), 100, true); holder.simpleDraweeView.getHierarchy()
.setImage(new BitmapDrawable(DisplayUtils.getRoundedBitmapFromVectorDrawableResource(
activityContext.getResources(), R.drawable.ic_people_group_white_24px)), 100, true);
} }
Resources resources = activityContext.getResources(); Resources resources = activityContext.getResources();
@ -188,24 +195,30 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
holder.videoCallImageView.setVisibility(View.GONE); holder.videoCallImageView.setVisibility(View.GONE);
break; break;
case IN_CALL: case IN_CALL:
holder.voiceOrSimpleCallImageView.setBackground(resources.getDrawable(R.drawable.shape_call_bubble)); holder.voiceOrSimpleCallImageView.setBackground(
resources.getDrawable(R.drawable.shape_call_bubble));
holder.voiceOrSimpleCallImageView.setVisibility(View.VISIBLE); holder.voiceOrSimpleCallImageView.setVisibility(View.VISIBLE);
holder.videoCallImageView.setVisibility(View.GONE); holder.videoCallImageView.setVisibility(View.GONE);
break; break;
case IN_CALL_WITH_AUDIO: case IN_CALL_WITH_AUDIO:
holder.voiceOrSimpleCallImageView.setBackground(resources.getDrawable(R.drawable.shape_voice_bubble)); holder.voiceOrSimpleCallImageView.setBackground(
resources.getDrawable(R.drawable.shape_voice_bubble));
holder.voiceOrSimpleCallImageView.setVisibility(View.VISIBLE); holder.voiceOrSimpleCallImageView.setVisibility(View.VISIBLE);
holder.videoCallImageView.setVisibility(View.GONE); holder.videoCallImageView.setVisibility(View.GONE);
break; break;
case IN_CALL_WITH_VIDEO: case IN_CALL_WITH_VIDEO:
holder.voiceOrSimpleCallImageView.setBackground(resources.getDrawable(R.drawable.shape_call_bubble)); holder.voiceOrSimpleCallImageView.setBackground(
holder.videoCallImageView.setBackground(resources.getDrawable(R.drawable.shape_video_bubble)); resources.getDrawable(R.drawable.shape_call_bubble));
holder.videoCallImageView.setBackground(
resources.getDrawable(R.drawable.shape_video_bubble));
holder.voiceOrSimpleCallImageView.setVisibility(View.VISIBLE); holder.voiceOrSimpleCallImageView.setVisibility(View.VISIBLE);
holder.videoCallImageView.setVisibility(View.VISIBLE); holder.videoCallImageView.setVisibility(View.VISIBLE);
break; break;
case IN_CALL_WITH_AUDIO_AND_VIDEO: case IN_CALL_WITH_AUDIO_AND_VIDEO:
holder.voiceOrSimpleCallImageView.setBackground(resources.getDrawable(R.drawable.shape_voice_bubble)); holder.voiceOrSimpleCallImageView.setBackground(
holder.videoCallImageView.setBackground(resources.getDrawable(R.drawable.shape_video_bubble)); resources.getDrawable(R.drawable.shape_voice_bubble));
holder.videoCallImageView.setBackground(
resources.getDrawable(R.drawable.shape_video_bubble));
holder.voiceOrSimpleCallImageView.setVisibility(View.VISIBLE); holder.voiceOrSimpleCallImageView.setVisibility(View.VISIBLE);
holder.videoCallImageView.setVisibility(View.VISIBLE); holder.videoCallImageView.setVisibility(View.VISIBLE);
break; break;
@ -215,7 +228,6 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
break; break;
} }
if (holder.contactMentionId != null) { if (holder.contactMentionId != null) {
String userType = ""; String userType = "";
@ -224,16 +236,20 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
//userType = NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_owner); //userType = NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_owner);
//break; //break;
case 2: case 2:
userType = NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_moderator); userType = NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_moderator);
break; break;
case 3: case 3:
userType = NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_user); userType = NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_user);
break; break;
case 4: case 4:
userType = NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest); userType = NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_guest);
break; break;
case 5: case 5:
userType = NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_following_link); userType = NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_following_link);
break; break;
default: default:
break; break;
@ -241,7 +257,8 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
if (!holder.contactMentionId.getText().equals(userType)) { if (!holder.contactMentionId.getText().equals(userType)) {
holder.contactMentionId.setText(userType); holder.contactMentionId.setText(userType);
holder.contactMentionId.setTextColor(activityContext.getResources().getColor(R.color.colorPrimary)); holder.contactMentionId.setTextColor(
activityContext.getResources().getColor(R.color.colorPrimary));
} }
} }
} }
@ -250,8 +267,12 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
@Override @Override
public boolean filter(String constraint) { public boolean filter(String constraint) {
return participant.getDisplayName() != null && return participant.getDisplayName() != null &&
(Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL).matcher(participant.getDisplayName().trim()).find() || (Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL).matcher(participant.getUserId().trim()).find()); .matcher(participant.getDisplayName().trim())
.find() ||
Pattern.compile(constraint, Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
.matcher(participant.getUserId().trim())
.find());
} }
@Override @Override
@ -264,7 +285,6 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
this.header = header; this.header = header;
} }
static class UserItemViewHolder extends FlexibleViewHolder { static class UserItemViewHolder extends FlexibleViewHolder {
@BindView(R.id.name_text) @BindView(R.id.name_text)
@ -292,6 +312,4 @@ public class UserItem extends AbstractFlexibleItem<UserItem.UserItemViewHolder>
ButterKnife.bind(this, view); ButterKnife.bind(this, view);
} }
} }
} }

View File

@ -82,12 +82,13 @@ public class MagicIncomingTextMessageViewHolder
public MagicIncomingTextMessageViewHolder(View itemView) { public MagicIncomingTextMessageViewHolder(View itemView) {
super(itemView); super(itemView);
ButterKnife.bind(this, itemView); ButterKnife.bind(this, itemView);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
this.itemView = itemView; this.itemView = itemView;
} }
@Override @Override
public void onBind(ChatMessage message) { public void onBind(ChatMessage message) {
super.onBind(message); super.onBind(message);
@ -103,17 +104,20 @@ public class MagicIncomingTextMessageViewHolder
messageUserAvatarView.setVisibility(View.VISIBLE); messageUserAvatarView.setVisibility(View.VISIBLE);
if (message.getActorType().equals("guests")) { if (message.getActorType().equals("guests")) {
// do nothing, avatar is set // do nothing, avatar is set
} else if (message.getActorType().equals("bots") && message.getActorId().equals("changelog")) { } else if (message.getActorType().equals("bots") && message.getActorId()
.equals("changelog")) {
messageUserAvatarView.setController(null); messageUserAvatarView.setController(null);
Drawable[] layers = new Drawable[2]; Drawable[] layers = new Drawable[2];
layers[0] = context.getDrawable(R.drawable.ic_launcher_background); layers[0] = context.getDrawable(R.drawable.ic_launcher_background);
layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground); layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground);
LayerDrawable layerDrawable = new LayerDrawable(layers); LayerDrawable layerDrawable = new LayerDrawable(layers);
messageUserAvatarView.getHierarchy().setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable)); messageUserAvatarView.getHierarchy()
.setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable));
} else if (message.getActorType().equals("bots")) { } else if (message.getActorType().equals("bots")) {
messageUserAvatarView.setController(null); messageUserAvatarView.setController(null);
TextDrawable drawable = TextDrawable.builder().beginConfig().bold().endConfig().buildRound(">", TextDrawable drawable =
TextDrawable.builder().beginConfig().bold().endConfig().buildRound(">",
context.getResources().getColor(R.color.black)); context.getResources().getColor(R.color.black));
messageUserAvatarView.setVisibility(View.VISIBLE); messageUserAvatarView.setVisibility(View.VISIBLE);
messageUserAvatarView.getHierarchy().setPlaceholderImage(drawable); messageUserAvatarView.getHierarchy().setPlaceholderImage(drawable);
@ -147,7 +151,8 @@ public class MagicIncomingTextMessageViewHolder
itemView.setSelected(false); itemView.setSelected(false);
messageTimeView.setTextColor(context.getResources().getColor(R.color.warm_grey_four)); messageTimeView.setTextColor(context.getResources().getColor(R.color.warm_grey_four));
FlexboxLayout.LayoutParams layoutParams = (FlexboxLayout.LayoutParams) messageTimeView.getLayoutParams(); FlexboxLayout.LayoutParams layoutParams =
(FlexboxLayout.LayoutParams) messageTimeView.getLayoutParams();
layoutParams.setWrapBefore(false); layoutParams.setWrapBefore(false);
Spannable messageString = new SpannableString(message.getText()); Spannable messageString = new SpannableString(message.getText());
@ -158,7 +163,8 @@ public class MagicIncomingTextMessageViewHolder
for (String key : messageParameters.keySet()) { for (String key : messageParameters.keySet()) {
Map<String, String> individualHashMap = message.getMessageParameters().get(key); Map<String, String> individualHashMap = message.getMessageParameters().get(key);
if (individualHashMap != null) { if (individualHashMap != null) {
if (individualHashMap.get("type").equals("user") || individualHashMap.get("type").equals("guest") || individualHashMap.get("type").equals("call")) { if (individualHashMap.get("type").equals("user") || individualHashMap.get("type")
.equals("guest") || individualHashMap.get("type").equals("call")) {
if (individualHashMap.get("id").equals(message.getActiveUser().getUserId())) { if (individualHashMap.get("id").equals(message.getActiveUser().getUserId())) {
messageString = messageString =
DisplayUtils.searchAndReplaceWithMentionSpan(messageText.getContext(), DisplayUtils.searchAndReplaceWithMentionSpan(messageText.getContext(),
@ -178,17 +184,15 @@ public class MagicIncomingTextMessageViewHolder
userUtils.getUserById(message.getActiveUser().getUserId()), userUtils.getUserById(message.getActiveUser().getUserId()),
R.xml.chip_others); R.xml.chip_others);
} }
} else if (individualHashMap.get("type").equals("file")) { } else if (individualHashMap.get("type").equals("file")) {
itemView.setOnClickListener(v -> { itemView.setOnClickListener(v -> {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(individualHashMap.get("link"))); Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse(individualHashMap.get("link")));
context.startActivity(browserIntent); context.startActivity(browserIntent);
}); });
} }
} }
} }
} else if (TextMatchers.isMessageWithSingleEmoticonOnly(message.getText())) { } else if (TextMatchers.isMessageWithSingleEmoticonOnly(message.getText())) {
textSize = (float) (textSize * 2.5); textSize = (float) (textSize * 2.5);
layoutParams.setWrapBefore(true); layoutParams.setWrapBefore(true);

View File

@ -48,7 +48,8 @@ import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
@AutoInjector(NextcloudTalkApplication.class) @AutoInjector(NextcloudTalkApplication.class)
public class MagicOutcomingTextMessageViewHolder extends MessageHolders.OutcomingTextMessageViewHolder<ChatMessage> { public class MagicOutcomingTextMessageViewHolder
extends MessageHolders.OutcomingTextMessageViewHolder<ChatMessage> {
@BindView(R.id.messageText) @BindView(R.id.messageText)
EmojiTextView messageText; EmojiTextView messageText;
@ -66,7 +67,9 @@ public class MagicOutcomingTextMessageViewHolder extends MessageHolders.Outcomin
public MagicOutcomingTextMessageViewHolder(View itemView) { public MagicOutcomingTextMessageViewHolder(View itemView) {
super(itemView); super(itemView);
ButterKnife.bind(this, itemView); ButterKnife.bind(this, itemView);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
this.itemView = itemView; this.itemView = itemView;
} }
@ -82,7 +85,8 @@ public class MagicOutcomingTextMessageViewHolder extends MessageHolders.Outcomin
itemView.setSelected(false); itemView.setSelected(false);
messageTimeView.setTextColor(context.getResources().getColor(R.color.white60)); messageTimeView.setTextColor(context.getResources().getColor(R.color.white60));
FlexboxLayout.LayoutParams layoutParams = (FlexboxLayout.LayoutParams) messageTimeView.getLayoutParams(); FlexboxLayout.LayoutParams layoutParams =
(FlexboxLayout.LayoutParams) messageTimeView.getLayoutParams();
layoutParams.setWrapBefore(false); layoutParams.setWrapBefore(false);
float textSize = context.getResources().getDimension(R.dimen.chat_text_size); float textSize = context.getResources().getDimension(R.dimen.chat_text_size);
@ -91,7 +95,8 @@ public class MagicOutcomingTextMessageViewHolder extends MessageHolders.Outcomin
for (String key : messageParameters.keySet()) { for (String key : messageParameters.keySet()) {
Map<String, String> individualHashMap = message.getMessageParameters().get(key); Map<String, String> individualHashMap = message.getMessageParameters().get(key);
if (individualHashMap != null) { if (individualHashMap != null) {
if (individualHashMap.get("type").equals("user") || individualHashMap.get("type").equals("guest") || individualHashMap.get("type").equals("call")) { if (individualHashMap.get("type").equals("user") || individualHashMap.get("type")
.equals("guest") || individualHashMap.get("type").equals("call")) {
messageString = messageString =
DisplayUtils.searchAndReplaceWithMentionSpan(messageText.getContext(), DisplayUtils.searchAndReplaceWithMentionSpan(messageText.getContext(),
messageString, messageString,
@ -102,14 +107,13 @@ public class MagicOutcomingTextMessageViewHolder extends MessageHolders.Outcomin
R.xml.chip_others); R.xml.chip_others);
} else if (individualHashMap.get("type").equals("file")) { } else if (individualHashMap.get("type").equals("file")) {
itemView.setOnClickListener(v -> { itemView.setOnClickListener(v -> {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(individualHashMap.get("link"))); Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse(individualHashMap.get("link")));
context.startActivity(browserIntent); context.startActivity(browserIntent);
}); });
} }
} }
} }
} else if (TextMatchers.isMessageWithSingleEmoticonOnly(message.getText())) { } else if (TextMatchers.isMessageWithSingleEmoticonOnly(message.getText())) {
textSize = (float) (textSize * 2.5); textSize = (float) (textSize * 2.5);
layoutParams.setWrapBefore(true); layoutParams.setWrapBefore(true);
@ -120,14 +124,18 @@ public class MagicOutcomingTextMessageViewHolder extends MessageHolders.Outcomin
Resources resources = NextcloudTalkApplication.Companion.getSharedApplication().getResources(); Resources resources = NextcloudTalkApplication.Companion.getSharedApplication().getResources();
if (message.isGrouped) { if (message.isGrouped) {
Drawable bubbleDrawable = Drawable bubbleDrawable =
DisplayUtils.getMessageSelector(resources.getColor(R.color.bg_message_list_outcoming_bubble), DisplayUtils.getMessageSelector(
resources.getColor(R.color.bg_message_list_outcoming_bubble),
resources.getColor(R.color.transparent), resources.getColor(R.color.transparent),
resources.getColor(R.color.bg_message_list_outcoming_bubble), R.drawable.shape_grouped_outcoming_message); resources.getColor(R.color.bg_message_list_outcoming_bubble),
R.drawable.shape_grouped_outcoming_message);
ViewCompat.setBackground(bubble, bubbleDrawable); ViewCompat.setBackground(bubble, bubbleDrawable);
} else { } else {
Drawable bubbleDrawable = DisplayUtils.getMessageSelector(resources.getColor(R.color.bg_message_list_outcoming_bubble), Drawable bubbleDrawable = DisplayUtils.getMessageSelector(
resources.getColor(R.color.bg_message_list_outcoming_bubble),
resources.getColor(R.color.transparent), resources.getColor(R.color.transparent),
resources.getColor(R.color.bg_message_list_outcoming_bubble), R.drawable.shape_outcoming_message); resources.getColor(R.color.bg_message_list_outcoming_bubble),
R.drawable.shape_outcoming_message);
ViewCompat.setBackground(bubble, bubbleDrawable); ViewCompat.setBackground(bubble, bubbleDrawable);
} }

View File

@ -55,7 +55,8 @@ import javax.inject.Inject;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
@AutoInjector(NextcloudTalkApplication.class) @AutoInjector(NextcloudTalkApplication.class)
public class MagicPreviewMessageViewHolder extends MessageHolders.IncomingImageMessageViewHolder<ChatMessage> { public class MagicPreviewMessageViewHolder
extends MessageHolders.IncomingImageMessageViewHolder<ChatMessage> {
@BindView(R.id.messageText) @BindView(R.id.messageText)
EmojiTextView messageText; EmojiTextView messageText;
@ -69,7 +70,9 @@ public class MagicPreviewMessageViewHolder extends MessageHolders.IncomingImageM
public MagicPreviewMessageViewHolder(View itemView) { public MagicPreviewMessageViewHolder(View itemView) {
super(itemView); super(itemView);
ButterKnife.bind(this, itemView); ButterKnife.bind(this, itemView);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
} }
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
@ -92,7 +95,8 @@ public class MagicPreviewMessageViewHolder extends MessageHolders.IncomingImageM
layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground); layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground);
LayerDrawable layerDrawable = new LayerDrawable(layers); LayerDrawable layerDrawable = new LayerDrawable(layers);
userAvatar.getHierarchy().setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable)); userAvatar.getHierarchy()
.setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable));
} }
} }
} }
@ -100,29 +104,41 @@ public class MagicPreviewMessageViewHolder extends MessageHolders.IncomingImageM
if (message.getMessageType() == ChatMessage.MessageType.SINGLE_NC_ATTACHMENT_MESSAGE) { if (message.getMessageType() == ChatMessage.MessageType.SINGLE_NC_ATTACHMENT_MESSAGE) {
// it's a preview for a Nextcloud share // it's a preview for a Nextcloud share
messageText.setText(message.getSelectedIndividualHashMap().get("name")); messageText.setText(message.getSelectedIndividualHashMap().get("name"));
DisplayUtils.setClickableString(message.getSelectedIndividualHashMap().get("name"), message.getSelectedIndividualHashMap().get("link"), messageText); DisplayUtils.setClickableString(message.getSelectedIndividualHashMap().get("name"),
message.getSelectedIndividualHashMap().get("link"), messageText);
if (message.getSelectedIndividualHashMap().containsKey("mimetype")) { if (message.getSelectedIndividualHashMap().containsKey("mimetype")) {
image.getHierarchy().setPlaceholderImage(context.getDrawable(DrawableUtils.INSTANCE.getDrawableResourceIdForMimeType(message.getSelectedIndividualHashMap().get("mimetype")))); image.getHierarchy()
.setPlaceholderImage(context.getDrawable(
DrawableUtils.INSTANCE.getDrawableResourceIdForMimeType(
message.getSelectedIndividualHashMap().get("mimetype"))));
} else { } else {
fetchFileInformation("/" + message.getSelectedIndividualHashMap().get("path"), message.getActiveUser()); fetchFileInformation("/" + message.getSelectedIndividualHashMap().get("path"),
message.getActiveUser());
} }
image.setOnClickListener(v -> { image.setOnClickListener(v -> {
String accountString = String accountString =
message.getActiveUser().getUsername() + "@" + message.getActiveUser().getBaseUrl().replace("https://", "").replace("http://", ""); message.getActiveUser().getUsername() + "@" + message.getActiveUser()
.getBaseUrl()
.replace("https://", "")
.replace("http://", "");
if (AccountUtils.INSTANCE.canWeOpenFilesApp(context, accountString)) { if (AccountUtils.INSTANCE.canWeOpenFilesApp(context, accountString)) {
Intent filesAppIntent = new Intent(Intent.ACTION_VIEW, null); Intent filesAppIntent = new Intent(Intent.ACTION_VIEW, null);
final ComponentName componentName = new ComponentName(context.getString(R.string.nc_import_accounts_from), "com.owncloud.android.ui.activity.FileDisplayActivity"); final ComponentName componentName =
new ComponentName(context.getString(R.string.nc_import_accounts_from),
"com.owncloud.android.ui.activity.FileDisplayActivity");
filesAppIntent.setComponent(componentName); filesAppIntent.setComponent(componentName);
filesAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); filesAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
filesAppIntent.setPackage(context.getString(R.string.nc_import_accounts_from)); filesAppIntent.setPackage(context.getString(R.string.nc_import_accounts_from));
filesAppIntent.putExtra(BundleKeys.INSTANCE.getKEY_ACCOUNT(), accountString); filesAppIntent.putExtra(BundleKeys.INSTANCE.getKEY_ACCOUNT(), accountString);
filesAppIntent.putExtra(BundleKeys.INSTANCE.getKEY_FILE_ID(), message.getSelectedIndividualHashMap().get("id")); filesAppIntent.putExtra(BundleKeys.INSTANCE.getKEY_FILE_ID(),
message.getSelectedIndividualHashMap().get("id"));
context.startActivity(filesAppIntent); context.startActivity(filesAppIntent);
} else { } else {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(message.getSelectedIndividualHashMap().get("link"))); Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(message.getSelectedIndividualHashMap().get("link")));
browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(browserIntent); context.startActivity(browserIntent);
} }
@ -166,7 +182,10 @@ public class MagicPreviewMessageViewHolder extends MessageHolders.IncomingImageM
if (davResponse.getData() != null) { if (davResponse.getData() != null) {
List<BrowserFile> browserFileList = (List<BrowserFile>) davResponse.getData(); List<BrowserFile> browserFileList = (List<BrowserFile>) davResponse.getData();
if (!browserFileList.isEmpty()) { if (!browserFileList.isEmpty()) {
new Handler(context.getMainLooper()).post(() -> image.getHierarchy().setPlaceholderImage(context.getDrawable(DrawableUtils.INSTANCE.getDrawableResourceIdForMimeType(browserFileList.get(0).getMimeType())))); new Handler(context.getMainLooper()).post(() -> image.getHierarchy()
.setPlaceholderImage(context.getDrawable(
DrawableUtils.INSTANCE.getDrawableResourceIdForMimeType(
browserFileList.get(0).getMimeType()))));
} }
} }
} }
@ -175,6 +194,5 @@ public class MagicPreviewMessageViewHolder extends MessageHolders.IncomingImageM
public void onError(Throwable e) { public void onError(Throwable e) {
} }
}); });
} }
} }

View File

@ -38,7 +38,8 @@ import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
@AutoInjector(NextcloudTalkApplication.class) @AutoInjector(NextcloudTalkApplication.class)
public class MagicSystemMessageViewHolder extends MessageHolders.IncomingTextMessageViewHolder<ChatMessage> { public class MagicSystemMessageViewHolder
extends MessageHolders.IncomingTextMessageViewHolder<ChatMessage> {
@Inject @Inject
AppPreferences appPreferences; AppPreferences appPreferences;
@ -48,7 +49,9 @@ public class MagicSystemMessageViewHolder extends MessageHolders.IncomingTextMes
public MagicSystemMessageViewHolder(View itemView) { public MagicSystemMessageViewHolder(View itemView) {
super(itemView); super(itemView);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
} }
@Override @Override
@ -60,7 +63,6 @@ public class MagicSystemMessageViewHolder extends MessageHolders.IncomingTextMes
int pressedColor; int pressedColor;
int mentionColor; int mentionColor;
pressedColor = normalColor; pressedColor = normalColor;
mentionColor = resources.getColor(R.color.nc_author_text); mentionColor = resources.getColor(R.color.nc_author_text);
@ -74,8 +76,12 @@ public class MagicSystemMessageViewHolder extends MessageHolders.IncomingTextMes
if (message.getMessageParameters() != null && message.getMessageParameters().size() > 0) { if (message.getMessageParameters() != null && message.getMessageParameters().size() > 0) {
for (String key : message.getMessageParameters().keySet()) { for (String key : message.getMessageParameters().keySet()) {
Map<String, String> individualHashMap = message.getMessageParameters().get(key); Map<String, String> individualHashMap = message.getMessageParameters().get(key);
if (individualHashMap != null && (individualHashMap.get("type").equals("user") || individualHashMap.get("type").equals("guest") || individualHashMap.get("type").equals("call"))) { if (individualHashMap != null && (individualHashMap.get("type").equals("user")
messageString = DisplayUtils.searchAndColor(messageString, "@" + individualHashMap.get("name"), mentionColor); || individualHashMap.get("type").equals("guest")
|| individualHashMap.get("type").equals("call"))) {
messageString =
DisplayUtils.searchAndColor(messageString, "@" + individualHashMap.get("name"),
mentionColor);
} }
} }
} }

View File

@ -24,7 +24,8 @@ import android.view.View;
import com.nextcloud.talk.models.json.chat.ChatMessage; import com.nextcloud.talk.models.json.chat.ChatMessage;
import com.stfalcon.chatkit.messages.MessageHolders; import com.stfalcon.chatkit.messages.MessageHolders;
public class MagicUnreadNoticeMessageViewHolder extends MessageHolders.SystemMessageViewHolder<ChatMessage> { public class MagicUnreadNoticeMessageViewHolder
extends MessageHolders.SystemMessageViewHolder<ChatMessage> {
public MagicUnreadNoticeMessageViewHolder(View itemView) { public MagicUnreadNoticeMessageViewHolder(View itemView) {
super(itemView); super(itemView);

View File

@ -69,9 +69,10 @@ public interface NcApi {
*/ */
@GET @GET
Observable<ResponseBody> getContactsWithSearchParam(@Header("Authorization") String authorization, @Url String url, Observable<ResponseBody> getContactsWithSearchParam(@Header("Authorization") String authorization,
@Nullable @Query("shareTypes[]") List<String> listOfShareTypes, @QueryMap Map<String, Object> options); @Url String url,
@Nullable @Query("shareTypes[]") List<String> listOfShareTypes,
@QueryMap Map<String, Object> options);
/* /*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room
@ -106,10 +107,10 @@ public interface NcApi {
@FormUrlEncoded @FormUrlEncoded
@PUT @PUT
Observable<GenericOverall> renameRoom(@Header("Authorization") String authorization, @Url String url, Observable<GenericOverall> renameRoom(@Header("Authorization") String authorization,
@Url String url,
@Field("roomName") String roomName); @Field("roomName") String roomName);
/* /*
QueryMap items are as follows: QueryMap items are as follows:
- "newParticipant" : "user" - "newParticipant" : "user"
@ -117,76 +118,91 @@ public interface NcApi {
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room/roomToken/participants Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room/roomToken/participants
*/ */
@POST @POST
Observable<AddParticipantOverall> addParticipant(@Header("Authorization") String authorization, @Url String url, Observable<AddParticipantOverall> addParticipant(@Header("Authorization") String authorization,
@Url String url,
@QueryMap Map<String, String> options); @QueryMap Map<String, String> options);
// also used for removing a guest from a conversation // also used for removing a guest from a conversation
@DELETE @DELETE
Observable<GenericOverall> removeParticipantFromConversation(@Header("Authorization") String authorization, @Url String url, @Query("participant") String participantId); Observable<GenericOverall> removeParticipantFromConversation(
@Header("Authorization") String authorization, @Url String url,
@Query("participant") String participantId);
@POST @POST
Observable<GenericOverall> promoteUserToModerator(@Header("Authorization") String authorization, @Url String url, @Query("participant") String participantId); Observable<GenericOverall> promoteUserToModerator(@Header("Authorization") String authorization,
@Url String url, @Query("participant") String participantId);
@DELETE @DELETE
Observable<GenericOverall> demoteModeratorToUser(@Header("Authorization") String authorization, @Url String url, @Query("participant") String participantId); Observable<GenericOverall> demoteModeratorToUser(@Header("Authorization") String authorization,
@Url String url, @Query("participant") String participantId);
/* /*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room/roomToken/participants/self Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room/roomToken/participants/self
*/ */
@DELETE @DELETE
Observable<GenericOverall> removeSelfFromRoom(@Header("Authorization") String authorization, @Url String url); Observable<GenericOverall> removeSelfFromRoom(@Header("Authorization") String authorization,
@Url String url);
/* /*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room/roomToken/public Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room/roomToken/public
*/ */
@POST @POST
Observable<GenericOverall> makeRoomPublic(@Header("Authorization") String authorization, @Url String url); Observable<GenericOverall> makeRoomPublic(@Header("Authorization") String authorization,
@Url String url);
/* /*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room/roomToken/public Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room/roomToken/public
*/ */
@DELETE @DELETE
Observable<GenericOverall> makeRoomPrivate(@Header("Authorization") String authorization, @Url String url); Observable<GenericOverall> makeRoomPrivate(@Header("Authorization") String authorization,
@Url String url);
@DELETE @DELETE
Observable<GenericOverall> deleteRoom(@Header("Authorization") String authorization, @Url String url); Observable<GenericOverall> deleteRoom(@Header("Authorization") String authorization,
@Url String url);
/* /*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /call/callToken Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /call/callToken
*/ */
@GET @GET
Observable<ParticipantsOverall> getPeersForCall(@Header("Authorization") String authorization, @Url String url); Observable<ParticipantsOverall> getPeersForCall(@Header("Authorization") String authorization,
@Url String url);
@FormUrlEncoded @FormUrlEncoded
@POST @POST
Observable<RoomOverall> joinRoom(@Nullable @Header("Authorization") String authorization, @Url String url, @Nullable @Field("password") String password); Observable<RoomOverall> joinRoom(@Nullable @Header("Authorization") String authorization,
@Url String url, @Nullable @Field("password") String password);
@DELETE @DELETE
Observable<GenericOverall> leaveRoom(@Nullable @Header("Authorization") String authorization, @Url String url); Observable<GenericOverall> leaveRoom(@Nullable @Header("Authorization") String authorization,
@Url String url);
/* /*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /call/callToken Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /call/callToken
*/ */
@POST @POST
Observable<GenericOverall> joinCall(@Nullable @Header("Authorization") String authorization, @Url String url); Observable<GenericOverall> joinCall(@Nullable @Header("Authorization") String authorization,
@Url String url);
/* /*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /call/callToken Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /call/callToken
*/ */
@DELETE @DELETE
Observable<GenericOverall> leaveCall(@Nullable @Header("Authorization") String authorization, @Url String url); Observable<GenericOverall> leaveCall(@Nullable @Header("Authorization") String authorization,
@Url String url);
/* /*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /call/callToken/ping Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /call/callToken/ping
*/ */
@POST @POST
Observable<GenericOverall> pingCall(@Nullable @Header("Authorization") String authorization, @Url String url); Observable<GenericOverall> pingCall(@Nullable @Header("Authorization") String authorization,
@Url String url);
@GET @GET
Observable<SignalingSettingsOverall> getSignalingSettings(@Nullable @Header("Authorization") String authorization, Observable<SignalingSettingsOverall> getSignalingSettings(
@Nullable @Header("Authorization") String authorization,
@Url String url); @Url String url);
/* /*
@ -197,14 +213,16 @@ public interface NcApi {
*/ */
@FormUrlEncoded @FormUrlEncoded
@POST @POST
Observable<SignalingOverall> sendSignalingMessages(@Nullable @Header("Authorization") String authorization, @Url String url, Observable<SignalingOverall> sendSignalingMessages(
@Nullable @Header("Authorization") String authorization, @Url String url,
@Field("messages") String messages); @Field("messages") String messages);
/* /*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /signaling Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /signaling
*/ */
@GET @GET
Observable<SignalingOverall> pullSignalingMessages(@Nullable @Header("Authorization") String authorization, @Url Observable<SignalingOverall> pullSignalingMessages(
@Nullable @Header("Authorization") String authorization, @Url
String String
url); url);
@ -216,7 +234,8 @@ public interface NcApi {
*/ */
@GET @GET
Observable<UserProfileOverall> getUserProfile(@Header("Authorization") String authorization, @Url String url); Observable<UserProfileOverall> getUserProfile(@Header("Authorization") String authorization,
@Url String url);
/* /*
Server URL is: baseUrl + /status.php Server URL is: baseUrl + /status.php
@ -236,7 +255,8 @@ public interface NcApi {
*/ */
@POST @POST
Observable<PushRegistrationOverall> registerDeviceForNotificationsWithNextcloud(@Header("Authorization") Observable<PushRegistrationOverall> registerDeviceForNotificationsWithNextcloud(
@Header("Authorization")
String authorization, String authorization,
@Url String url, @Url String url,
@QueryMap Map<String, @QueryMap Map<String,
@ -252,7 +272,6 @@ public interface NcApi {
Observable<Void> registerDeviceForNotificationsWithProxy(@Url String url, Observable<Void> registerDeviceForNotificationsWithProxy(@Url String url,
@FieldMap Map<String, String> fields); @FieldMap Map<String, String> fields);
/* /*
QueryMap items are as follows: QueryMap items are as follows:
- "deviceIdentifier": "{{deviceIdentifier}}", - "deviceIdentifier": "{{deviceIdentifier}}",
@ -265,11 +284,13 @@ public interface NcApi {
@FormUrlEncoded @FormUrlEncoded
@PUT @PUT
Observable<GenericOverall> setPassword(@Header("Authorization") String authorization, @Url String url, Observable<GenericOverall> setPassword(@Header("Authorization") String authorization,
@Url String url,
@Field("password") String password); @Field("password") String password);
@GET @GET
Observable<CapabilitiesOverall> getCapabilities(@Header("Authorization") String authorization, @Url String url); Observable<CapabilitiesOverall> getCapabilities(@Header("Authorization") String authorization,
@Url String url);
/* /*
QueryMap items are as follows: QueryMap items are as follows:
@ -279,7 +300,8 @@ public interface NcApi {
- "lastKnownMessageId", int, use one from X-Chat-Last-Given - "lastKnownMessageId", int, use one from X-Chat-Last-Given
*/ */
@GET @GET
Observable<Response<ChatOverall>> pullChatMessages(@Header("Authorization") String authorization, @Url String url, Observable<Response<ChatOverall>> pullChatMessages(@Header("Authorization") String authorization,
@Url String url,
@QueryMap Map<String, Integer> fields); @QueryMap Map<String, Integer> fields);
/* /*
@ -290,23 +312,27 @@ public interface NcApi {
@FormUrlEncoded @FormUrlEncoded
@POST @POST
Observable<GenericOverall> sendChatMessage(@Header("Authorization") String authorization, @Url String url, Observable<GenericOverall> sendChatMessage(@Header("Authorization") String authorization,
@Url String url,
@Field("message") CharSequence message, @Field("message") CharSequence message,
@Field("actorDisplayName") String actorDisplayName); @Field("actorDisplayName") String actorDisplayName);
@GET @GET
Observable<MentionOverall> getMentionAutocompleteSuggestions(@Header("Authorization") String authorization, Observable<MentionOverall> getMentionAutocompleteSuggestions(
@Header("Authorization") String authorization,
@Url String url, @Query("search") String query, @Url String url, @Query("search") String query,
@Nullable @Query("limit") Integer limit); @Nullable @Query("limit") Integer limit);
// Url is: /api/{apiVersion}/room/{token}/pin // Url is: /api/{apiVersion}/room/{token}/pin
@POST @POST
Observable<GenericOverall> addConversationToFavorites(@Header("Authorization") String authorization, Observable<GenericOverall> addConversationToFavorites(
@Header("Authorization") String authorization,
@Url String url); @Url String url);
// Url is: /api/{apiVersion}/room/{token}/favorites // Url is: /api/{apiVersion}/room/{token}/favorites
@DELETE @DELETE
Observable<GenericOverall> removeConversationFromFavorites(@Header("Authorization") String authorization, Observable<GenericOverall> removeConversationFromFavorites(
@Header("Authorization") String authorization,
@Url String url); @Url String url);
@GET @GET
@ -315,16 +341,18 @@ public interface NcApi {
@FormUrlEncoded @FormUrlEncoded
@POST @POST
Observable<GenericOverall> setNotificationLevel(@Header("Authorization") String authorization, @Url String url, @Field("level") int level); Observable<GenericOverall> setNotificationLevel(@Header("Authorization") String authorization,
@Url String url, @Field("level") int level);
@FormUrlEncoded @FormUrlEncoded
@PUT @PUT
Observable<GenericOverall> setReadOnlyState(@Header("Authorization") String authorization, @Url String url, @Field("viewState") int state); Observable<GenericOverall> setReadOnlyState(@Header("Authorization") String authorization,
@Url String url, @Field("viewState") int state);
@FormUrlEncoded @FormUrlEncoded
@POST @POST
Observable<Void> createRemoteShare(@Nullable @Header("Authorization") String authorization, @Url String url, Observable<Void> createRemoteShare(@Nullable @Header("Authorization") String authorization,
@Url String url,
@Field("path") String remotePath, @Field("path") String remotePath,
@Field("shareWith") String roomToken, @Field("shareWith") String roomToken,
@Field("shareType") String shareType); @Field("shareType") String shareType);
@ -334,5 +362,4 @@ public interface NcApi {
Observable<GenericOverall> setLobbyForConversation(@Header("Authorization") String authorization, Observable<GenericOverall> setLobbyForConversation(@Header("Authorization") String authorization,
@Url String url, @Field("viewState") Integer state, @Url String url, @Field("viewState") Integer state,
@Field("timer") Long timer); @Field("timer") Long timer);
} }

View File

@ -29,7 +29,6 @@ import androidx.emoji.bundled.BundledEmojiCompatConfig
import androidx.emoji.text.EmojiCompat import androidx.emoji.text.EmojiCompat
import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleObserver
import androidx.multidex.MultiDex import androidx.multidex.MultiDex
import androidx.multidex.MultiDexApplication
import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.OneTimeWorkRequest import androidx.work.OneTimeWorkRequest
import androidx.work.PeriodicWorkRequest import androidx.work.PeriodicWorkRequest
@ -54,7 +53,6 @@ import com.nextcloud.talk.newarch.di.module.NetworkModule
import com.nextcloud.talk.newarch.di.module.StorageModule import com.nextcloud.talk.newarch.di.module.StorageModule
import com.nextcloud.talk.newarch.features.conversationsList.di.module.ConversationsListModule import com.nextcloud.talk.newarch.features.conversationsList.di.module.ConversationsListModule
import com.nextcloud.talk.utils.ClosedInterfaceImpl import com.nextcloud.talk.utils.ClosedInterfaceImpl
import com.nextcloud.talk.utils.DeviceUtils
import com.nextcloud.talk.utils.DisplayUtils import com.nextcloud.talk.utils.DisplayUtils
import com.nextcloud.talk.utils.OkHttpNetworkFetcherWithCache import com.nextcloud.talk.utils.OkHttpNetworkFetcherWithCache
import com.nextcloud.talk.utils.database.arbitrarystorage.ArbitraryStorageModule import com.nextcloud.talk.utils.database.arbitrarystorage.ArbitraryStorageModule
@ -78,7 +76,9 @@ import java.util.concurrent.TimeUnit
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@AutoComponent(modules = [BusModule::class, ContextModule::class, DatabaseModule::class, RestModule::class, UserModule::class, ArbitraryStorageModule::class]) @AutoComponent(
modules = [BusModule::class, ContextModule::class, DatabaseModule::class, RestModule::class, UserModule::class, ArbitraryStorageModule::class]
)
@Singleton @Singleton
@AutoInjector(NextcloudTalkApplication::class) @AutoInjector(NextcloudTalkApplication::class)
class NextcloudTalkApplication : Application(), LifecycleObserver { class NextcloudTalkApplication : Application(), LifecycleObserver {
@ -107,9 +107,13 @@ class NextcloudTalkApplication : Application(), LifecycleObserver {
} }
PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions.builder(this) PeerConnectionFactory.initialize(
.setEnableVideoHwAcceleration(MagicWebRTCUtils.shouldEnableVideoHardwareAcceleration()) PeerConnectionFactory.InitializationOptions.builder(this)
.createInitializationOptions()) .setEnableVideoHwAcceleration(
MagicWebRTCUtils.shouldEnableVideoHardwareAcceleration()
)
.createInitializationOptions()
)
} catch (e: UnsatisfiedLinkError) { } catch (e: UnsatisfiedLinkError) {
Log.w(TAG, e) Log.w(TAG, e)
} }
@ -140,11 +144,13 @@ class NextcloudTalkApplication : Application(), LifecycleObserver {
val imagePipelineConfig = ImagePipelineConfig.newBuilder(this) val imagePipelineConfig = ImagePipelineConfig.newBuilder(this)
.setNetworkFetcher(OkHttpNetworkFetcherWithCache(okHttpClient)) .setNetworkFetcher(OkHttpNetworkFetcherWithCache(okHttpClient))
.setMainDiskCacheConfig(DiskCacheConfig.newBuilder(this) .setMainDiskCacheConfig(
DiskCacheConfig.newBuilder(this)
.setMaxCacheSize(0) .setMaxCacheSize(0)
.setMaxCacheSizeOnLowDiskSpace(0) .setMaxCacheSizeOnLowDiskSpace(0)
.setMaxCacheSizeOnVeryLowDiskSpace(0) .setMaxCacheSizeOnVeryLowDiskSpace(0)
.build()) .build()
)
.build() .build()
Fresco.initialize(this, imagePipelineConfig) Fresco.initialize(this, imagePipelineConfig)
@ -152,18 +158,33 @@ class NextcloudTalkApplication : Application(), LifecycleObserver {
ClosedInterfaceImpl().providerInstallerInstallIfNeededAsync() ClosedInterfaceImpl().providerInstallerInstallIfNeededAsync()
val pushRegistrationWork = OneTimeWorkRequest.Builder(PushRegistrationWorker::class.java).build() val pushRegistrationWork = OneTimeWorkRequest.Builder(PushRegistrationWorker::class.java)
val accountRemovalWork = OneTimeWorkRequest.Builder(AccountRemovalWorker::class.java).build() .build()
val periodicCapabilitiesUpdateWork = PeriodicWorkRequest.Builder(CapabilitiesWorker::class.java, val accountRemovalWork = OneTimeWorkRequest.Builder(AccountRemovalWorker::class.java)
12, TimeUnit.HOURS).build() .build()
val capabilitiesUpdateWork = OneTimeWorkRequest.Builder(CapabilitiesWorker::class.java).build() val periodicCapabilitiesUpdateWork = PeriodicWorkRequest.Builder(
val signalingSettingsWork = OneTimeWorkRequest.Builder(SignalingSettingsWorker::class.java).build() CapabilitiesWorker::class.java,
12, TimeUnit.HOURS
)
.build()
val capabilitiesUpdateWork = OneTimeWorkRequest.Builder(CapabilitiesWorker::class.java)
.build()
val signalingSettingsWork = OneTimeWorkRequest.Builder(SignalingSettingsWorker::class.java)
.build()
WorkManager.getInstance().enqueue(pushRegistrationWork) WorkManager.getInstance()
WorkManager.getInstance().enqueue(accountRemovalWork) .enqueue(pushRegistrationWork)
WorkManager.getInstance().enqueue(capabilitiesUpdateWork) WorkManager.getInstance()
WorkManager.getInstance().enqueue(signalingSettingsWork) .enqueue(accountRemovalWork)
WorkManager.getInstance().enqueueUniquePeriodicWork("DailyCapabilitiesUpdateWork", ExistingPeriodicWorkPolicy.REPLACE, periodicCapabilitiesUpdateWork) WorkManager.getInstance()
.enqueue(capabilitiesUpdateWork)
WorkManager.getInstance()
.enqueue(signalingSettingsWork)
WorkManager.getInstance()
.enqueueUniquePeriodicWork(
"DailyCapabilitiesUpdateWork", ExistingPeriodicWorkPolicy.REPLACE,
periodicCapabilitiesUpdateWork
)
val config = BundledEmojiCompatConfig(this) val config = BundledEmojiCompatConfig(this)
config.setReplaceAll(true) config.setReplaceAll(true)
@ -178,7 +199,6 @@ class NextcloudTalkApplication : Application(), LifecycleObserver {
} }
//endregion //endregion
//region Protected methods //region Protected methods
protected fun buildComponent() { protected fun buildComponent() {
componentApplication = DaggerNextcloudTalkApplicationComponent.builder() componentApplication = DaggerNextcloudTalkApplicationComponent.builder()
@ -216,7 +236,9 @@ class NextcloudTalkApplication : Application(), LifecycleObserver {
when (theme) { when (theme) {
"night_no" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) "night_no" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
"night_yes" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) "night_yes" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
"battery_saver" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY) "battery_saver" -> AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY
)
else -> else ->
// will be "follow_system" only for now // will be "follow_system" only for now
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)

View File

@ -25,9 +25,9 @@ import android.text.Editable;
import android.text.Spanned; import android.text.Spanned;
import android.widget.EditText; import android.widget.EditText;
import com.facebook.widget.text.span.BetterImageSpan; import com.facebook.widget.text.span.BetterImageSpan;
import com.nextcloud.talk.models.json.mention.Mention;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.mention.Mention;
import com.nextcloud.talk.utils.DisplayUtils; import com.nextcloud.talk.utils.DisplayUtils;
import com.nextcloud.talk.utils.MagicCharPolicy; import com.nextcloud.talk.utils.MagicCharPolicy;
import com.nextcloud.talk.utils.text.Spans; import com.nextcloud.talk.utils.text.Spans;
@ -56,7 +56,7 @@ public class MentionAutocompleteCallback implements AutocompleteCallback<Mention
String replacement = item.getLabel(); String replacement = item.getLabel();
StringBuilder replacementStringBuilder = new StringBuilder(item.getLabel()); StringBuilder replacementStringBuilder = new StringBuilder(item.getLabel());
for(EmojiRange emojiRange : EmojiUtils.emojis(replacement)) { for (EmojiRange emojiRange : EmojiUtils.emojis(replacement)) {
replacementStringBuilder.delete(emojiRange.start, emojiRange.end); replacementStringBuilder.delete(emojiRange.start, emojiRange.end);
} }

View File

@ -50,7 +50,8 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
@AutoInjector(NextcloudTalkApplication.class) @AutoInjector(NextcloudTalkApplication.class)
public class BrowserFileItem extends AbstractFlexibleItem<BrowserFileItem.ViewHolder> implements IFilterable<String> { public class BrowserFileItem extends AbstractFlexibleItem<BrowserFileItem.ViewHolder>
implements IFilterable<String> {
@Inject @Inject
Context context; Context context;
private BrowserFile browserFile; private BrowserFile browserFile;
@ -58,11 +59,14 @@ public class BrowserFileItem extends AbstractFlexibleItem<BrowserFileItem.ViewHo
private SelectionInterface selectionInterface; private SelectionInterface selectionInterface;
private boolean selected; private boolean selected;
public BrowserFileItem(BrowserFile browserFile, UserEntity activeUser, SelectionInterface selectionInterface) { public BrowserFileItem(BrowserFile browserFile, UserEntity activeUser,
SelectionInterface selectionInterface) {
this.browserFile = browserFile; this.browserFile = browserFile;
this.activeUser = activeUser; this.activeUser = activeUser;
this.selectionInterface = selectionInterface; this.selectionInterface = selectionInterface;
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
} }
@Override @Override
@ -87,7 +91,6 @@ public class BrowserFileItem extends AbstractFlexibleItem<BrowserFileItem.ViewHo
@Override @Override
public ViewHolder createViewHolder(View view, FlexibleAdapter<IFlexible> adapter) { public ViewHolder createViewHolder(View view, FlexibleAdapter<IFlexible> adapter) {
return new ViewHolder(view, adapter); return new ViewHolder(view, adapter);
} }
private boolean isSelected() { private boolean isSelected() {
@ -99,7 +102,8 @@ public class BrowserFileItem extends AbstractFlexibleItem<BrowserFileItem.ViewHo
} }
@Override @Override
public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, ViewHolder holder, int position, List<Object> payloads) { public void bindViewHolder(FlexibleAdapter<IFlexible> adapter, ViewHolder holder, int position,
List<Object> payloads) {
holder.fileIconImageView.setController(null); holder.fileIconImageView.setController(null);
if (browserFile.isEncrypted()) { if (browserFile.isEncrypted()) {
@ -118,7 +122,9 @@ public class BrowserFileItem extends AbstractFlexibleItem<BrowserFileItem.ViewHo
holder.fileFavoriteImageView.setVisibility(View.GONE); holder.fileFavoriteImageView.setVisibility(View.GONE);
} }
holder.fileIconImageView.getHierarchy().setPlaceholderImage(context.getDrawable(DrawableUtils.INSTANCE.getDrawableResourceIdForMimeType(browserFile.getMimeType()))); holder.fileIconImageView.getHierarchy()
.setPlaceholderImage(context.getDrawable(
DrawableUtils.INSTANCE.getDrawableResourceIdForMimeType(browserFile.getMimeType())));
if (browserFile.isHasPreview()) { if (browserFile.isHasPreview()) {
String path = ApiUtils.getUrlForFilePreviewWithRemotePath(activeUser.getBaseUrl(), String path = ApiUtils.getUrlForFilePreviewWithRemotePath(activeUser.getBaseUrl(),
@ -137,7 +143,8 @@ public class BrowserFileItem extends AbstractFlexibleItem<BrowserFileItem.ViewHo
holder.filenameTextView.setText(browserFile.getDisplayName()); holder.filenameTextView.setText(browserFile.getDisplayName());
holder.fileModifiedTextView.setText(String.format(context.getString(R.string.nc_last_modified), holder.fileModifiedTextView.setText(String.format(context.getString(R.string.nc_last_modified),
Formatter.formatShortFileSize(context, browserFile.getSize()), Formatter.formatShortFileSize(context, browserFile.getSize()),
DateUtils.INSTANCE.getLocalDateTimeStringFromTimestamp(browserFile.getModifiedTimestamp()))); DateUtils.INSTANCE.getLocalDateTimeStringFromTimestamp(
browserFile.getModifiedTimestamp())));
setSelected(selectionInterface.isPathSelected(browserFile.getPath())); setSelected(selectionInterface.isPathSelected(browserFile.getPath()));
holder.selectFileCheckbox.setChecked(isSelected()); holder.selectFileCheckbox.setChecked(isSelected());

View File

@ -103,7 +103,9 @@ public class BrowserController extends BaseController implements ListingInterfac
public BrowserController(Bundle args) { public BrowserController(Bundle args) {
super(); super();
setHasOptionsMenu(true); setHasOptionsMenu(true);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
browserType = Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_BROWSER_TYPE())); browserType = Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_BROWSER_TYPE()));
activeUser = Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY())); activeUser = Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY()));
roomToken = args.getString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN()); roomToken = args.getString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN());
@ -225,7 +227,8 @@ public class BrowserController extends BaseController implements ListingInterfac
listingAbstractClass.cancelAllJobs(); listingAbstractClass.cancelAllJobs();
changeEnabledStatusForBarItems(false); changeEnabledStatusForBarItems(false);
listingAbstractClass.getFiles(path, activeUser, BrowserType.DAV_BROWSER.equals(browserType) ? okHttpClient : null); listingAbstractClass.getFiles(path, activeUser,
BrowserType.DAV_BROWSER.equals(browserType) ? okHttpClient : null);
} }
@Override @Override
@ -252,7 +255,6 @@ public class BrowserController extends BaseController implements ListingInterfac
getActivity().runOnUiThread(() -> { getActivity().runOnUiThread(() -> {
adapter.notifyDataSetChanged(); adapter.notifyDataSetChanged();
changeEnabledStatusForBarItems(true); changeEnabledStatusForBarItems(true);
}); });
} }
} }
@ -314,7 +316,8 @@ public class BrowserController extends BaseController implements ListingInterfac
fastScroller.setBubbleTextCreator(position -> { fastScroller.setBubbleTextCreator(position -> {
IFlexible abstractFlexibleItem = adapter.getItem(position); IFlexible abstractFlexibleItem = adapter.getItem(position);
if (abstractFlexibleItem instanceof BrowserFileItem) { if (abstractFlexibleItem instanceof BrowserFileItem) {
return String.valueOf(((BrowserFileItem) adapter.getItem(position)).getModel().getDisplayName().charAt(0)); return String.valueOf(
((BrowserFileItem) adapter.getItem(position)).getModel().getDisplayName().charAt(0));
} else { } else {
return ""; return "";
} }

View File

@ -68,7 +68,8 @@ public class BrowserFile {
if (property instanceof ResourceType) { if (property instanceof ResourceType) {
browserFile.isFile = browserFile.isFile =
!(((ResourceType) property).getTypes().contains(ResourceType.Companion.getCOLLECTION())); !(((ResourceType) property).getTypes()
.contains(ResourceType.Companion.getCOLLECTION()));
} }
if (property instanceof GetLastModified) { if (property instanceof GetLastModified) {

View File

@ -34,7 +34,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserException;
public class NCEncrypted implements Property { public class NCEncrypted implements Property {
public static final Name NAME = new Name(DavUtils.NC_NAMESPACE, DavUtils.EXTENDED_PROPERTY_IS_ENCRYPTED); public static final Name NAME =
new Name(DavUtils.NC_NAMESPACE, DavUtils.EXTENDED_PROPERTY_IS_ENCRYPTED);
@Getter @Getter
@Setter @Setter

View File

@ -34,7 +34,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserException;
public class NCPreview implements Property { public class NCPreview implements Property {
public static final Property.Name NAME = new Property.Name(DavUtils.NC_NAMESPACE, DavUtils.EXTENDED_PROPERTY_HAS_PREVIEW); public static final Property.Name NAME =
new Property.Name(DavUtils.NC_NAMESPACE, DavUtils.EXTENDED_PROPERTY_HAS_PREVIEW);
@Getter @Getter
@Setter @Setter

View File

@ -34,7 +34,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserException;
public class OCFavorite implements Property { public class OCFavorite implements Property {
public static final Property.Name NAME = new Property.Name(DavUtils.OC_NAMESPACE, DavUtils.EXTENDED_PROPERTY_FAVORITE); public static final Property.Name NAME =
new Property.Name(DavUtils.OC_NAMESPACE, DavUtils.EXTENDED_PROPERTY_FAVORITE);
@Getter @Getter
@Setter @Setter

View File

@ -34,7 +34,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserException;
public class OCId implements Property { public class OCId implements Property {
public static final Name NAME = new Name(DavUtils.OC_NAMESPACE, DavUtils.EXTENDED_PROPERTY_NAME_REMOTE_ID); public static final Name NAME =
new Name(DavUtils.OC_NAMESPACE, DavUtils.EXTENDED_PROPERTY_NAME_REMOTE_ID);
@Getter @Getter
@Setter @Setter

View File

@ -34,7 +34,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserException;
public class OCSize implements Property { public class OCSize implements Property {
public static final Property.Name NAME = new Property.Name(DavUtils.OC_NAMESPACE, DavUtils.EXTENDED_PROPERTY_NAME_SIZE); public static final Property.Name NAME =
new Property.Name(DavUtils.OC_NAMESPACE, DavUtils.EXTENDED_PROPERTY_NAME_SIZE);
@Getter @Getter
@Setter @Setter

View File

@ -35,7 +35,8 @@ public abstract class ListingAbstractClass {
this.listingInterface = listingInterface; this.listingInterface = listingInterface;
} }
public abstract void getFiles(String path, UserEntity currentUser, @Nullable OkHttpClient okHttpClient); public abstract void getFiles(String path, UserEntity currentUser,
@Nullable OkHttpClient okHttpClient);
public void cancelAllJobs() { public void cancelAllJobs() {
handler.removeCallbacksAndMessages(null); handler.removeCallbacksAndMessages(null);

View File

@ -113,7 +113,5 @@ public class DavUtils {
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View File

@ -42,11 +42,14 @@ public class ReadFilesystemOperation {
private final int depth; private final int depth;
private final String basePath; private final String basePath;
public ReadFilesystemOperation(OkHttpClient okHttpClient, UserEntity currentUser, String path, int depth) { public ReadFilesystemOperation(OkHttpClient okHttpClient, UserEntity currentUser, String path,
int depth) {
OkHttpClient.Builder okHttpClientBuilder = okHttpClient.newBuilder(); OkHttpClient.Builder okHttpClientBuilder = okHttpClient.newBuilder();
okHttpClientBuilder.followRedirects(false); okHttpClientBuilder.followRedirects(false);
okHttpClientBuilder.followSslRedirects(false); okHttpClientBuilder.followSslRedirects(false);
okHttpClientBuilder.authenticator(new RestModule.MagicAuthenticator(ApiUtils.getCredentials(currentUser.getUsername(), currentUser.getToken()), "Authorization")); okHttpClientBuilder.authenticator(new RestModule.MagicAuthenticator(
ApiUtils.getCredentials(currentUser.getUsername(), currentUser.getToken()),
"Authorization"));
this.okHttpClient = okHttpClientBuilder.build(); this.okHttpClient = okHttpClientBuilder.build();
this.basePath = currentUser.getBaseUrl() + DavUtils.DAV_PATH + currentUser.getUserId(); this.basePath = currentUser.getBaseUrl() + DavUtils.DAV_PATH + currentUser.getUserId();
this.url = basePath + path; this.url = basePath + path;
@ -84,7 +87,6 @@ public class ReadFilesystemOperation {
e.printStackTrace(); e.printStackTrace();
} }
remoteFiles.add(BrowserFile.getModelFromResponse(rootElement[0], remoteFiles.add(BrowserFile.getModelFromResponse(rootElement[0],
rootElement[0].getHref().toString().substring(basePath.length()))); rootElement[0].getHref().toString().substring(basePath.length())));
for (Response memberElement : memberElements) { for (Response memberElement : memberElements) {
@ -95,5 +97,4 @@ public class ReadFilesystemOperation {
davResponse.setData(remoteFiles); davResponse.setData(remoteFiles);
return davResponse; return davResponse;
} }
} }

View File

@ -36,9 +36,6 @@ import autodagger.AutoInjector;
import butterknife.BindView; import butterknife.BindView;
import com.bluelinelabs.conductor.RouterTransaction; import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler; import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.nextcloud.talk.models.json.conversations.RoomsOverall;
import com.nextcloud.talk.models.json.generic.Status;
import com.nextcloud.talk.models.json.userprofile.UserProfileOverall;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
@ -48,6 +45,9 @@ import com.nextcloud.talk.jobs.CapabilitiesWorker;
import com.nextcloud.talk.jobs.PushRegistrationWorker; import com.nextcloud.talk.jobs.PushRegistrationWorker;
import com.nextcloud.talk.jobs.SignalingSettingsWorker; import com.nextcloud.talk.jobs.SignalingSettingsWorker;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.conversations.RoomsOverall;
import com.nextcloud.talk.models.json.generic.Status;
import com.nextcloud.talk.models.json.userprofile.UserProfileOverall;
import com.nextcloud.talk.newarch.features.conversationsList.ConversationsListView; import com.nextcloud.talk.newarch.features.conversationsList.ConversationsListView;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.ClosedInterfaceImpl; import com.nextcloud.talk.utils.ClosedInterfaceImpl;
@ -67,7 +67,6 @@ import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode; import org.greenrobot.eventbus.ThreadMode;
@AutoInjector(NextcloudTalkApplication.class) @AutoInjector(NextcloudTalkApplication.class)
public class AccountVerificationController extends BaseController { public class AccountVerificationController extends BaseController {
@ -134,7 +133,9 @@ public class AccountVerificationController extends BaseController {
@Override @Override
protected void onViewBound(@NonNull View view) { protected void onViewBound(@NonNull View view) {
super.onViewBound(view); super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
if (getActivity() != null) { if (getActivity() != null) {
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
@ -144,7 +145,8 @@ public class AccountVerificationController extends BaseController {
getActionBar().hide(); getActionBar().hide();
} }
if (isAccountImport && !baseUrl.startsWith("http://") && !baseUrl.startsWith("https://") || (!TextUtils if (isAccountImport && !baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")
|| (!TextUtils
.isEmpty(originalProtocol) && !baseUrl.startsWith(originalProtocol))) { .isEmpty(originalProtocol) && !baseUrl.startsWith(originalProtocol))) {
determineBaseUrlProtocol(true); determineBaseUrlProtocol(true);
} else { } else {
@ -190,7 +192,8 @@ public class AccountVerificationController extends BaseController {
} }
if (isAccountImport) { if (isAccountImport) {
getRouter().replaceTopController(RouterTransaction.with(new WebViewLoginController(baseUrl, getRouter().replaceTopController(
RouterTransaction.with(new WebViewLoginController(baseUrl,
false, username, "")) false, username, ""))
.pushChangeHandler(new HorizontalChangeHandler()) .pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new HorizontalChangeHandler())); .popChangeHandler(new HorizontalChangeHandler()));
@ -232,8 +235,10 @@ public class AccountVerificationController extends BaseController {
@Override @Override
public void onError(Throwable e) { public void onError(Throwable e) {
if (getActivity() != null && getResources() != null) { if (getActivity() != null && getResources() != null) {
getActivity().runOnUiThread(() -> progressText.setText(String.format(getResources().getString( getActivity().runOnUiThread(
R.string.nc_nextcloud_talk_app_not_installed), getResources().getString(R.string.nc_app_name)))); () -> progressText.setText(String.format(getResources().getString(
R.string.nc_nextcloud_talk_app_not_installed),
getResources().getString(R.string.nc_app_name))));
} }
ApplicationWideMessageHolder.getInstance().setMessageType( ApplicationWideMessageHolder.getInstance().setMessageType(
@ -268,7 +273,8 @@ public class AccountVerificationController extends BaseController {
if (new ClosedInterfaceImpl().isGooglePlayServicesAvailable()) { if (new ClosedInterfaceImpl().isGooglePlayServicesAvailable()) {
registerForPush(); registerForPush();
} else { } else {
getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" + getActivity().runOnUiThread(
() -> progressText.setText(progressText.getText().toString() + "\n" +
getResources().getString(R.string.nc_push_disabled))); getResources().getString(R.string.nc_push_disabled)));
fetchAndStoreCapabilities(); fetchAndStoreCapabilities();
} }
@ -281,7 +287,6 @@ public class AccountVerificationController extends BaseController {
getResources().getString( getResources().getString(
R.string.nc_display_name_not_stored)); R.string.nc_display_name_not_stored));
abortVerification(); abortVerification();
} }
@Override @Override
@ -318,7 +323,8 @@ public class AccountVerificationController extends BaseController {
storeProfile(displayName, userProfileOverall.getOcs().getData().getUserId()); storeProfile(displayName, userProfileOverall.getOcs().getData().getUserId());
} else { } else {
if (getActivity() != null) { if (getActivity() != null) {
getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" + getActivity().runOnUiThread(
() -> progressText.setText(progressText.getText().toString() + "\n" +
getResources().getString(R.string.nc_display_name_not_fetched))); getResources().getString(R.string.nc_display_name_not_fetched)));
} }
abortVerification(); abortVerification();
@ -328,11 +334,11 @@ public class AccountVerificationController extends BaseController {
@Override @Override
public void onError(Throwable e) { public void onError(Throwable e) {
if (getActivity() != null) { if (getActivity() != null) {
getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" + getActivity().runOnUiThread(
() -> progressText.setText(progressText.getText().toString() + "\n" +
getResources().getString(R.string.nc_display_name_not_fetched))); getResources().getString(R.string.nc_display_name_not_fetched)));
} }
abortVerification(); abortVerification();
} }
@Override @Override
@ -343,22 +349,27 @@ public class AccountVerificationController extends BaseController {
} }
private void registerForPush() { private void registerForPush() {
OneTimeWorkRequest pushRegistrationWork = new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build(); OneTimeWorkRequest pushRegistrationWork =
new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
WorkManager.getInstance().enqueue(pushRegistrationWork); WorkManager.getInstance().enqueue(pushRegistrationWork);
} }
@Subscribe(threadMode = ThreadMode.BACKGROUND) @Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(EventStatus eventStatus) { public void onMessageEvent(EventStatus eventStatus) {
if (eventStatus.getEventType().equals(EventStatus.EventType.PUSH_REGISTRATION)) { if (eventStatus.getEventType().equals(EventStatus.EventType.PUSH_REGISTRATION)) {
if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood() && getActivity() != null) { if (internalAccountId == eventStatus.getUserId()
getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" + && !eventStatus.isAllGood()
&& getActivity() != null) {
getActivity().runOnUiThread(
() -> progressText.setText(progressText.getText().toString() + "\n" +
getResources().getString(R.string.nc_push_disabled))); getResources().getString(R.string.nc_push_disabled)));
} }
fetchAndStoreCapabilities(); fetchAndStoreCapabilities();
} else if (eventStatus.getEventType().equals(EventStatus.EventType.CAPABILITIES_FETCH)) { } else if (eventStatus.getEventType().equals(EventStatus.EventType.CAPABILITIES_FETCH)) {
if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood()) { if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood()) {
if (getActivity() != null) { if (getActivity() != null) {
getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" + getActivity().runOnUiThread(
() -> progressText.setText(progressText.getText().toString() + "\n" +
getResources().getString(R.string.nc_capabilities_failed))); getResources().getString(R.string.nc_capabilities_failed)));
} }
abortVerification(); abortVerification();
@ -368,14 +379,14 @@ public class AccountVerificationController extends BaseController {
} else if (eventStatus.getEventType().equals(EventStatus.EventType.SIGNALING_SETTINGS)) { } else if (eventStatus.getEventType().equals(EventStatus.EventType.SIGNALING_SETTINGS)) {
if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood()) { if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood()) {
if (getActivity() != null) { if (getActivity() != null) {
getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" + getActivity().runOnUiThread(
() -> progressText.setText(progressText.getText().toString() + "\n" +
getResources().getString(R.string.nc_external_server_failed))); getResources().getString(R.string.nc_external_server_failed)));
} }
} }
proceedWithLogin(); proceedWithLogin();
} }
} }
private void fetchAndStoreCapabilities() { private void fetchAndStoreCapabilities() {
@ -383,7 +394,8 @@ public class AccountVerificationController extends BaseController {
.putLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), internalAccountId) .putLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), internalAccountId)
.build(); .build();
OneTimeWorkRequest pushNotificationWork = new OneTimeWorkRequest.Builder(CapabilitiesWorker.class) OneTimeWorkRequest pushNotificationWork =
new OneTimeWorkRequest.Builder(CapabilitiesWorker.class)
.setInputData(userData) .setInputData(userData)
.build(); .build();
WorkManager.getInstance().enqueue(pushNotificationWork); WorkManager.getInstance().enqueue(pushNotificationWork);
@ -394,7 +406,8 @@ public class AccountVerificationController extends BaseController {
.putLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), internalAccountId) .putLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), internalAccountId)
.build(); .build();
OneTimeWorkRequest signalingSettings = new OneTimeWorkRequest.Builder(SignalingSettingsWorker.class) OneTimeWorkRequest signalingSettings =
new OneTimeWorkRequest.Builder(SignalingSettingsWorker.class)
.setInputData(userData) .setInputData(userData)
.build(); .build();
WorkManager.getInstance().enqueue(signalingSettings); WorkManager.getInstance().enqueue(signalingSettings);
@ -422,7 +435,6 @@ public class AccountVerificationController extends BaseController {
} }
} }
@Override @Override
protected void onDestroyView(@NonNull View view) { protected void onDestroyView(@NonNull View view) {
super.onDestroyView(view); super.onDestroyView(view);
@ -471,8 +483,6 @@ public class AccountVerificationController extends BaseController {
if (getActivity() != null) { if (getActivity() != null) {
getRouter().popToRoot(); getRouter().popToRoot();
} }
} else { } else {
if (userUtils.anyUserExists()) { if (userUtils.anyUserExists()) {
getRouter().setRoot(RouterTransaction.with(new ConversationsListView()) getRouter().setRoot(RouterTransaction.with(new ConversationsListView())
@ -488,5 +498,4 @@ public class AccountVerificationController extends BaseController {
} }
} }
} }
} }

View File

@ -56,17 +56,6 @@ import com.bluelinelabs.logansquare.LoganSquare;
import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.drawee.view.SimpleDraweeView;
import com.nextcloud.talk.models.ExternalSignalingServer;
import com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.models.json.conversations.RoomOverall;
import com.nextcloud.talk.models.json.conversations.RoomsOverall;
import com.nextcloud.talk.models.json.generic.GenericOverall;
import com.nextcloud.talk.models.json.participants.Participant;
import com.nextcloud.talk.models.json.participants.ParticipantsOverall;
import com.nextcloud.talk.models.json.signaling.*;
import com.nextcloud.talk.models.json.signaling.settings.IceServer;
import com.nextcloud.talk.models.json.signaling.settings.SignalingSettingsOverall;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
@ -77,7 +66,25 @@ import com.nextcloud.talk.events.NetworkEvent;
import com.nextcloud.talk.events.PeerConnectionEvent; import com.nextcloud.talk.events.PeerConnectionEvent;
import com.nextcloud.talk.events.SessionDescriptionSendEvent; import com.nextcloud.talk.events.SessionDescriptionSendEvent;
import com.nextcloud.talk.events.WebSocketCommunicationEvent; import com.nextcloud.talk.events.WebSocketCommunicationEvent;
import com.nextcloud.talk.models.ExternalSignalingServer;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.models.json.conversations.RoomOverall;
import com.nextcloud.talk.models.json.conversations.RoomsOverall;
import com.nextcloud.talk.models.json.generic.GenericOverall;
import com.nextcloud.talk.models.json.participants.Participant;
import com.nextcloud.talk.models.json.participants.ParticipantsOverall;
import com.nextcloud.talk.models.json.signaling.DataChannelMessage;
import com.nextcloud.talk.models.json.signaling.DataChannelMessageNick;
import com.nextcloud.talk.models.json.signaling.NCIceCandidate;
import com.nextcloud.talk.models.json.signaling.NCMessagePayload;
import com.nextcloud.talk.models.json.signaling.NCMessageWrapper;
import com.nextcloud.talk.models.json.signaling.NCSignalingMessage;
import com.nextcloud.talk.models.json.signaling.Signaling;
import com.nextcloud.talk.models.json.signaling.SignalingOverall;
import com.nextcloud.talk.models.json.signaling.settings.IceServer;
import com.nextcloud.talk.models.json.signaling.settings.SignalingSettingsOverall;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.DisplayUtils; import com.nextcloud.talk.utils.DisplayUtils;
import com.nextcloud.talk.utils.NotificationUtils; import com.nextcloud.talk.utils.NotificationUtils;
@ -258,14 +265,11 @@ public class CallController extends BaseController {
private MediaPlayer mediaPlayer; private MediaPlayer mediaPlayer;
@Parcel
public enum CallStatus {
CALLING, CALLING_TIMEOUT, ESTABLISHED, IN_CONVERSATION, RECONNECTING, OFFLINE, LEAVING, PUBLISHER_FAILED
}
public CallController(Bundle args) { public CallController(Bundle args) {
super(); super();
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
roomId = args.getString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), ""); roomId = args.getString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), "");
roomToken = args.getString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), ""); roomToken = args.getString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), "");
@ -273,7 +277,8 @@ public class CallController extends BaseController {
conversationPassword = args.getString(BundleKeys.INSTANCE.getKEY_CONVERSATION_PASSWORD(), ""); conversationPassword = args.getString(BundleKeys.INSTANCE.getKEY_CONVERSATION_PASSWORD(), "");
isVoiceOnlyCall = args.getBoolean(BundleKeys.INSTANCE.getKEY_CALL_VOICE_ONLY(), false); isVoiceOnlyCall = args.getBoolean(BundleKeys.INSTANCE.getKEY_CALL_VOICE_ONLY(), false);
credentials = ApiUtils.getCredentials(conversationUser.getUsername(), conversationUser.getToken()); credentials =
ApiUtils.getCredentials(conversationUser.getUsername(), conversationUser.getToken());
baseUrl = args.getString(BundleKeys.INSTANCE.getKEY_MODIFIED_BASE_URL(), ""); baseUrl = args.getString(BundleKeys.INSTANCE.getKEY_MODIFIED_BASE_URL(), "");
@ -302,7 +307,8 @@ public class CallController extends BaseController {
if (camera2EnumeratorIsSupported) { if (camera2EnumeratorIsSupported) {
cameraEnumerator = new Camera2Enumerator(getActivity()); cameraEnumerator = new Camera2Enumerator(getActivity());
} else { } else {
cameraEnumerator = new Camera1Enumerator(MagicWebRTCUtils.shouldEnableVideoHardwareAcceleration()); cameraEnumerator =
new Camera1Enumerator(MagicWebRTCUtils.shouldEnableVideoHardwareAcceleration());
} }
} }
} }
@ -371,15 +377,21 @@ public class CallController extends BaseController {
offerToReceiveVideoString = "false"; offerToReceiveVideoString = "false";
} }
sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", offerToReceiveVideoString)); sdpConstraints.mandatory.add(
new MediaConstraints.KeyValuePair("OfferToReceiveVideo", offerToReceiveVideoString));
sdpConstraintsForMCU.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "false")); sdpConstraintsForMCU.mandatory.add(
sdpConstraintsForMCU.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false")); new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "false"));
sdpConstraintsForMCU.mandatory.add(
new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
sdpConstraintsForMCU.optional.add(new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true")); sdpConstraintsForMCU.optional.add(
sdpConstraintsForMCU.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true")); new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true"));
sdpConstraintsForMCU.optional.add(
new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
sdpConstraints.optional.add(new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true")); sdpConstraints.optional.add(
new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true"));
sdpConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true")); sdpConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
if (!isVoiceOnlyCall) { if (!isVoiceOnlyCall) {
@ -443,7 +455,6 @@ public class CallController extends BaseController {
} }
} }
private void checkPermissions() { private void checkPermissions() {
if (isVoiceOnlyCall) { if (isVoiceOnlyCall) {
onMicrophoneClick(); onMicrophoneClick();
@ -451,14 +462,14 @@ public class CallController extends BaseController {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(PERMISSIONS_CALL, 100); requestPermissions(PERMISSIONS_CALL, 100);
} else { } else {
onRequestPermissionsResult(100, PERMISSIONS_CALL, new int[]{1, 1}); onRequestPermissionsResult(100, PERMISSIONS_CALL, new int[] { 1, 1 });
} }
} }
} }
private boolean isConnectionEstablished() { private boolean isConnectionEstablished() {
return (currentCallStatus.equals(CallStatus.ESTABLISHED) || currentCallStatus.equals(CallStatus.IN_CONVERSATION)); return (currentCallStatus.equals(CallStatus.ESTABLISHED) || currentCallStatus.equals(
CallStatus.IN_CONVERSATION));
} }
@AfterPermissionGranted(100) @AfterPermissionGranted(100)
@ -485,11 +496,11 @@ public class CallController extends BaseController {
if (!isConnectionEstablished()) { if (!isConnectionEstablished()) {
fetchSignalingSettings(); fetchSignalingSettings();
} }
} else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(), } else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(
getActivity(),
PERMISSIONS_CALL)) { PERMISSIONS_CALL)) {
checkIfSomeAreApproved(); checkIfSomeAreApproved();
} }
} }
private void checkIfSomeAreApproved() { private void checkIfSomeAreApproved() {
@ -502,12 +513,14 @@ public class CallController extends BaseController {
cameraSwitchButton.setVisibility(View.VISIBLE); cameraSwitchButton.setVisibility(View.VISIBLE);
} }
if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA)) { if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(),
PERMISSIONS_CAMERA)) {
if (!videoOn) { if (!videoOn) {
onCameraClick(); onCameraClick();
} }
} else { } else {
cameraControlButton.getHierarchy().setPlaceholderImage(R.drawable.ic_videocam_off_white_24px); cameraControlButton.getHierarchy()
.setPlaceholderImage(R.drawable.ic_videocam_off_white_24px);
cameraControlButton.setAlpha(0.7f); cameraControlButton.setAlpha(0.7f);
cameraSwitchButton.setVisibility(View.GONE); cameraSwitchButton.setVisibility(View.GONE);
} }
@ -536,7 +549,8 @@ public class CallController extends BaseController {
} }
} }
if (getActivity() != null && (EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA) || if (getActivity() != null && (EffortlessPermissions.hasPermissions(getActivity(),
PERMISSIONS_CAMERA) ||
EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_MICROPHONE))) { EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_MICROPHONE))) {
checkIfSomeAreApproved(); checkIfSomeAreApproved();
} else if (!isConnectionEstablished()) { } else if (!isConnectionEstablished()) {
@ -545,22 +559,24 @@ public class CallController extends BaseController {
} }
private void onAudioManagerDevicesChanged( private void onAudioManagerDevicesChanged(
final MagicAudioManager.AudioDevice device, final Set<MagicAudioManager.AudioDevice> availableDevices) { final MagicAudioManager.AudioDevice device,
final Set<MagicAudioManager.AudioDevice> availableDevices) {
Log.d(TAG, "onAudioManagerDevicesChanged: " + availableDevices + ", " Log.d(TAG, "onAudioManagerDevicesChanged: " + availableDevices + ", "
+ "selected: " + device); + "selected: " + device);
final boolean shouldDisableProximityLock = (device.equals(MagicAudioManager.AudioDevice.WIRED_HEADSET) final boolean shouldDisableProximityLock =
(device.equals(MagicAudioManager.AudioDevice.WIRED_HEADSET)
|| device.equals(MagicAudioManager.AudioDevice.SPEAKER_PHONE) || device.equals(MagicAudioManager.AudioDevice.SPEAKER_PHONE)
|| device.equals(MagicAudioManager.AudioDevice.BLUETOOTH)); || device.equals(MagicAudioManager.AudioDevice.BLUETOOTH));
if (shouldDisableProximityLock) { if (shouldDisableProximityLock) {
powerManagerUtils.updatePhoneState(PowerManagerUtils.PhoneState.WITHOUT_PROXIMITY_SENSOR_LOCK); powerManagerUtils.updatePhoneState(
PowerManagerUtils.PhoneState.WITHOUT_PROXIMITY_SENSOR_LOCK);
} else { } else {
powerManagerUtils.updatePhoneState(PowerManagerUtils.PhoneState.WITH_PROXIMITY_SENSOR_LOCK); powerManagerUtils.updatePhoneState(PowerManagerUtils.PhoneState.WITH_PROXIMITY_SENSOR_LOCK);
} }
} }
private void cameraInitialization() { private void cameraInitialization() {
videoCapturer = createCameraCapturer(cameraEnumerator); videoCapturer = createCameraCapturer(cameraEnumerator);
@ -572,7 +588,6 @@ public class CallController extends BaseController {
localVideoTrack.setEnabled(false); localVideoTrack.setEnabled(false);
localVideoTrack.addSink(pipVideoView); localVideoTrack.addSink(pipVideoView);
} }
} }
private void microphoneInitialization() { private void microphoneInitialization() {
@ -599,7 +614,6 @@ public class CallController extends BaseController {
} }
} }
// Front facing camera not found, try something else // Front facing camera not found, try something else
Logging.d(TAG, "Looking for other cameras."); Logging.d(TAG, "Looking for other cameras.");
for (String deviceName : deviceNames) { for (String deviceName : deviceNames) {
@ -638,16 +652,19 @@ public class CallController extends BaseController {
if (audioManager != null) { if (audioManager != null) {
audioManager.toggleUseSpeakerphone(); audioManager.toggleUseSpeakerphone();
if (audioManager.isSpeakerphoneAutoOn()) { if (audioManager.isSpeakerphoneAutoOn()) {
callControlEnableSpeaker.getHierarchy().setPlaceholderImage(R.drawable.ic_volume_up_white_24dp); callControlEnableSpeaker.getHierarchy()
.setPlaceholderImage(R.drawable.ic_volume_up_white_24dp);
} else { } else {
callControlEnableSpeaker.getHierarchy().setPlaceholderImage(R.drawable.ic_volume_mute_white_24dp); callControlEnableSpeaker.getHierarchy()
.setPlaceholderImage(R.drawable.ic_volume_mute_white_24dp);
} }
} }
} }
@OnClick(R.id.call_control_microphone) @OnClick(R.id.call_control_microphone)
public void onMicrophoneClick() { public void onMicrophoneClick() {
if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_MICROPHONE)) { if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(),
PERMISSIONS_MICROPHONE)) {
if (getActivity() != null && !appPreferences.getPushToTalkIntroShown()) { if (getActivity() != null && !appPreferences.getPushToTalkIntroShown()) {
spotlightView = new SpotlightView.Builder(getActivity()) spotlightView = new SpotlightView.Builder(getActivity())
@ -679,7 +696,8 @@ public class CallController extends BaseController {
if (audioOn) { if (audioOn) {
microphoneControlButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_white_24px); microphoneControlButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_white_24px);
} else { } else {
microphoneControlButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_off_white_24px); microphoneControlButton.getHierarchy()
.setPlaceholderImage(R.drawable.ic_mic_off_white_24px);
} }
toggleMedia(audioOn, false); toggleMedia(audioOn, false);
@ -692,8 +710,8 @@ public class CallController extends BaseController {
if (isVoiceOnlyCall && !isConnectionEstablished()) { if (isVoiceOnlyCall && !isConnectionEstablished()) {
fetchSignalingSettings(); fetchSignalingSettings();
} }
} else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(
} else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(), getActivity(),
PERMISSIONS_MICROPHONE)) { PERMISSIONS_MICROPHONE)) {
// Microphone permission is permanently denied so we cannot request it normally. // Microphone permission is permanently denied so we cannot request it normally.
@ -704,7 +722,7 @@ public class CallController extends BaseController {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(PERMISSIONS_MICROPHONE, 100); requestPermissions(PERMISSIONS_MICROPHONE, 100);
} else { } else {
onRequestPermissionsResult(100, PERMISSIONS_MICROPHONE, new int[]{1}); onRequestPermissionsResult(100, PERMISSIONS_MICROPHONE, new int[] { 1 });
} }
} }
} }
@ -717,7 +735,8 @@ public class CallController extends BaseController {
@OnClick(R.id.call_control_camera) @OnClick(R.id.call_control_camera)
public void onCameraClick() { public void onCameraClick() {
if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA)) { if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(),
PERMISSIONS_CAMERA)) {
videoOn = !videoOn; videoOn = !videoOn;
if (videoOn) { if (videoOn) {
@ -726,12 +745,14 @@ public class CallController extends BaseController {
cameraSwitchButton.setVisibility(View.VISIBLE); cameraSwitchButton.setVisibility(View.VISIBLE);
} }
} else { } else {
cameraControlButton.getHierarchy().setPlaceholderImage(R.drawable.ic_videocam_off_white_24px); cameraControlButton.getHierarchy()
.setPlaceholderImage(R.drawable.ic_videocam_off_white_24px);
cameraSwitchButton.setVisibility(View.GONE); cameraSwitchButton.setVisibility(View.GONE);
} }
toggleMedia(videoOn, true); toggleMedia(videoOn, true);
} else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(), } else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(
getActivity(),
PERMISSIONS_CAMERA)) { PERMISSIONS_CAMERA)) {
// Camera permission is permanently denied so we cannot request it normally. // Camera permission is permanently denied so we cannot request it normally.
OpenAppDetailsDialogFragment.show( OpenAppDetailsDialogFragment.show(
@ -742,13 +763,12 @@ public class CallController extends BaseController {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(PERMISSIONS_CAMERA, 100); requestPermissions(PERMISSIONS_CAMERA, 100);
} else { } else {
onRequestPermissionsResult(100, PERMISSIONS_CAMERA, new int[]{1}); onRequestPermissionsResult(100, PERMISSIONS_CAMERA, new int[] { 1 });
}
} }
} }
} @OnClick({ R.id.call_control_switch_camera, R.id.pip_video_view })
@OnClick({R.id.call_control_switch_camera, R.id.pip_video_view})
public void switchCamera() { public void switchCamera() {
CameraVideoCapturer cameraVideoCapturer = (CameraVideoCapturer) videoCapturer; CameraVideoCapturer cameraVideoCapturer = (CameraVideoCapturer) videoCapturer;
if (cameraVideoCapturer != null) { if (cameraVideoCapturer != null) {
@ -814,17 +834,17 @@ public class CallController extends BaseController {
} }
} else { } else {
for (int i = 0; i < magicPeerConnectionWrapperList.size(); i++) { for (int i = 0; i < magicPeerConnectionWrapperList.size(); i++) {
if (magicPeerConnectionWrapperList.get(i).getSessionId().equals(webSocketClient.getSessionId())) { if (magicPeerConnectionWrapperList.get(i)
.getSessionId()
.equals(webSocketClient.getSessionId())) {
magicPeerConnectionWrapperList.get(i).sendChannelData(new DataChannelMessage(message)); magicPeerConnectionWrapperList.get(i).sendChannelData(new DataChannelMessage(message));
break; break;
} }
} }
} }
} }
} }
private void animateCallControls(boolean show, long startDelay) { private void animateCallControls(boolean show, long startDelay) {
if (isVoiceOnlyCall) { if (isVoiceOnlyCall) {
if (spotlightView != null && spotlightView.getVisibility() != View.GONE) { if (spotlightView != null && spotlightView.getVisibility() != View.GONE) {
@ -909,7 +929,6 @@ public class CallController extends BaseController {
} }
}); });
} }
} }
} }
@ -941,11 +960,16 @@ public class CallController extends BaseController {
externalSignalingServer = new ExternalSignalingServer(); externalSignalingServer = new ExternalSignalingServer();
if (!TextUtils.isEmpty(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer()) && if (!TextUtils.isEmpty(
!TextUtils.isEmpty(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket())) { signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer()) &&
!TextUtils.isEmpty(signalingSettingsOverall.getOcs()
.getSettings()
.getExternalSignalingTicket())) {
externalSignalingServer = new ExternalSignalingServer(); externalSignalingServer = new ExternalSignalingServer();
externalSignalingServer.setExternalSignalingServer(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer()); externalSignalingServer.setExternalSignalingServer(
externalSignalingServer.setExternalSignalingTicket(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket()); signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer());
externalSignalingServer.setExternalSignalingTicket(
signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket());
hasExternalSignalingServer = true; hasExternalSignalingServer = true;
} else { } else {
hasExternalSignalingServer = false; hasExternalSignalingServer = false;
@ -954,7 +978,8 @@ public class CallController extends BaseController {
if (!conversationUser.getUserId().equals("?")) { if (!conversationUser.getUserId().equals("?")) {
try { try {
userUtils.createOrUpdateUser(null, null, null, null, null, null, null, userUtils.createOrUpdateUser(null, null, null, null, null, null, null,
conversationUser.getId(), null, null, LoganSquare.serialize(externalSignalingServer)) conversationUser.getId(), null, null,
LoganSquare.serialize(externalSignalingServer))
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.subscribe(); .subscribe();
} catch (IOException exception) { } catch (IOException exception) {
@ -963,9 +988,11 @@ public class CallController extends BaseController {
} }
if (signalingSettingsOverall.getOcs().getSettings().getStunServers() != null) { if (signalingSettingsOverall.getOcs().getSettings().getStunServers() != null) {
for (int i = 0; i < signalingSettingsOverall.getOcs().getSettings().getStunServers().size(); for (int i = 0;
i < signalingSettingsOverall.getOcs().getSettings().getStunServers().size();
i++) { i++) {
iceServer = signalingSettingsOverall.getOcs().getSettings().getStunServers().get(i); iceServer =
signalingSettingsOverall.getOcs().getSettings().getStunServers().get(i);
if (TextUtils.isEmpty(iceServer.getUsername()) || TextUtils.isEmpty(iceServer if (TextUtils.isEmpty(iceServer.getUsername()) || TextUtils.isEmpty(iceServer
.getCredential())) { .getCredential())) {
iceServers.add(new PeerConnection.IceServer(iceServer.getUrl())); iceServers.add(new PeerConnection.IceServer(iceServer.getUrl()));
@ -977,9 +1004,11 @@ public class CallController extends BaseController {
} }
if (signalingSettingsOverall.getOcs().getSettings().getTurnServers() != null) { if (signalingSettingsOverall.getOcs().getSettings().getTurnServers() != null) {
for (int i = 0; i < signalingSettingsOverall.getOcs().getSettings().getTurnServers().size(); for (int i = 0;
i < signalingSettingsOverall.getOcs().getSettings().getTurnServers().size();
i++) { i++) {
iceServer = signalingSettingsOverall.getOcs().getSettings().getTurnServers().get(i); iceServer =
signalingSettingsOverall.getOcs().getSettings().getTurnServers().get(i);
for (int j = 0; j < iceServer.getUrls().size(); j++) { for (int j = 0; j < iceServer.getUrls().size(); j++) {
if (TextUtils.isEmpty(iceServer.getUsername()) || TextUtils.isEmpty(iceServer if (TextUtils.isEmpty(iceServer.getUsername()) || TextUtils.isEmpty(iceServer
.getCredential())) { .getCredential())) {
@ -1154,14 +1183,18 @@ public class CallController extends BaseController {
urlToken = roomToken; urlToken = roomToken;
} }
if (!conversationUser.hasSpreedFeatureCapability("no-ping") && !TextUtils.isEmpty(roomId)) { if (!conversationUser.hasSpreedFeatureCapability("no-ping") && !TextUtils.isEmpty(
NotificationUtils.INSTANCE.cancelExistingNotificationsForRoom(getApplicationContext(), conversationUser, roomId); roomId)) {
NotificationUtils.INSTANCE.cancelExistingNotificationsForRoom(
getApplicationContext(), conversationUser, roomId);
} else if (!TextUtils.isEmpty(roomToken)) { } else if (!TextUtils.isEmpty(roomToken)) {
NotificationUtils.INSTANCE.cancelExistingNotificationsForRoom(getApplicationContext(), conversationUser, roomToken); NotificationUtils.INSTANCE.cancelExistingNotificationsForRoom(
getApplicationContext(), conversationUser, roomToken);
} }
if (!hasExternalSignalingServer) { if (!hasExternalSignalingServer) {
ncApi.pullSignalingMessages(credentials, ApiUtils.getUrlForSignaling(baseUrl, urlToken)) ncApi.pullSignalingMessages(credentials,
ApiUtils.getUrlForSignaling(baseUrl, urlToken))
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.repeatWhen(observable -> observable) .repeatWhen(observable -> observable)
@ -1176,9 +1209,11 @@ public class CallController extends BaseController {
@Override @Override
public void onNext(SignalingOverall signalingOverall) { public void onNext(SignalingOverall signalingOverall) {
if (signalingOverall.getOcs().getSignalings() != null) { if (signalingOverall.getOcs().getSignalings() != null) {
for (int i = 0; i < signalingOverall.getOcs().getSignalings().size(); i++) { for (int i = 0; i < signalingOverall.getOcs().getSignalings().size();
i++) {
try { try {
receivedSignalingMessage(signalingOverall.getOcs().getSignalings().get(i)); receivedSignalingMessage(
signalingOverall.getOcs().getSignalings().get(i));
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, "Failed to process received signaling" + Log.e(TAG, "Failed to process received signaling" +
" message"); " message");
@ -1197,8 +1232,6 @@ public class CallController extends BaseController {
dispose(signalingDisposable); dispose(signalingDisposable);
} }
}); });
} }
} }
} }
@ -1275,19 +1308,22 @@ public class CallController extends BaseController {
break; break;
case "participantsUpdate": case "participantsUpdate":
if (webSocketCommunicationEvent.getHashMap().get("roomToken").equals(roomToken)) { if (webSocketCommunicationEvent.getHashMap().get("roomToken").equals(roomToken)) {
processUsersInRoom((List<HashMap<String, Object>>) webSocketClient.getJobWithId(Integer.valueOf(webSocketCommunicationEvent.getHashMap().get("jobId")))); processUsersInRoom((List<HashMap<String, Object>>) webSocketClient.getJobWithId(
Integer.valueOf(webSocketCommunicationEvent.getHashMap().get("jobId"))));
} }
break; break;
case "signalingMessage": case "signalingMessage":
processMessage((NCSignalingMessage) webSocketClient.getJobWithId(Integer.valueOf(webSocketCommunicationEvent.getHashMap().get("jobId")))); processMessage((NCSignalingMessage) webSocketClient.getJobWithId(
Integer.valueOf(webSocketCommunicationEvent.getHashMap().get("jobId"))));
break; break;
case "peerReadyForRequestingOffer": case "peerReadyForRequestingOffer":
webSocketClient.requestOfferForSessionIdWithType(webSocketCommunicationEvent.getHashMap().get("sessionId"), "video"); webSocketClient.requestOfferForSessionIdWithType(
webSocketCommunicationEvent.getHashMap().get("sessionId"), "video");
break; break;
} }
} }
@OnClick({R.id.pip_video_view, R.id.remote_renderers_layout}) @OnClick({ R.id.pip_video_view, R.id.remote_renderers_layout })
public void showCallControls() { public void showCallControls() {
animateCallControls(true, 0); animateCallControls(true, 0);
} }
@ -1319,7 +1355,8 @@ public class CallController extends BaseController {
if ("usersInRoom".equals(messageType)) { if ("usersInRoom".equals(messageType)) {
processUsersInRoom((List<HashMap<String, Object>>) signaling.getMessageWrapper()); processUsersInRoom((List<HashMap<String, Object>>) signaling.getMessageWrapper());
} else if ("message".equals(messageType)) { } else if ("message".equals(messageType)) {
NCSignalingMessage ncSignalingMessage = LoganSquare.parse(signaling.getMessageWrapper().toString(), NCSignalingMessage ncSignalingMessage =
LoganSquare.parse(signaling.getMessageWrapper().toString(),
NCSignalingMessage.class); NCSignalingMessage.class);
processMessage(ncSignalingMessage); processMessage(ncSignalingMessage);
} else { } else {
@ -1328,13 +1365,15 @@ public class CallController extends BaseController {
} }
private void processMessage(NCSignalingMessage ncSignalingMessage) { private void processMessage(NCSignalingMessage ncSignalingMessage) {
if (ncSignalingMessage.getRoomType().equals("video") || ncSignalingMessage.getRoomType().equals("screen")) { if (ncSignalingMessage.getRoomType().equals("video") || ncSignalingMessage.getRoomType()
.equals("screen")) {
MagicPeerConnectionWrapper magicPeerConnectionWrapper = MagicPeerConnectionWrapper magicPeerConnectionWrapper =
getPeerConnectionWrapperForSessionIdAndType(ncSignalingMessage.getFrom(), getPeerConnectionWrapperForSessionIdAndType(ncSignalingMessage.getFrom(),
ncSignalingMessage.getRoomType(), false); ncSignalingMessage.getRoomType(), false);
String type = null; String type = null;
if (ncSignalingMessage.getPayload() != null && ncSignalingMessage.getPayload().getType() != null) { if (ncSignalingMessage.getPayload() != null
&& ncSignalingMessage.getPayload().getType() != null) {
type = ncSignalingMessage.getPayload().getType(); type = ncSignalingMessage.getPayload().getType();
} else if (ncSignalingMessage.getType() != null) { } else if (ncSignalingMessage.getType() != null) {
type = ncSignalingMessage.getType(); type = ncSignalingMessage.getType();
@ -1359,7 +1398,8 @@ public class CallController extends BaseController {
sessionDescriptionStringWithPreferredCodec); sessionDescriptionStringWithPreferredCodec);
if (magicPeerConnectionWrapper.getPeerConnection() != null) { if (magicPeerConnectionWrapper.getPeerConnection() != null) {
magicPeerConnectionWrapper.getPeerConnection().setRemoteDescription(magicPeerConnectionWrapper magicPeerConnectionWrapper.getPeerConnection()
.setRemoteDescription(magicPeerConnectionWrapper
.getMagicSdpObserver(), sessionDescriptionWithPreferredCodec); .getMagicSdpObserver(), sessionDescriptionWithPreferredCodec);
} }
break; break;
@ -1423,7 +1463,6 @@ public class CallController extends BaseController {
localAudioTrack = null; localAudioTrack = null;
localVideoTrack = null; localVideoTrack = null;
if (TextUtils.isEmpty(credentials) && hasExternalSignalingServer) { if (TextUtils.isEmpty(credentials) && hasExternalSignalingServer) {
WebSocketConnectionHelper.deleteExternalSignalingInstanceForUserEntity(-1); WebSocketConnectionHelper.deleteExternalSignalingInstanceForUserEntity(-1);
} }
@ -1455,7 +1494,8 @@ public class CallController extends BaseController {
if (isMultiSession) { if (isMultiSession) {
if (shutDownView && getActivity() != null) { if (shutDownView && getActivity() != null) {
getActivity().finish(); getActivity().finish();
} else if (!shutDownView && (currentCallStatus.equals(CallStatus.RECONNECTING) || currentCallStatus.equals(CallStatus.PUBLISHER_FAILED))) { } else if (!shutDownView && (currentCallStatus.equals(CallStatus.RECONNECTING)
|| currentCallStatus.equals(CallStatus.PUBLISHER_FAILED))) {
initiateCall(); initiateCall();
} }
} else { } else {
@ -1476,7 +1516,8 @@ public class CallController extends BaseController {
} }
private void leaveRoom(boolean shutDownView) { private void leaveRoom(boolean shutDownView) {
ncApi.leaveRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken)) ncApi.leaveRoom(credentials,
ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken))
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<GenericOverall>() { .subscribe(new Observer<GenericOverall>() {
@ -1555,7 +1596,8 @@ public class CallController extends BaseController {
hasMCU = hasExternalSignalingServer && webSocketClient != null && webSocketClient.hasMCU(); hasMCU = hasExternalSignalingServer && webSocketClient != null && webSocketClient.hasMCU();
for (String sessionId : newSessions) { for (String sessionId : newSessions) {
getPeerConnectionWrapperForSessionIdAndType(sessionId, "video", hasMCU && sessionId.equals(webSocketClient.getSessionId())); getPeerConnectionWrapperForSessionIdAndType(sessionId, "video",
hasMCU && sessionId.equals(webSocketClient.getSessionId()));
} }
if (newSessions.size() > 0 && !currentCallStatus.equals(CallStatus.IN_CONVERSATION)) { if (newSessions.size() > 0 && !currentCallStatus.equals(CallStatus.IN_CONVERSATION)) {
@ -1582,7 +1624,8 @@ public class CallController extends BaseController {
for (Participant participant : participantsOverall.getOcs().getData()) { for (Participant participant : participantsOverall.getOcs().getData()) {
participantMap.put(participant.getSessionId(), participant); participantMap.put(participant.getSessionId(), participant);
if (getActivity() != null) { if (getActivity() != null) {
getActivity().runOnUiThread(() -> setupAvatarForSession(participant.getSessionId())); getActivity().runOnUiThread(
() -> setupAvatarForSession(participant.getSessionId()));
} }
} }
} }
@ -1604,9 +1647,11 @@ public class CallController extends BaseController {
magicPeerConnectionWrapperList.remove(magicPeerConnectionWrapper); magicPeerConnectionWrapperList.remove(magicPeerConnectionWrapper);
} }
private MagicPeerConnectionWrapper getPeerConnectionWrapperForSessionId(String sessionId, String type) { private MagicPeerConnectionWrapper getPeerConnectionWrapperForSessionId(String sessionId,
String type) {
for (int i = 0; i < magicPeerConnectionWrapperList.size(); i++) { for (int i = 0; i < magicPeerConnectionWrapperList.size(); i++) {
if (magicPeerConnectionWrapperList.get(i).getSessionId().equals(sessionId) && magicPeerConnectionWrapperList.get(i).getVideoStreamType().equals(type)) { if (magicPeerConnectionWrapperList.get(i).getSessionId().equals(sessionId)
&& magicPeerConnectionWrapperList.get(i).getVideoStreamType().equals(type)) {
return magicPeerConnectionWrapperList.get(i); return magicPeerConnectionWrapperList.get(i);
} }
} }
@ -1614,22 +1659,25 @@ public class CallController extends BaseController {
return null; return null;
} }
private MagicPeerConnectionWrapper getPeerConnectionWrapperForSessionIdAndType(String sessionId, String type, boolean publisher) { private MagicPeerConnectionWrapper getPeerConnectionWrapperForSessionIdAndType(String sessionId,
String type, boolean publisher) {
MagicPeerConnectionWrapper magicPeerConnectionWrapper; MagicPeerConnectionWrapper magicPeerConnectionWrapper;
if ((magicPeerConnectionWrapper = getPeerConnectionWrapperForSessionId(sessionId, type)) != null) { if ((magicPeerConnectionWrapper = getPeerConnectionWrapperForSessionId(sessionId, type))
!= null) {
return magicPeerConnectionWrapper; return magicPeerConnectionWrapper;
} else { } else {
if (hasMCU && publisher) { if (hasMCU && publisher) {
magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory, magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory,
iceServers, sdpConstraintsForMCU, sessionId, callSession, localMediaStream, true, true, type); iceServers, sdpConstraintsForMCU, sessionId, callSession, localMediaStream, true, true,
type);
} else if (hasMCU) { } else if (hasMCU) {
magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory, magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory,
iceServers, sdpConstraints, sessionId, callSession, null, false, true, type); iceServers, sdpConstraints, sessionId, callSession, null, false, true, type);
} else { } else {
if (!"screen".equals(type)) { if (!"screen".equals(type)) {
magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory, magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory,
iceServers, sdpConstraints, sessionId, callSession, localMediaStream, false, false, type); iceServers, sdpConstraints, sessionId, callSession, localMediaStream, false, false,
type);
} else { } else {
magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory, magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory,
iceServers, sdpConstraints, sessionId, callSession, null, false, false, type); iceServers, sdpConstraints, sessionId, callSession, null, false, false, type);
@ -1646,7 +1694,8 @@ public class CallController extends BaseController {
} }
} }
private List<MagicPeerConnectionWrapper> getPeerConnectionWrapperListForSessionId(String sessionId) { private List<MagicPeerConnectionWrapper> getPeerConnectionWrapperListForSessionId(
String sessionId) {
List<MagicPeerConnectionWrapper> internalList = new ArrayList<>(); List<MagicPeerConnectionWrapper> internalList = new ArrayList<>();
for (MagicPeerConnectionWrapper magicPeerConnectionWrapper : magicPeerConnectionWrapperList) { for (MagicPeerConnectionWrapper magicPeerConnectionWrapper : magicPeerConnectionWrapperList) {
if (magicPeerConnectionWrapper.getSessionId().equals(sessionId)) { if (magicPeerConnectionWrapper.getSessionId().equals(sessionId)) {
@ -1660,7 +1709,8 @@ public class CallController extends BaseController {
private void endPeerConnection(String sessionId, boolean justScreen) { private void endPeerConnection(String sessionId, boolean justScreen) {
List<MagicPeerConnectionWrapper> magicPeerConnectionWrappers; List<MagicPeerConnectionWrapper> magicPeerConnectionWrappers;
MagicPeerConnectionWrapper magicPeerConnectionWrapper; MagicPeerConnectionWrapper magicPeerConnectionWrapper;
if (!(magicPeerConnectionWrappers = getPeerConnectionWrapperListForSessionId(sessionId)).isEmpty() if (!(magicPeerConnectionWrappers =
getPeerConnectionWrapperListForSessionId(sessionId)).isEmpty()
&& getActivity() != null) { && getActivity() != null) {
for (int i = 0; i < magicPeerConnectionWrappers.size(); i++) { for (int i = 0; i < magicPeerConnectionWrappers.size(); i++) {
magicPeerConnectionWrapper = magicPeerConnectionWrappers.get(i); magicPeerConnectionWrapper = magicPeerConnectionWrappers.get(i);
@ -1694,12 +1744,13 @@ public class CallController extends BaseController {
@Subscribe(threadMode = ThreadMode.MAIN) @Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(ConfigurationChangeEvent configurationChangeEvent) { public void onMessageEvent(ConfigurationChangeEvent configurationChangeEvent) {
powerManagerUtils.setOrientation(Objects.requireNonNull(getResources()).getConfiguration().orientation); powerManagerUtils.setOrientation(
Objects.requireNonNull(getResources()).getConfiguration().orientation);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
remoteRenderersLayout.setOrientation(LinearLayout.HORIZONTAL); remoteRenderersLayout.setOrientation(LinearLayout.HORIZONTAL);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { } else if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_PORTRAIT) {
remoteRenderersLayout.setOrientation(LinearLayout.VERTICAL); remoteRenderersLayout.setOrientation(LinearLayout.VERTICAL);
} }
@ -1707,14 +1758,16 @@ public class CallController extends BaseController {
} }
private void setPipVideoViewDimensions() { private void setPipVideoViewDimensions() {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) pipVideoView.getLayoutParams(); FrameLayout.LayoutParams layoutParams =
(FrameLayout.LayoutParams) pipVideoView.getLayoutParams();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
remoteRenderersLayout.setOrientation(LinearLayout.HORIZONTAL); remoteRenderersLayout.setOrientation(LinearLayout.HORIZONTAL);
layoutParams.height = (int) getResources().getDimension(R.dimen.large_preview_dimension); layoutParams.height = (int) getResources().getDimension(R.dimen.large_preview_dimension);
layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT;
pipVideoView.setLayoutParams(layoutParams); pipVideoView.setLayoutParams(layoutParams);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { } else if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_PORTRAIT) {
remoteRenderersLayout.setOrientation(LinearLayout.VERTICAL); remoteRenderersLayout.setOrientation(LinearLayout.VERTICAL);
layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams.width = (int) getResources().getDimension(R.dimen.large_preview_dimension); layoutParams.width = (int) getResources().getDimension(R.dimen.large_preview_dimension);
@ -1724,18 +1777,22 @@ public class CallController extends BaseController {
@Subscribe(threadMode = ThreadMode.MAIN) @Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(PeerConnectionEvent peerConnectionEvent) { public void onMessageEvent(PeerConnectionEvent peerConnectionEvent) {
if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent.PeerConnectionEventType if (peerConnectionEvent.getPeerConnectionEventType()
.equals(PeerConnectionEvent.PeerConnectionEventType
.PEER_CLOSED)) { .PEER_CLOSED)) {
endPeerConnection(peerConnectionEvent.getSessionId(), peerConnectionEvent.getVideoStreamType().equals("screen")); endPeerConnection(peerConnectionEvent.getSessionId(),
peerConnectionEvent.getVideoStreamType().equals("screen"));
} else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.PeerConnectionEventType.SENSOR_FAR) || .PeerConnectionEventType.SENSOR_FAR) ||
peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.PeerConnectionEventType.SENSOR_NEAR)) { .PeerConnectionEventType.SENSOR_NEAR)) {
if (!isVoiceOnlyCall) { if (!isVoiceOnlyCall) {
boolean enableVideo = peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent boolean enableVideo =
peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.PeerConnectionEventType.SENSOR_FAR) && videoOn; .PeerConnectionEventType.SENSOR_FAR) && videoOn;
if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA) && if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(),
PERMISSIONS_CAMERA) &&
(currentCallStatus.equals(CallStatus.CALLING) || isConnectionEstablished()) && videoOn (currentCallStatus.equals(CallStatus.CALLING) || isConnectionEstablished()) && videoOn
&& enableVideo != localVideoTrack.enabled()) { && enableVideo != localVideoTrack.enabled()) {
toggleMedia(enableVideo, true); toggleMedia(enableVideo, true);
@ -1743,16 +1800,20 @@ public class CallController extends BaseController {
} }
} else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.PeerConnectionEventType.NICK_CHANGE)) { .PeerConnectionEventType.NICK_CHANGE)) {
gotNick(peerConnectionEvent.getSessionId(), peerConnectionEvent.getNick(), true, peerConnectionEvent.getVideoStreamType()); gotNick(peerConnectionEvent.getSessionId(), peerConnectionEvent.getNick(), true,
peerConnectionEvent.getVideoStreamType());
} else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.PeerConnectionEventType.VIDEO_CHANGE) && !isVoiceOnlyCall) { .PeerConnectionEventType.VIDEO_CHANGE) && !isVoiceOnlyCall) {
gotAudioOrVideoChange(true, peerConnectionEvent.getSessionId() + "+" + peerConnectionEvent.getVideoStreamType(), gotAudioOrVideoChange(true,
peerConnectionEvent.getSessionId() + "+" + peerConnectionEvent.getVideoStreamType(),
peerConnectionEvent.getChangeValue()); peerConnectionEvent.getChangeValue());
} else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.PeerConnectionEventType.AUDIO_CHANGE)) { .PeerConnectionEventType.AUDIO_CHANGE)) {
gotAudioOrVideoChange(false, peerConnectionEvent.getSessionId() + "+" + peerConnectionEvent.getVideoStreamType(), gotAudioOrVideoChange(false,
peerConnectionEvent.getSessionId() + "+" + peerConnectionEvent.getVideoStreamType(),
peerConnectionEvent.getChangeValue()); peerConnectionEvent.getChangeValue());
} else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent.PeerConnectionEventType.PUBLISHER_FAILED)) { } else if (peerConnectionEvent.getPeerConnectionEventType()
.equals(PeerConnectionEvent.PeerConnectionEventType.PUBLISHER_FAILED)) {
currentCallStatus = CallStatus.PUBLISHER_FAILED; currentCallStatus = CallStatus.PUBLISHER_FAILED;
webSocketClient.clearResumeId(); webSocketClient.clearResumeId();
hangup(false); hangup(false);
@ -1797,7 +1858,6 @@ public class CallController extends BaseController {
}); });
break; break;
} }
} }
} }
@ -1806,14 +1866,17 @@ public class CallController extends BaseController {
if (mediaStreamEvent.getMediaStream() != null) { if (mediaStreamEvent.getMediaStream() != null) {
setupVideoStreamForLayout(mediaStreamEvent.getMediaStream(), mediaStreamEvent.getSession(), setupVideoStreamForLayout(mediaStreamEvent.getMediaStream(), mediaStreamEvent.getSession(),
mediaStreamEvent.getMediaStream().videoTracks != null mediaStreamEvent.getMediaStream().videoTracks != null
&& mediaStreamEvent.getMediaStream().videoTracks.size() > 0, mediaStreamEvent.getVideoStreamType()); && mediaStreamEvent.getMediaStream().videoTracks.size() > 0,
mediaStreamEvent.getVideoStreamType());
} else { } else {
setupVideoStreamForLayout(null, mediaStreamEvent.getSession(), false, mediaStreamEvent.getVideoStreamType()); setupVideoStreamForLayout(null, mediaStreamEvent.getSession(), false,
mediaStreamEvent.getVideoStreamType());
} }
} }
@Subscribe(threadMode = ThreadMode.BACKGROUND) @Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(SessionDescriptionSendEvent sessionDescriptionSend) throws IOException { public void onMessageEvent(SessionDescriptionSendEvent sessionDescriptionSend)
throws IOException {
NCMessageWrapper ncMessageWrapper = new NCMessageWrapper(); NCMessageWrapper ncMessageWrapper = new NCMessageWrapper();
ncMessageWrapper.setEv("message"); ncMessageWrapper.setEv("message");
ncMessageWrapper.setSessionId(callSession); ncMessageWrapper.setSessionId(callSession);
@ -1831,17 +1894,16 @@ public class CallController extends BaseController {
ncMessagePayload.setIceCandidate(sessionDescriptionSend.getNcIceCandidate()); ncMessagePayload.setIceCandidate(sessionDescriptionSend.getNcIceCandidate());
} }
// Set all we need // Set all we need
ncSignalingMessage.setPayload(ncMessagePayload); ncSignalingMessage.setPayload(ncMessagePayload);
ncMessageWrapper.setSignalingMessage(ncSignalingMessage); ncMessageWrapper.setSignalingMessage(ncSignalingMessage);
if (!hasExternalSignalingServer) { if (!hasExternalSignalingServer) {
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{") stringBuilder.append("{")
.append("\"fn\":\"") .append("\"fn\":\"")
.append(StringEscapeUtils.escapeJson(LoganSquare.serialize(ncMessageWrapper.getSignalingMessage()))).append("\"") .append(StringEscapeUtils.escapeJson(
LoganSquare.serialize(ncMessageWrapper.getSignalingMessage()))).append("\"")
.append(",") .append(",")
.append("\"sessionId\":") .append("\"sessionId\":")
.append("\"").append(StringEscapeUtils.escapeJson(callSession)).append("\"") .append("\"").append(StringEscapeUtils.escapeJson(callSession)).append("\"")
@ -1925,7 +1987,8 @@ public class CallController extends BaseController {
DraweeController draweeController = Fresco.newDraweeControllerBuilder() DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(avatarImageView.getController()) .setOldController(avatarImageView.getController())
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(baseUrl, .setImageRequest(
DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(baseUrl,
userId, userId,
R.dimen.avatar_size_big), null)) R.dimen.avatar_size_big), null))
.build(); .build();
@ -1936,18 +1999,23 @@ public class CallController extends BaseController {
} }
} }
private void setupVideoStreamForLayout(@Nullable MediaStream mediaStream, String session, boolean enable, String videoStreamType) { private void setupVideoStreamForLayout(@Nullable MediaStream mediaStream, String session,
boolean enable, String videoStreamType) {
boolean isInitialLayoutSetupForPeer = false; boolean isInitialLayoutSetupForPeer = false;
if (remoteRenderersLayout.findViewWithTag(session) == null) { if (remoteRenderersLayout.findViewWithTag(session) == null) {
setupNewPeerLayout(session, videoStreamType); setupNewPeerLayout(session, videoStreamType);
isInitialLayoutSetupForPeer = true; isInitialLayoutSetupForPeer = true;
} }
RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(session + "+" + videoStreamType); RelativeLayout relativeLayout =
remoteRenderersLayout.findViewWithTag(session + "+" + videoStreamType);
SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id.surface_view); SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id.surface_view);
SimpleDraweeView imageView = relativeLayout.findViewById(R.id.avatarImageView); SimpleDraweeView imageView = relativeLayout.findViewById(R.id.avatarImageView);
if (mediaStream != null && mediaStream.videoTracks != null && mediaStream.videoTracks.size() > 0 && enable) { if (mediaStream != null
&& mediaStream.videoTracks != null
&& mediaStream.videoTracks.size() > 0
&& enable) {
VideoTrack videoTrack = mediaStream.videoTracks.get(0); VideoTrack videoTrack = mediaStream.videoTracks.get(0);
videoTrack.addSink(surfaceViewRenderer); videoTrack.addSink(surfaceViewRenderer);
@ -1996,7 +2064,8 @@ public class CallController extends BaseController {
} }
private void setupNewPeerLayout(String session, String type) { private void setupNewPeerLayout(String session, String type) {
if (remoteRenderersLayout.findViewWithTag(session + "+" + type) == null && getActivity() != null) { if (remoteRenderersLayout.findViewWithTag(session + "+" + type) == null
&& getActivity() != null) {
getActivity().runOnUiThread(() -> { getActivity().runOnUiThread(() -> {
RelativeLayout relativeLayout = (RelativeLayout) RelativeLayout relativeLayout = (RelativeLayout)
getActivity().getLayoutInflater().inflate(R.layout.call_item, remoteRenderersLayout, getActivity().getLayoutInflater().inflate(R.layout.call_item, remoteRenderersLayout,
@ -2016,7 +2085,9 @@ public class CallController extends BaseController {
if (hasExternalSignalingServer) { if (hasExternalSignalingServer) {
gotNick(session, webSocketClient.getDisplayNameForSession(session), false, type); gotNick(session, webSocketClient.getDisplayNameForSession(session), false, type);
} else { } else {
gotNick(session, getPeerConnectionWrapperForSessionIdAndType(session, type, false).getNick(), false, type); gotNick(session,
getPeerConnectionWrapperForSessionIdAndType(session, type, false).getNick(), false,
type);
} }
if ("video".equals(type)) { if ("video".equals(type)) {
@ -2200,7 +2271,6 @@ public class CallController extends BaseController {
} }
} }
if (conversationView != null) { if (conversationView != null) {
if (conversationView.getVisibility() != View.INVISIBLE) { if (conversationView.getVisibility() != View.INVISIBLE) {
conversationView.setVisibility(View.INVISIBLE); conversationView.setVisibility(View.INVISIBLE);
@ -2240,20 +2310,24 @@ public class CallController extends BaseController {
private void playCallingSound() { private void playCallingSound() {
stopCallingSound(); stopCallingSound();
Uri ringtoneUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/raw/librem_by_feandesign_call"); Uri ringtoneUri = Uri.parse("android.resource://"
+ getApplicationContext().getPackageName()
+ "/raw/librem_by_feandesign_call");
if (getActivity() != null) { if (getActivity() != null) {
mediaPlayer = new MediaPlayer(); mediaPlayer = new MediaPlayer();
try { try {
mediaPlayer.setDataSource(Objects.requireNonNull(getActivity()), ringtoneUri); mediaPlayer.setDataSource(Objects.requireNonNull(getActivity()), ringtoneUri);
mediaPlayer.setLooping(true); mediaPlayer.setLooping(true);
AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(AudioAttributes AudioAttributes audioAttributes =
.CONTENT_TYPE_SONIFICATION).setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION).build(); new AudioAttributes.Builder().setContentType(AudioAttributes
.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.build();
mediaPlayer.setAudioAttributes(audioAttributes); mediaPlayer.setAudioAttributes(audioAttributes);
mediaPlayer.setOnPreparedListener(mp -> mediaPlayer.start()); mediaPlayer.setOnPreparedListener(mp -> mediaPlayer.start());
mediaPlayer.prepareAsync(); mediaPlayer.prepareAsync();
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, "Failed to play sound"); Log.e(TAG, "Failed to play sound");
} }
@ -2271,6 +2345,37 @@ public class CallController extends BaseController {
} }
} }
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(NetworkEvent networkEvent) {
if (networkEvent.getNetworkConnectionEvent()
.equals(NetworkEvent.NetworkConnectionEvent.NETWORK_CONNECTED)) {
if (handler != null) {
handler.removeCallbacksAndMessages(null);
}
/*if (!hasMCU) {
setCallState(CallStatus.RECONNECTING);
hangupNetworkCalls(false);
}*/
} else if (networkEvent.getNetworkConnectionEvent()
.equals(NetworkEvent.NetworkConnectionEvent.NETWORK_DISCONNECTED)) {
if (handler != null) {
handler.removeCallbacksAndMessages(null);
}
/* if (!hasMCU) {
setCallState(CallStatus.OFFLINE);
hangup(false);
}*/
}
}
@Parcel
public enum CallStatus {
CALLING, CALLING_TIMEOUT, ESTABLISHED, IN_CONVERSATION, RECONNECTING, OFFLINE, LEAVING, PUBLISHER_FAILED
}
private class MicrophoneButtonTouchListener implements View.OnTouchListener { private class MicrophoneButtonTouchListener implements View.OnTouchListener {
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@ -2279,7 +2384,8 @@ public class CallController extends BaseController {
v.onTouchEvent(event); v.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP && isPTTActive) { if (event.getAction() == MotionEvent.ACTION_UP && isPTTActive) {
isPTTActive = false; isPTTActive = false;
microphoneControlButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_off_white_24px); microphoneControlButton.getHierarchy()
.setPlaceholderImage(R.drawable.ic_mic_off_white_24px);
pulseAnimation.stop(); pulseAnimation.stop();
toggleMedia(false, false); toggleMedia(false, false);
animateCallControls(false, 5000); animateCallControls(false, 5000);
@ -2295,28 +2401,4 @@ public class CallController extends BaseController {
showCallControls(); showCallControls();
} }
} }
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(NetworkEvent networkEvent) {
if (networkEvent.getNetworkConnectionEvent().equals(NetworkEvent.NetworkConnectionEvent.NETWORK_CONNECTED)) {
if (handler != null) {
handler.removeCallbacksAndMessages(null);
}
/*if (!hasMCU) {
setCallState(CallStatus.RECONNECTING);
hangupNetworkCalls(false);
}*/
} else if (networkEvent.getNetworkConnectionEvent().equals(NetworkEvent.NetworkConnectionEvent.NETWORK_DISCONNECTED)) {
if (handler != null) {
handler.removeCallbacksAndMessages(null);
}
/* if (!hasMCU) {
setCallState(CallStatus.OFFLINE);
hangup(false);
}*/
}
}
} }

View File

@ -61,17 +61,17 @@ import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.postprocessors.BlurPostProcessor; import com.facebook.imagepipeline.postprocessors.BlurPostProcessor;
import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequest;
import com.nextcloud.talk.models.RingtoneSettings;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.models.json.conversations.RoomsOverall;
import com.nextcloud.talk.models.json.participants.Participant;
import com.nextcloud.talk.models.json.participants.ParticipantsOverall;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.controllers.base.BaseController; import com.nextcloud.talk.controllers.base.BaseController;
import com.nextcloud.talk.events.ConfigurationChangeEvent; import com.nextcloud.talk.events.ConfigurationChangeEvent;
import com.nextcloud.talk.models.RingtoneSettings;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.models.json.conversations.RoomsOverall;
import com.nextcloud.talk.models.json.participants.Participant;
import com.nextcloud.talk.models.json.participants.ParticipantsOverall;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.DisplayUtils; import com.nextcloud.talk.utils.DisplayUtils;
import com.nextcloud.talk.utils.DoNotDisturbUtils; import com.nextcloud.talk.utils.DoNotDisturbUtils;
@ -145,14 +145,18 @@ public class CallNotificationController extends BaseController {
public CallNotificationController(Bundle args) { public CallNotificationController(Bundle args) {
super(); super();
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
this.roomId = args.getString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), ""); this.roomId = args.getString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), "");
this.currentConversation = Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_ROOM())); this.currentConversation =
Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_ROOM()));
this.userBeingCalled = args.getParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY()); this.userBeingCalled = args.getParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY());
this.originalBundle = args; this.originalBundle = args;
credentials = ApiUtils.getCredentials(userBeingCalled.getUsername(), userBeingCalled.getToken()); credentials =
ApiUtils.getCredentials(userBeingCalled.getUsername(), userBeingCalled.getToken());
} }
@Override @Override
@ -199,7 +203,8 @@ public class CallNotificationController extends BaseController {
} }
private void proceedToCall() { private void proceedToCall() {
originalBundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), currentConversation.getToken()); originalBundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(),
currentConversation.getToken());
getRouter().replaceTopController(RouterTransaction.with(new CallController(originalBundle)) getRouter().replaceTopController(RouterTransaction.with(new CallController(originalBundle))
.popChangeHandler(new HorizontalChangeHandler()) .popChangeHandler(new HorizontalChangeHandler())
@ -253,7 +258,6 @@ public class CallNotificationController extends BaseController {
} }
} }
}); });
} }
private void handleFromNotification() { private void handleFromNotification() {
@ -276,7 +280,6 @@ public class CallNotificationController extends BaseController {
break; break;
} }
} }
} }
@Override @Override
@ -334,7 +337,8 @@ public class CallNotificationController extends BaseController {
"/raw/librem_by_feandesign_call"); "/raw/librem_by_feandesign_call");
} else { } else {
try { try {
RingtoneSettings ringtoneSettings = LoganSquare.parse(callRingtonePreferenceString, RingtoneSettings.class); RingtoneSettings ringtoneSettings =
LoganSquare.parse(callRingtonePreferenceString, RingtoneSettings.class);
ringtoneUri = ringtoneSettings.getRingtoneUri(); ringtoneUri = ringtoneSettings.getRingtoneUri();
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, "Failed to parse ringtone settings"); Log.e(TAG, "Failed to parse ringtone settings");
@ -349,8 +353,11 @@ public class CallNotificationController extends BaseController {
mediaPlayer.setDataSource(getActivity(), ringtoneUri); mediaPlayer.setDataSource(getActivity(), ringtoneUri);
mediaPlayer.setLooping(true); mediaPlayer.setLooping(true);
AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(AudioAttributes AudioAttributes audioAttributes =
.CONTENT_TYPE_SONIFICATION).setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build(); new AudioAttributes.Builder().setContentType(AudioAttributes
.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
mediaPlayer.setAudioAttributes(audioAttributes); mediaPlayer.setAudioAttributes(audioAttributes);
mediaPlayer.setOnPreparedListener(mp -> mediaPlayer.start()); mediaPlayer.setOnPreparedListener(mp -> mediaPlayer.start());
@ -366,8 +373,8 @@ public class CallNotificationController extends BaseController {
vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE); vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null) { if (vibrator != null) {
long[] vibratePattern = new long[]{0, 400, 800, 600, 800, 800, 800, 1000}; long[] vibratePattern = new long[] { 0, 400, 800, 600, 800, 800, 800, 1000 };
int[] amplitudes = new int[]{0, 255, 0, 255, 0, 255, 0, 255}; int[] amplitudes = new int[] { 0, 255, 0, 255, 0, 255, 0, 255 };
VibrationEffect vibrationEffect; VibrationEffect vibrationEffect;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@ -391,10 +398,10 @@ public class CallNotificationController extends BaseController {
} }
} }
@Subscribe(threadMode = ThreadMode.MAIN) @Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(ConfigurationChangeEvent configurationChangeEvent) { public void onMessageEvent(ConfigurationChangeEvent configurationChangeEvent) {
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) avatarImageView.getLayoutParams(); ConstraintLayout.LayoutParams layoutParams =
(ConstraintLayout.LayoutParams) avatarImageView.getLayoutParams();
int dimen = (int) getResources().getDimension(R.dimen.avatar_size_very_big); int dimen = (int) getResources().getDimension(R.dimen.avatar_size_very_big);
layoutParams.width = dimen; layoutParams.width = dimen;
@ -408,11 +415,13 @@ public class CallNotificationController extends BaseController {
avatarImageView.setVisibility(View.VISIBLE); avatarImageView.setVisibility(View.VISIBLE);
ImageRequest imageRequest = ImageRequest imageRequest =
DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(userBeingCalled.getBaseUrl(), DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(userBeingCalled.getBaseUrl(),
currentConversation.getName(), R.dimen.avatar_size_very_big), null); currentConversation.getName(), R.dimen.avatar_size_very_big), null);
ImagePipeline imagePipeline = Fresco.getImagePipeline(); ImagePipeline imagePipeline = Fresco.getImagePipeline();
DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, null); DataSource<CloseableReference<CloseableImage>> dataSource =
imagePipeline.fetchDecodedImage(imageRequest, null);
dataSource.subscribe(new BaseBitmapDataSubscriber() { dataSource.subscribe(new BaseBitmapDataSubscriber() {
@Override @Override
@ -426,7 +435,8 @@ public class CallNotificationController extends BaseController {
.incoming_gradient)); .incoming_gradient));
} }
if ((AvatarStatusCodeHolder.getInstance().getStatusCode() == 200 || AvatarStatusCodeHolder.getInstance().getStatusCode() == 0) && if ((AvatarStatusCodeHolder.getInstance().getStatusCode() == 200
|| AvatarStatusCodeHolder.getInstance().getStatusCode() == 0) &&
userBeingCalled.hasSpreedFeatureCapability("no-ping")) { userBeingCalled.hasSpreedFeatureCapability("no-ping")) {
if (getActivity() != null) { if (getActivity() != null) {
Bitmap backgroundBitmap = bitmap.copy(bitmap.getConfig(), true); Bitmap backgroundBitmap = bitmap.copy(bitmap.getConfig(), true);
@ -454,10 +464,14 @@ public class CallNotificationController extends BaseController {
break; break;
case ROOM_GROUP_CALL: case ROOM_GROUP_CALL:
avatarImageView.getHierarchy().setImage(DisplayUtils.getRoundedDrawable(context.getDrawable(R.drawable.ic_people_group_white_24px)) avatarImageView.getHierarchy()
.setImage(DisplayUtils.getRoundedDrawable(
context.getDrawable(R.drawable.ic_people_group_white_24px))
, 100, true); , 100, true);
case ROOM_PUBLIC_CALL: case ROOM_PUBLIC_CALL:
avatarImageView.getHierarchy().setImage(DisplayUtils.getRoundedDrawable(context.getDrawable(R.drawable.ic_people_group_white_24px)) avatarImageView.getHierarchy()
.setImage(DisplayUtils.getRoundedDrawable(
context.getDrawable(R.drawable.ic_people_group_white_24px))
, 100, true); , 100, true);
break; break;
default: default:

View File

@ -56,14 +56,6 @@ import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.VerticalChangeHandler; import com.bluelinelabs.conductor.changehandler.VerticalChangeHandler;
import com.bluelinelabs.logansquare.LoganSquare; import com.bluelinelabs.logansquare.LoganSquare;
import com.kennyc.bottomsheet.BottomSheet; import com.kennyc.bottomsheet.BottomSheet;
import com.nextcloud.talk.models.RetrofitBucket;
import com.nextcloud.talk.models.json.autocomplete.AutocompleteOverall;
import com.nextcloud.talk.models.json.autocomplete.AutocompleteUser;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.models.json.conversations.RoomOverall;
import com.nextcloud.talk.models.json.participants.Participant;
import com.nextcloud.talk.models.json.sharees.Sharee;
import com.nextcloud.talk.models.json.sharees.ShareesOverall;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.activities.MagicCallActivity; import com.nextcloud.talk.activities.MagicCallActivity;
import com.nextcloud.talk.adapters.items.GenericTextHeaderItem; import com.nextcloud.talk.adapters.items.GenericTextHeaderItem;
@ -76,7 +68,15 @@ import com.nextcloud.talk.controllers.bottomsheet.EntryMenuController;
import com.nextcloud.talk.controllers.bottomsheet.OperationsMenuController; import com.nextcloud.talk.controllers.bottomsheet.OperationsMenuController;
import com.nextcloud.talk.events.BottomSheetLockEvent; import com.nextcloud.talk.events.BottomSheetLockEvent;
import com.nextcloud.talk.jobs.AddParticipantsToConversation; import com.nextcloud.talk.jobs.AddParticipantsToConversation;
import com.nextcloud.talk.models.RetrofitBucket;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.autocomplete.AutocompleteOverall;
import com.nextcloud.talk.models.json.autocomplete.AutocompleteUser;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.models.json.conversations.RoomOverall;
import com.nextcloud.talk.models.json.participants.Participant;
import com.nextcloud.talk.models.json.sharees.Sharee;
import com.nextcloud.talk.models.json.sharees.ShareesOverall;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.ConductorRemapping; import com.nextcloud.talk.utils.ConductorRemapping;
import com.nextcloud.talk.utils.KeyboardUtils; import com.nextcloud.talk.utils.KeyboardUtils;
@ -110,7 +110,8 @@ import org.parceler.Parcels;
@AutoInjector(NextcloudTalkApplication.class) @AutoInjector(NextcloudTalkApplication.class)
public class ContactsController extends BaseController implements SearchView.OnQueryTextListener, public class ContactsController extends BaseController implements SearchView.OnQueryTextListener,
FlexibleAdapter.OnItemClickListener, FastScroller.OnScrollStateChangeListener, FlexibleAdapter.EndlessScrollListener { FlexibleAdapter.OnItemClickListener, FastScroller.OnScrollStateChangeListener,
FlexibleAdapter.EndlessScrollListener {
public static final String TAG = "ContactsController"; public static final String TAG = "ContactsController";
@ -197,7 +198,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
existingParticipants = new ArrayList<>(); existingParticipants = new ArrayList<>();
if (args.containsKey(BundleKeys.INSTANCE.getKEY_EXISTING_PARTICIPANTS())) { if (args.containsKey(BundleKeys.INSTANCE.getKEY_EXISTING_PARTICIPANTS())) {
existingParticipants = args.getStringArrayList(BundleKeys.INSTANCE.getKEY_EXISTING_PARTICIPANTS()); existingParticipants =
args.getStringArrayList(BundleKeys.INSTANCE.getKEY_EXISTING_PARTICIPANTS());
} }
} }
@ -229,13 +231,14 @@ public class ContactsController extends BaseController implements SearchView.OnQ
joinConversationViaLinkLayout.setVisibility(View.GONE); joinConversationViaLinkLayout.setVisibility(View.GONE);
conversationPrivacyToogleLayout.setVisibility(View.GONE); conversationPrivacyToogleLayout.setVisibility(View.GONE);
} }
} }
@Override @Override
protected void onViewBound(@NonNull View view) { protected void onViewBound(@NonNull View view) {
super.onViewBound(view); super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
currentUser = userUtils.getCurrentUser(); currentUser = userUtils.getCurrentUser();
@ -283,7 +286,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
userId = selectedUserIds.iterator().next(); userId = selectedUserIds.iterator().next();
} }
RetrofitBucket retrofitBucket = ApiUtils.getRetrofitBucketForCreateRoom(currentUser.getBaseUrl(), roomType, RetrofitBucket retrofitBucket =
ApiUtils.getRetrofitBucketForCreateRoom(currentUser.getBaseUrl(), roomType,
userId, null); userId, null);
ncApi.createRoom(credentials, ncApi.createRoom(credentials,
retrofitBucket.getUrl(), retrofitBucket.getQueryMap()) retrofitBucket.getUrl(), retrofitBucket.getQueryMap())
@ -301,8 +305,10 @@ public class ContactsController extends BaseController implements SearchView.OnQ
Intent conversationIntent = new Intent(getActivity(), MagicCallActivity.class); Intent conversationIntent = new Intent(getActivity(), MagicCallActivity.class);
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), currentUser); bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), currentUser);
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), roomOverall.getOcs().getData().getToken()); bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(),
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), roomOverall.getOcs().getData().getRoomId()); roomOverall.getOcs().getData().getToken());
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(),
roomOverall.getOcs().getData().getRoomId());
if (currentUser.hasSpreedFeatureCapability("chat-v2")) { if (currentUser.hasSpreedFeatureCapability("chat-v2")) {
ncApi.getRoom(credentials, ncApi.getRoom(credentials,
@ -323,7 +329,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(), bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(),
Parcels.wrap(roomOverall.getOcs().getData())); Parcels.wrap(roomOverall.getOcs().getData()));
ConductorRemapping.INSTANCE.remapChatController(getRouter(), currentUser.getId(), ConductorRemapping.INSTANCE.remapChatController(getRouter(),
currentUser.getId(),
roomOverall.getOcs().getData().getToken(), bundle, true); roomOverall.getOcs().getData().getToken(), bundle, true);
} }
@ -373,8 +380,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
ArrayList<String> userIdsArray = new ArrayList<>(selectedUserIds); ArrayList<String> userIdsArray = new ArrayList<>(selectedUserIds);
ArrayList<String> groupIdsArray = new ArrayList<>(selectedGroupIds); ArrayList<String> groupIdsArray = new ArrayList<>(selectedGroupIds);
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_CONVERSATION_TYPE(),
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_CONVERSATION_TYPE(), Parcels.wrap(roomType)); Parcels.wrap(roomType));
bundle.putStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_PARTICIPANTS(), userIdsArray); bundle.putStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_PARTICIPANTS(), userIdsArray);
bundle.putStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_GROUP(), groupIdsArray); bundle.putStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_GROUP(), groupIdsArray);
bundle.putInt(BundleKeys.INSTANCE.getKEY_OPERATION_CODE(), 11); bundle.putInt(BundleKeys.INSTANCE.getKEY_OPERATION_CODE(), 11);
@ -391,7 +398,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
data.putStringArray(BundleKeys.INSTANCE.getKEY_SELECTED_GROUPS(), groupIdsArray); data.putStringArray(BundleKeys.INSTANCE.getKEY_SELECTED_GROUPS(), groupIdsArray);
OneTimeWorkRequest addParticipantsToConversationWorker = OneTimeWorkRequest addParticipantsToConversationWorker =
new OneTimeWorkRequest.Builder(AddParticipantsToConversation.class).setInputData(data.build()).build(); new OneTimeWorkRequest.Builder(AddParticipantsToConversation.class).setInputData(
data.build()).build();
WorkManager.getInstance().enqueue(addParticipantsToConversationWorker); WorkManager.getInstance().enqueue(addParticipantsToConversationWorker);
getRouter().popCurrentController(); getRouter().popCurrentController();
@ -400,19 +408,22 @@ public class ContactsController extends BaseController implements SearchView.OnQ
private void initSearchView() { private void initSearchView() {
if (getActivity() != null) { if (getActivity() != null) {
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE); SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) { if (searchItem != null) {
searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setMaxWidth(Integer.MAX_VALUE); searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER); searchView.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER);
int imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_FULLSCREEN; int imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_FULLSCREEN;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && appPreferences.getIsKeyboardIncognito()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& appPreferences.getIsKeyboardIncognito()) {
imeOptions |= EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING; imeOptions |= EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING;
} }
searchView.setImeOptions(imeOptions); searchView.setImeOptions(imeOptions);
searchView.setQueryHint(getResources().getString(R.string.nc_search)); searchView.setQueryHint(getResources().getString(R.string.nc_search));
if (searchManager != null) { if (searchManager != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName())); searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
} }
searchView.setOnQueryTextListener(this); searchView.setOnQueryTextListener(this);
} }
@ -466,7 +477,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
boolean serverIs14OrUp = false; boolean serverIs14OrUp = false;
if (currentUser.hasSpreedFeatureCapability("last-room-activity")) { if (currentUser.hasSpreedFeatureCapability("last-room-activity")) {
// a hack to see if we're on 14 or not // a hack to see if we're on 14 or not
retrofitBucket = ApiUtils.getRetrofitBucketForContactsSearchFor14(currentUser.getBaseUrl(), query); retrofitBucket =
ApiUtils.getRetrofitBucketForContactsSearchFor14(currentUser.getBaseUrl(), query);
serverIs14OrUp = true; serverIs14OrUp = true;
} else { } else {
retrofitBucket = ApiUtils.getRetrofitBucketForContactsSearch(currentUser.getBaseUrl(), query); retrofitBucket = ApiUtils.getRetrofitBucketForContactsSearch(currentUser.getBaseUrl(), query);
@ -496,7 +508,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
// mails // mails
//shareTypesList.add("4"); //shareTypesList.add("4");
modifiedQueryMap.put("shareTypes[]", shareTypesList); modifiedQueryMap.put("shareTypes[]", shareTypesList);
} }
@ -522,7 +533,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
try { try {
if (!finalServerIs14OrUp) { if (!finalServerIs14OrUp) {
ShareesOverall shareesOverall = LoganSquare.parse(responseBody.string(), ShareesOverall.class); ShareesOverall shareesOverall =
LoganSquare.parse(responseBody.string(), ShareesOverall.class);
if (shareesOverall.getOcs().getData().getUsers() != null) { if (shareesOverall.getOcs().getData().getUsers() != null) {
shareeHashSet.addAll(shareesOverall.getOcs().getData().getUsers()); shareeHashSet.addAll(shareesOverall.getOcs().getData().getUsers());
@ -535,7 +547,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
} }
for (Sharee sharee : shareeHashSet) { for (Sharee sharee : shareeHashSet) {
if (!sharee.getValue().getShareWith().equals(currentUser.getUserId()) && !existingParticipants.contains(sharee.getValue().getShareWith())) { if (!sharee.getValue().getShareWith().equals(currentUser.getUserId())
&& !existingParticipants.contains(sharee.getValue().getShareWith())) {
participant = new Participant(); participant = new Participant();
participant.setDisplayName(sharee.getLabel()); participant.setDisplayName(sharee.getLabel());
String headerTitle; String headerTitle;
@ -556,17 +569,16 @@ public class ContactsController extends BaseController implements SearchView.OnQ
if (!contactItems.contains(newContactItem)) { if (!contactItems.contains(newContactItem)) {
newUserItemList.add(newContactItem); newUserItemList.add(newContactItem);
} }
} }
} }
} else { } else {
AutocompleteOverall autocompleteOverall = LoganSquare.parse(responseBody.string(), AutocompleteOverall.class); AutocompleteOverall autocompleteOverall =
LoganSquare.parse(responseBody.string(), AutocompleteOverall.class);
autocompleteUsersHashSet.addAll(autocompleteOverall.getOcs().getData()); autocompleteUsersHashSet.addAll(autocompleteOverall.getOcs().getData());
for (AutocompleteUser autocompleteUser : autocompleteUsersHashSet) { for (AutocompleteUser autocompleteUser : autocompleteUsersHashSet) {
if (!autocompleteUser.getId().equals(currentUser.getUserId()) && !existingParticipants.contains(autocompleteUser.getId())) { if (!autocompleteUser.getId().equals(currentUser.getUserId())
&& !existingParticipants.contains(autocompleteUser.getId())) {
participant = new Participant(); participant = new Participant();
participant.setUserId(autocompleteUser.getId()); participant.setUserId(autocompleteUser.getId());
participant.setDisplayName(autocompleteUser.getLabel()); participant.setDisplayName(autocompleteUser.getLabel());
@ -586,14 +598,12 @@ public class ContactsController extends BaseController implements SearchView.OnQ
userHeaderItems.put(headerTitle, genericTextHeaderItem); userHeaderItems.put(headerTitle, genericTextHeaderItem);
} }
UserItem newContactItem = new UserItem(participant, currentUser, UserItem newContactItem = new UserItem(participant, currentUser,
userHeaderItems.get(headerTitle), getActivity()); userHeaderItems.get(headerTitle), getActivity());
if (!contactItems.contains(newContactItem)) { if (!contactItems.contains(newContactItem)) {
newUserItemList.add(newContactItem); newUserItemList.add(newContactItem);
} }
} }
} }
} }
@ -602,10 +612,12 @@ public class ContactsController extends BaseController implements SearchView.OnQ
} }
if (TextUtils.isEmpty((CharSequence) modifiedQueryMap.get("search"))) { if (TextUtils.isEmpty((CharSequence) modifiedQueryMap.get("search"))) {
canFetchFurther = !shareeHashSet.isEmpty() || (finalServerIs14OrUp && autocompleteUsersHashSet.size() == 100); canFetchFurther = !shareeHashSet.isEmpty() || (finalServerIs14OrUp
&& autocompleteUsersHashSet.size() == 100);
currentPage = (int) modifiedQueryMap.get("page"); currentPage = (int) modifiedQueryMap.get("page");
} else { } else {
canFetchSearchFurther = !shareeHashSet.isEmpty() || (finalServerIs14OrUp && autocompleteUsersHashSet.size() == 100); canFetchSearchFurther = !shareeHashSet.isEmpty() || (finalServerIs14OrUp
&& autocompleteUsersHashSet.size() == 100);
currentSearchPage = (int) modifiedQueryMap.get("page"); currentSearchPage = (int) modifiedQueryMap.get("page");
} }
@ -616,7 +628,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
String firstName; String firstName;
String secondName; String secondName;
if (o1 instanceof UserItem) { if (o1 instanceof UserItem) {
firstName = ((UserItem) o1).getModel().getDisplayName(); firstName = ((UserItem) o1).getModel().getDisplayName();
} else { } else {
@ -630,7 +641,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
} }
if (o1 instanceof UserItem && o2 instanceof UserItem) { if (o1 instanceof UserItem && o2 instanceof UserItem) {
if ("groups".equals(((UserItem) o1).getModel().getSource()) && "groups".equals(((UserItem) o2).getModel().getSource())) { if ("groups".equals(((UserItem) o1).getModel().getSource()) && "groups".equals(
((UserItem) o2).getModel().getSource())) {
return firstName.compareToIgnoreCase(secondName); return firstName.compareToIgnoreCase(secondName);
} else if ("groups".equals(((UserItem) o1).getModel().getSource())) { } else if ("groups".equals(((UserItem) o1).getModel().getSource())) {
return -1; return -1;
@ -646,7 +658,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
String firstName; String firstName;
String secondName; String secondName;
if (o1 instanceof UserItem) { if (o1 instanceof UserItem) {
firstName = ((UserItem) o1).getModel().getDisplayName(); firstName = ((UserItem) o1).getModel().getDisplayName();
} else { } else {
@ -660,7 +671,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
} }
if (o1 instanceof UserItem && o2 instanceof UserItem) { if (o1 instanceof UserItem && o2 instanceof UserItem) {
if ("groups".equals(((UserItem) o1).getModel().getSource()) && "groups".equals(((UserItem) o2).getModel().getSource())) { if ("groups".equals(((UserItem) o1).getModel().getSource()) && "groups".equals(
((UserItem) o2).getModel().getSource())) {
return firstName.compareToIgnoreCase(secondName); return firstName.compareToIgnoreCase(secondName);
} else if ("groups".equals(((UserItem) o1).getModel().getSource())) { } else if ("groups".equals(((UserItem) o1).getModel().getSource())) {
return -1; return -1;
@ -672,7 +684,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
return firstName.compareToIgnoreCase(secondName); return firstName.compareToIgnoreCase(secondName);
}); });
if (newUserItemList.size() > 0) { if (newUserItemList.size() > 0) {
adapter.updateDataSet(newUserItemList); adapter.updateDataSet(newUserItemList);
} else { } else {
@ -683,7 +694,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setRefreshing(false);
} }
} }
} }
@Override @Override
@ -691,7 +701,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
if (swipeRefreshLayout != null) { if (swipeRefreshLayout != null) {
swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setRefreshing(false);
} }
} }
@Override @Override
@ -704,7 +713,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
disengageProgressBar(); disengageProgressBar();
} }
}); });
} }
private void prepareViews() { private void prepareViews() {
@ -806,7 +814,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
swipeRefreshLayout.setEnabled(!scrolling); swipeRefreshLayout.setEnabled(!scrolling);
} }
private void prepareAndShowBottomSheetWithBundle(Bundle bundle, boolean showEntrySheet) { private void prepareAndShowBottomSheetWithBundle(Bundle bundle, boolean showEntrySheet) {
if (view == null) { if (view == null) {
view = getActivity().getLayoutInflater().inflate(R.layout.bottom_sheet, null, false); view = getActivity().getLayoutInflater().inflate(R.layout.bottom_sheet, null, false);
@ -837,7 +844,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
} }
}); });
bottomSheet.setOnDismissListener(dialog -> getActionBar().setDisplayHomeAsUpEnabled(getRouter().getBackstackSize() > 1)); bottomSheet.setOnDismissListener(
dialog -> getActionBar().setDisplayHomeAsUpEnabled(getRouter().getBackstackSize() > 1));
bottomSheet.show(); bottomSheet.show();
} }
@ -854,7 +862,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
new Handler().postDelayed(() -> { new Handler().postDelayed(() -> {
bottomSheet.setOnCancelListener(null); bottomSheet.setOnCancelListener(null);
bottomSheet.cancel(); bottomSheet.cancel();
}, bottomSheetLockEvent.getDelay()); }, bottomSheetLockEvent.getDelay());
} }
} }
@ -872,7 +879,9 @@ public class ContactsController extends BaseController implements SearchView.OnQ
roomType = "2"; roomType = "2";
} }
RetrofitBucket retrofitBucket = ApiUtils.getRetrofitBucketForCreateRoom(currentUser.getBaseUrl(), roomType, userItem.getModel().getUserId(), null); RetrofitBucket retrofitBucket =
ApiUtils.getRetrofitBucketForCreateRoom(currentUser.getBaseUrl(), roomType,
userItem.getModel().getUserId(), null);
ncApi.createRoom(credentials, ncApi.createRoom(credentials,
retrofitBucket.getUrl(), retrofitBucket.getQueryMap()) retrofitBucket.getUrl(), retrofitBucket.getQueryMap())
@ -891,15 +900,18 @@ public class ContactsController extends BaseController implements SearchView.OnQ
Intent conversationIntent = new Intent(getActivity(), MagicCallActivity.class); Intent conversationIntent = new Intent(getActivity(), MagicCallActivity.class);
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), currentUser); bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), currentUser);
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), roomOverall.getOcs().getData().getToken()); bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(),
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), roomOverall.getOcs().getData().getRoomId()); roomOverall.getOcs().getData().getToken());
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(),
roomOverall.getOcs().getData().getRoomId());
conversationIntent.putExtras(bundle); conversationIntent.putExtras(bundle);
if (currentUser.hasSpreedFeatureCapability("chat-v2")) { if (currentUser.hasSpreedFeatureCapability("chat-v2")) {
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(), bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(),
Parcels.wrap(roomOverall.getOcs().getData())); Parcels.wrap(roomOverall.getOcs().getData()));
ConductorRemapping.INSTANCE.remapChatController(getRouter(), currentUser.getId(), ConductorRemapping.INSTANCE.remapChatController(getRouter(),
currentUser.getId(),
roomOverall.getOcs().getData().getToken(), bundle, true); roomOverall.getOcs().getData().getToken(), bundle, true);
} else { } else {
startActivity(conversationIntent); startActivity(conversationIntent);
@ -945,13 +957,14 @@ public class ContactsController extends BaseController implements SearchView.OnQ
Participant internalParticipant; Participant internalParticipant;
for (int i = 0; i < currentItems.size(); i++) { for (int i = 0; i < currentItems.size(); i++) {
internalParticipant = currentItems.get(i).getModel(); internalParticipant = currentItems.get(i).getModel();
if (internalParticipant.getUserId().equals(participant.getUserId()) && if (internalParticipant.getUserId().equals(participant.getUserId())
"groups".equals(internalParticipant.getSource()) && internalParticipant.isSelected()) { &&
"groups".equals(internalParticipant.getSource())
&& internalParticipant.isSelected()) {
internalParticipant.setSelected(false); internalParticipant.setSelected(false);
selectedGroupIds.remove(internalParticipant.getUserId()); selectedGroupIds.remove(internalParticipant.getUserId());
} }
} }
} }
adapter.notifyDataSetChanged(); adapter.notifyDataSetChanged();
@ -988,7 +1001,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
for (int i = 0; i < currentItems.size(); i++) { for (int i = 0; i < currentItems.size(); i++) {
if (currentItems.get(i) instanceof UserItem) { if (currentItems.get(i) instanceof UserItem) {
internalParticipant = ((UserItem) currentItems.get(i)).getModel(); internalParticipant = ((UserItem) currentItems.get(i)).getModel();
if ("groups".equals(internalParticipant.getSource()) && internalParticipant.isSelected()) { if ("groups".equals(internalParticipant.getSource())
&& internalParticipant.isSelected()) {
internalParticipant.setSelected(false); internalParticipant.setSelected(false);
selectedGroupIds.remove(internalParticipant.getUserId()); selectedGroupIds.remove(internalParticipant.getUserId());
} }

View File

@ -20,7 +20,6 @@
package com.nextcloud.talk.controllers package com.nextcloud.talk.controllers
import android.content.res.Configuration
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable import android.graphics.drawable.LayerDrawable
import android.os.Bundle import android.os.Bundle
@ -48,12 +47,6 @@ import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler
import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.view.SimpleDraweeView import com.facebook.drawee.view.SimpleDraweeView
import com.nextcloud.talk.models.json.conversations.Conversation
import com.nextcloud.talk.models.json.conversations.RoomOverall
import com.nextcloud.talk.models.json.converters.EnumNotificationLevelConverter
import com.nextcloud.talk.models.json.generic.GenericOverall
import com.nextcloud.talk.models.json.participants.Participant
import com.nextcloud.talk.models.json.participants.ParticipantsOverall
import com.nextcloud.talk.R import com.nextcloud.talk.R
import com.nextcloud.talk.adapters.items.UserItem import com.nextcloud.talk.adapters.items.UserItem
import com.nextcloud.talk.api.NcApi import com.nextcloud.talk.api.NcApi
@ -65,6 +58,12 @@ import com.nextcloud.talk.events.EventStatus
import com.nextcloud.talk.jobs.DeleteConversationWorker import com.nextcloud.talk.jobs.DeleteConversationWorker
import com.nextcloud.talk.jobs.LeaveConversationWorker import com.nextcloud.talk.jobs.LeaveConversationWorker
import com.nextcloud.talk.models.database.UserEntity import com.nextcloud.talk.models.database.UserEntity
import com.nextcloud.talk.models.json.conversations.Conversation
import com.nextcloud.talk.models.json.conversations.RoomOverall
import com.nextcloud.talk.models.json.converters.EnumNotificationLevelConverter
import com.nextcloud.talk.models.json.generic.GenericOverall
import com.nextcloud.talk.models.json.participants.Participant
import com.nextcloud.talk.models.json.participants.ParticipantsOverall
import com.nextcloud.talk.utils.ApiUtils import com.nextcloud.talk.utils.ApiUtils
import com.nextcloud.talk.utils.DateUtils import com.nextcloud.talk.utils.DateUtils
import com.nextcloud.talk.utils.DisplayUtils import com.nextcloud.talk.utils.DisplayUtils
@ -92,7 +91,8 @@ import java.util.Calendar
import javax.inject.Inject import javax.inject.Inject
@AutoInjector(NextcloudTalkApplication::class) @AutoInjector(NextcloudTalkApplication::class)
class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapter.OnItemClickListener { class ConversationInfoController(args: Bundle) : BaseController(),
FlexibleAdapter.OnItemClickListener {
@BindView(R.id.notification_settings) @BindView(R.id.notification_settings)
lateinit var notificationsPreferenceScreen: MaterialPreferenceScreen lateinit var notificationsPreferenceScreen: MaterialPreferenceScreen
@BindView(R.id.progressBar) @BindView(R.id.progressBar)
@ -173,7 +173,10 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
} }
} }
override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View { override fun inflateView(
inflater: LayoutInflater,
container: ViewGroup
): View {
return inflater.inflate(R.layout.controller_conversation_info, container, false) return inflater.inflate(R.layout.controller_conversation_info, container, false)
} }
@ -209,10 +212,14 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
private fun setupWebinaryView() { private fun setupWebinaryView() {
if (conversationUser!!.hasSpreedFeatureCapability("webinary-lobby") && (conversation!!.type if (conversationUser!!.hasSpreedFeatureCapability("webinary-lobby") && (conversation!!.type
== Conversation.ConversationType.ROOM_GROUP_CALL || conversation!!.type == == Conversation.ConversationType.ROOM_GROUP_CALL || conversation!!.type ==
Conversation.ConversationType.ROOM_PUBLIC_CALL) && conversation!!.canModerate(conversationUser)) { Conversation.ConversationType.ROOM_PUBLIC_CALL) && conversation!!.canModerate(
conversationUser
)
) {
conversationInfoWebinar.visibility = View.VISIBLE conversationInfoWebinar.visibility = View.VISIBLE
val isLobbyOpenToModeratorsOnly = conversation!!.lobbyState == Conversation.LobbyState.LOBBY_STATE_MODERATORS_ONLY val isLobbyOpenToModeratorsOnly =
conversation!!.lobbyState == Conversation.LobbyState.LOBBY_STATE_MODERATORS_ONLY
(conversationInfoLobby.findViewById<View>(R.id.mp_checkable) as SwitchCompat) (conversationInfoLobby.findViewById<View>(R.id.mp_checkable) as SwitchCompat)
.isChecked = isLobbyOpenToModeratorsOnly .isChecked = isLobbyOpenToModeratorsOnly
@ -234,7 +241,9 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
} }
} }
(conversationInfoLobby.findViewById<View>(R.id.mp_checkable) as SwitchCompat).setOnCheckedChangeListener { _, _ -> (conversationInfoLobby.findViewById<View>(
R.id.mp_checkable
) as SwitchCompat).setOnCheckedChangeListener { _, _ ->
reconfigureLobbyTimerView() reconfigureLobbyTimerView()
submitLobbyChanges() submitLobbyChanges()
} }
@ -244,7 +253,8 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
} }
fun reconfigureLobbyTimerView(dateTime: Calendar? = null) { fun reconfigureLobbyTimerView(dateTime: Calendar? = null) {
val isChecked = (conversationInfoLobby.findViewById<View>(R.id.mp_checkable) as SwitchCompat).isChecked val isChecked =
(conversationInfoLobby.findViewById<View>(R.id.mp_checkable) as SwitchCompat).isChecked
if (dateTime != null && isChecked) { if (dateTime != null && isChecked) {
conversation!!.lobbyTimer = (dateTime.timeInMillis - (dateTime.time.seconds * 1000)) / 1000 conversation!!.lobbyTimer = (dateTime.timeInMillis - (dateTime.time.seconds * 1000)) / 1000
@ -256,7 +266,9 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
.LOBBY_STATE_MODERATORS_ONLY else Conversation.LobbyState.LOBBY_STATE_ALL_PARTICIPANTS .LOBBY_STATE_MODERATORS_ONLY else Conversation.LobbyState.LOBBY_STATE_ALL_PARTICIPANTS
if (conversation!!.lobbyTimer != null && conversation!!.lobbyTimer != java.lang.Long.MIN_VALUE && conversation!!.lobbyTimer != 0L) { if (conversation!!.lobbyTimer != null && conversation!!.lobbyTimer != java.lang.Long.MIN_VALUE && conversation!!.lobbyTimer != 0L) {
startTimeView.setSummary(DateUtils.getLocalDateStringFromTimestampForLobby(conversation!!.lobbyTimer)) startTimeView.setSummary(
DateUtils.getLocalDateStringFromTimestampForLobby(conversation!!.lobbyTimer)
)
} else { } else {
startTimeView.setSummary(R.string.nc_manual) startTimeView.setSummary(R.string.nc_manual)
} }
@ -269,11 +281,18 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
} }
fun submitLobbyChanges() { fun submitLobbyChanges() {
val state = if ((conversationInfoLobby.findViewById<View>(R.id val state = if ((conversationInfoLobby.findViewById<View>(
.mp_checkable) as SwitchCompat).isChecked) 1 else 0 R.id
ncApi.setLobbyForConversation(ApiUtils.getCredentials(conversationUser!!.username, .mp_checkable
conversationUser.token), ApiUtils.getUrlForLobbyForConversation ) as SwitchCompat).isChecked
(conversationUser.baseUrl, conversation!!.token), state, conversation!!.lobbyTimer) ) 1 else 0
ncApi.setLobbyForConversation(
ApiUtils.getCredentials(
conversationUser!!.username,
conversationUser.token
), ApiUtils.getUrlForLobbyForConversation
(conversationUser.baseUrl, conversation!!.token), state, conversation!!.lobbyTimer
)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<GenericOverall> { .subscribe(object : Observer<GenericOverall> {
@ -292,7 +311,10 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
}) })
} }
private fun showLovelyDialog(dialogId: Int, savedInstanceState: Bundle) { private fun showLovelyDialog(
dialogId: Int,
savedInstanceState: Bundle
) {
when (dialogId) { when (dialogId) {
ID_DELETE_CONVERSATION_DIALOG -> showDeleteConversationDialog(savedInstanceState) ID_DELETE_CONVERSATION_DIALOG -> showDeleteConversationDialog(savedInstanceState)
else -> { else -> {
@ -309,9 +331,12 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
if (activity != null) { if (activity != null) {
LovelyStandardDialog(activity, LovelyStandardDialog.ButtonLayout.HORIZONTAL) LovelyStandardDialog(activity, LovelyStandardDialog.ButtonLayout.HORIZONTAL)
.setTopColorRes(R.color.nc_darkRed) .setTopColorRes(R.color.nc_darkRed)
.setIcon(DisplayUtils.getTintedDrawable( .setIcon(
DisplayUtils.getTintedDrawable(
context.resources, context.resources,
R.drawable.ic_delete_black_24dp, R.color.bg_default)) R.drawable.ic_delete_black_24dp, R.color.bg_default
)
)
.setPositiveButtonColor(context.resources.getColor(R.color.nc_darkRed)) .setPositiveButtonColor(context.resources.getColor(R.color.nc_darkRed))
.setTitle(R.string.nc_delete_call) .setTitle(R.string.nc_delete_call)
.setMessage(conversation!!.deleteWarningMessage) .setMessage(conversation!!.deleteWarningMessage)
@ -323,12 +348,18 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
} }
} }
override fun onSaveViewState(view: View, outState: Bundle) { override fun onSaveViewState(
view: View,
outState: Bundle
) {
saveStateHandler!!.saveInstanceState(outState) saveStateHandler!!.saveInstanceState(outState)
super.onSaveViewState(view, outState) super.onSaveViewState(view, outState)
} }
override fun onRestoreViewState(view: View, savedViewState: Bundle) { override fun onRestoreViewState(
view: View,
savedViewState: Bundle
) {
super.onRestoreViewState(view, savedViewState) super.onRestoreViewState(view, savedViewState)
if (LovelySaveStateHandler.wasDialogOnScreen(savedViewState)) { if (LovelySaveStateHandler.wasDialogOnScreen(savedViewState)) {
//Dialog won't be restarted automatically, so we need to call this method. //Dialog won't be restarted automatically, so we need to call this method.
@ -362,9 +393,11 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
bundle.putStringArrayList(BundleKeys.KEY_EXISTING_PARTICIPANTS, existingParticipantsId) bundle.putStringArrayList(BundleKeys.KEY_EXISTING_PARTICIPANTS, existingParticipantsId)
bundle.putString(BundleKeys.KEY_TOKEN, conversation!!.token) bundle.putString(BundleKeys.KEY_TOKEN, conversation!!.token)
router.pushController((RouterTransaction.with(ContactsController(bundle)) router.pushController(
(RouterTransaction.with(ContactsController(bundle))
.pushChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler()))) .popChangeHandler(HorizontalChangeHandler()))
)
} }
} }
@ -381,7 +414,10 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
participant = participants[i] participant = participants[i]
userItem = UserItem(participant, conversationUser, null, activity) userItem = UserItem(participant, conversationUser, null, activity)
userItem.isOnline = !participant.sessionId.equals("0") userItem.isOnline = !participant.sessionId.equals("0")
if (!TextUtils.isEmpty(participant.userId) && participant.userId == conversationUser!!.userId) { if (!TextUtils.isEmpty(
participant.userId
) && participant.userId == conversationUser!!.userId
) {
ownUserItem = userItem ownUserItem = userItem
ownUserItem.model.sessionId = "-1" ownUserItem.model.sessionId = "-1"
ownUserItem.isOnline = true ownUserItem.isOnline = true
@ -406,7 +442,9 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
} }
private fun getListOfParticipants() { private fun getListOfParticipants() {
ncApi.getPeersForCall(credentials, ApiUtils.getUrlForParticipants(conversationUser!!.baseUrl, conversationToken)) ncApi.getPeersForCall(
credentials, ApiUtils.getUrlForParticipants(conversationUser!!.baseUrl, conversationToken)
)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<ParticipantsOverall> { .subscribe(object : Observer<ParticipantsOverall> {
@ -432,9 +470,13 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
@OnClick(R.id.leaveConversationAction) @OnClick(R.id.leaveConversationAction)
internal fun leaveConversation() { internal fun leaveConversation() {
workerData?.let { workerData?.let {
WorkManager.getInstance().enqueue(OneTimeWorkRequest.Builder WorkManager.getInstance()
(LeaveConversationWorker::class .enqueue(
.java).setInputData(it).build() OneTimeWorkRequest.Builder
(
LeaveConversationWorker::class
.java
).setInputData(it).build()
) )
popTwoLastControllers() popTwoLastControllers()
} }
@ -442,8 +484,11 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
private fun deleteConversation() { private fun deleteConversation() {
workerData?.let { workerData?.let {
WorkManager.getInstance().enqueue(OneTimeWorkRequest.Builder WorkManager.getInstance()
(DeleteConversationWorker::class.java).setInputData(it).build()) .enqueue(
OneTimeWorkRequest.Builder
(DeleteConversationWorker::class.java).setInputData(it).build()
)
popTwoLastControllers() popTwoLastControllers()
} }
} }
@ -528,12 +573,16 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
private fun adjustNotificationLevelUI() { private fun adjustNotificationLevelUI() {
if (conversation != null) { if (conversation != null) {
if (conversationUser != null && conversationUser.hasSpreedFeatureCapability("notification-levels")) { if (conversationUser != null && conversationUser.hasSpreedFeatureCapability(
"notification-levels"
)
) {
messageNotificationLevel.isEnabled = true messageNotificationLevel.isEnabled = true
messageNotificationLevel.alpha = 1.0f messageNotificationLevel.alpha = 1.0f
if (conversation!!.notificationLevel != Conversation.NotificationLevel.DEFAULT) { if (conversation!!.notificationLevel != Conversation.NotificationLevel.DEFAULT) {
val stringValue: String = when (EnumNotificationLevelConverter().convertToInt(conversation!!.notificationLevel)) { val stringValue: String =
when (EnumNotificationLevelConverter().convertToInt(conversation!!.notificationLevel)) {
1 -> "always" 1 -> "always"
2 -> "mention" 2 -> "mention"
3 -> "never" 3 -> "never"
@ -568,27 +617,44 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
private fun loadConversationAvatar() { private fun loadConversationAvatar() {
when (conversation!!.type) { when (conversation!!.type) {
Conversation.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL -> if (!TextUtils.isEmpty Conversation.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL -> if (!TextUtils.isEmpty
(conversation!!.name)) { (conversation!!.name)
) {
val draweeController = Fresco.newDraweeControllerBuilder() val draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(conversationAvatarImageView.controller) .setOldController(conversationAvatarImageView.controller)
.setAutoPlayAnimations(true) .setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(conversationUser!!.baseUrl, .setImageRequest(
conversation!!.name, R.dimen.avatar_size_big), null)) DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(
conversationUser!!.baseUrl,
conversation!!.name, R.dimen.avatar_size_big
), null
)
)
.build() .build()
conversationAvatarImageView.controller = draweeController conversationAvatarImageView.controller = draweeController
} }
Conversation.ConversationType.ROOM_GROUP_CALL -> conversationAvatarImageView.hierarchy.setPlaceholderImage(DisplayUtils Conversation.ConversationType.ROOM_GROUP_CALL -> conversationAvatarImageView.hierarchy.setPlaceholderImage(
.getRoundedBitmapDrawableFromVectorDrawableResource(resources, DisplayUtils
R.drawable.ic_people_group_white_24px)) .getRoundedBitmapDrawableFromVectorDrawableResource(
Conversation.ConversationType.ROOM_PUBLIC_CALL -> conversationAvatarImageView.hierarchy.setPlaceholderImage(DisplayUtils resources,
.getRoundedBitmapDrawableFromVectorDrawableResource(resources, R.drawable.ic_people_group_white_24px
R.drawable.ic_link_white_24px)) )
)
Conversation.ConversationType.ROOM_PUBLIC_CALL -> conversationAvatarImageView.hierarchy.setPlaceholderImage(
DisplayUtils
.getRoundedBitmapDrawableFromVectorDrawableResource(
resources,
R.drawable.ic_link_white_24px
)
)
Conversation.ConversationType.ROOM_SYSTEM -> { Conversation.ConversationType.ROOM_SYSTEM -> {
val layers = arrayOfNulls<Drawable>(2) val layers = arrayOfNulls<Drawable>(2)
layers[0] = context.getDrawable(R.drawable.ic_launcher_background) layers[0] = context.getDrawable(R.drawable.ic_launcher_background)
layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground) layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground)
val layerDrawable = LayerDrawable(layers) val layerDrawable = LayerDrawable(layers)
conversationAvatarImageView.hierarchy.setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable)) conversationAvatarImageView.hierarchy.setPlaceholderImage(
DisplayUtils.getRoundedDrawable(layerDrawable)
)
} }
else -> { else -> {
@ -596,17 +662,26 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
} }
} }
override fun onItemClick(view: View?, position: Int): Boolean { override fun onItemClick(
view: View?,
position: Int
): Boolean {
val userItem = adapter?.getItem(position) as UserItem val userItem = adapter?.getItem(position) as UserItem
val participant = userItem.model val participant = userItem.model
if (participant.userId != conversationUser!!.userId) { if (participant.userId != conversationUser!!.userId) {
var items = mutableListOf( var items = mutableListOf(
BasicListItemWithImage(R.drawable.ic_pencil_grey600_24dp, context.getString(R.string.nc_promote)), BasicListItemWithImage(
BasicListItemWithImage(R.drawable.ic_pencil_grey600_24dp, context.getString(R.string.nc_demote)), R.drawable.ic_pencil_grey600_24dp, context.getString(R.string.nc_promote)
BasicListItemWithImage(R.drawable.ic_delete_grey600_24dp, ),
context.getString(R.string.nc_remove_participant)) BasicListItemWithImage(
R.drawable.ic_pencil_grey600_24dp, context.getString(R.string.nc_demote)
),
BasicListItemWithImage(
R.drawable.ic_delete_grey600_24dp,
context.getString(R.string.nc_remove_participant)
)
) )
if (!conversation!!.canModerate(conversationUser)) { if (!conversation!!.canModerate(conversationUser)) {
@ -629,14 +704,22 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
if (index == 0) { if (index == 0) {
if (participant.type == Participant.ParticipantType.MODERATOR) { if (participant.type == Participant.ParticipantType.MODERATOR) {
ncApi.demoteModeratorToUser(credentials, ApiUtils.getUrlForModerators(conversationUser.baseUrl, conversation!!.token), participant.userId) ncApi.demoteModeratorToUser(
credentials,
ApiUtils.getUrlForModerators(conversationUser.baseUrl, conversation!!.token),
participant.userId
)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe { .subscribe {
getListOfParticipants() getListOfParticipants()
} }
} else if (participant.type == Participant.ParticipantType.USER) { } else if (participant.type == Participant.ParticipantType.USER) {
ncApi.promoteUserToModerator(credentials, ApiUtils.getUrlForModerators(conversationUser.baseUrl, conversation!!.token), participant.userId) ncApi.promoteUserToModerator(
credentials,
ApiUtils.getUrlForModerators(conversationUser.baseUrl, conversation!!.token),
participant.userId
)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe { .subscribe {
@ -645,8 +728,13 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
} }
} else if (index == 1) { } else if (index == 1) {
if (participant.type == Participant.ParticipantType.GUEST || if (participant.type == Participant.ParticipantType.GUEST ||
participant.type == Participant.ParticipantType.USER_FOLLOWING_LINK) { participant.type == Participant.ParticipantType.USER_FOLLOWING_LINK
ncApi.removeParticipantFromConversation(credentials, ApiUtils.getUrlForRemovingParticipantFromConversation(conversationUser.baseUrl, conversation!!.token, true), participant.sessionId) ) {
ncApi.removeParticipantFromConversation(
credentials, ApiUtils.getUrlForRemovingParticipantFromConversation(
conversationUser.baseUrl, conversation!!.token, true
), participant.sessionId
)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe { .subscribe {
@ -654,7 +742,11 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
} }
} else { } else {
ncApi.removeParticipantFromConversation(credentials, ApiUtils.getUrlForRemovingParticipantFromConversation(conversationUser.baseUrl, conversation!!.token, false), participant.userId) ncApi.removeParticipantFromConversation(
credentials, ApiUtils.getUrlForRemovingParticipantFromConversation(
conversationUser.baseUrl, conversation!!.token, false
), participant.userId
)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe { .subscribe {

View File

@ -36,8 +36,6 @@ import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo; import android.view.inputmethod.EditorInfo;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView; import androidx.appcompat.widget.SearchView;
import androidx.core.graphics.drawable.RoundedBitmapDrawable; import androidx.core.graphics.drawable.RoundedBitmapDrawable;
@ -65,8 +63,6 @@ import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequest;
import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.kennyc.bottomsheet.BottomSheet; import com.kennyc.bottomsheet.BottomSheet;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.models.json.participants.Participant;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.activities.MagicCallActivity; import com.nextcloud.talk.activities.MagicCallActivity;
import com.nextcloud.talk.adapters.items.CallItem; import com.nextcloud.talk.adapters.items.CallItem;
@ -82,6 +78,8 @@ import com.nextcloud.talk.events.MoreMenuClickEvent;
import com.nextcloud.talk.interfaces.ConversationMenuInterface; import com.nextcloud.talk.interfaces.ConversationMenuInterface;
import com.nextcloud.talk.jobs.DeleteConversationWorker; import com.nextcloud.talk.jobs.DeleteConversationWorker;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.models.json.participants.Participant;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.ConductorRemapping; import com.nextcloud.talk.utils.ConductorRemapping;
import com.nextcloud.talk.utils.DisplayUtils; import com.nextcloud.talk.utils.DisplayUtils;
@ -111,7 +109,8 @@ import org.parceler.Parcels;
import retrofit2.HttpException; import retrofit2.HttpException;
@AutoInjector(NextcloudTalkApplication.class) @AutoInjector(NextcloudTalkApplication.class)
public class ConversationsListController extends BaseController implements SearchView.OnQueryTextListener, public class ConversationsListController extends BaseController
implements SearchView.OnQueryTextListener,
FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, FastScroller FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, FastScroller
.OnScrollStateChangeListener, ConversationMenuInterface { .OnScrollStateChangeListener, ConversationMenuInterface {
@ -180,7 +179,9 @@ public class ConversationsListController extends BaseController implements Searc
@Override @Override
protected void onViewBound(@NonNull View view) { protected void onViewBound(@NonNull View view) {
super.onViewBound(view); super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
if (getActionBar() != null) { if (getActionBar() != null) {
getActionBar().show(); getActionBar().show();
@ -202,17 +203,21 @@ public class ConversationsListController extends BaseController implements Searc
private void loadUserAvatar(MenuItem menuItem) { private void loadUserAvatar(MenuItem menuItem) {
if (getActivity() != null) { if (getActivity() != null) {
int avatarSize = (int) DisplayUtils.convertDpToPixel(menuItem.getIcon().getIntrinsicHeight(), getActivity()); int avatarSize = (int) DisplayUtils.convertDpToPixel(menuItem.getIcon().getIntrinsicHeight(),
ImageRequest imageRequest = DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithNameAndPixels(currentUser.getBaseUrl(), getActivity());
ImageRequest imageRequest = DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithNameAndPixels(currentUser.getBaseUrl(),
currentUser.getUserId(), avatarSize), null); currentUser.getUserId(), avatarSize), null);
ImagePipeline imagePipeline = Fresco.getImagePipeline(); ImagePipeline imagePipeline = Fresco.getImagePipeline();
DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, null); DataSource<CloseableReference<CloseableImage>> dataSource =
imagePipeline.fetchDecodedImage(imageRequest, null);
dataSource.subscribe(new BaseBitmapDataSubscriber() { dataSource.subscribe(new BaseBitmapDataSubscriber() {
@Override @Override
protected void onNewResultImpl(Bitmap bitmap) { protected void onNewResultImpl(Bitmap bitmap) {
if (bitmap != null && getResources() != null) { if (bitmap != null && getResources() != null) {
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap); RoundedBitmapDrawable roundedBitmapDrawable =
RoundedBitmapDrawableFactory.create(getResources(), bitmap);
roundedBitmapDrawable.setCircular(true); roundedBitmapDrawable.setCircular(true);
roundedBitmapDrawable.setAntiAlias(true); roundedBitmapDrawable.setAntiAlias(true);
menuItem.setIcon(roundedBitmapDrawable); menuItem.setIcon(roundedBitmapDrawable);
@ -239,22 +244,24 @@ public class ConversationsListController extends BaseController implements Searc
} }
} }
private void initSearchView() { private void initSearchView() {
if (getActivity() != null) { if (getActivity() != null) {
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE); SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) { if (searchItem != null) {
searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setMaxWidth(Integer.MAX_VALUE); searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER); searchView.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER);
int imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_FULLSCREEN; int imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_FULLSCREEN;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && appPreferences.getIsKeyboardIncognito()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& appPreferences.getIsKeyboardIncognito()) {
imeOptions |= EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING; imeOptions |= EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING;
} }
searchView.setImeOptions(imeOptions); searchView.setImeOptions(imeOptions);
searchView.setQueryHint(getResources().getString(R.string.nc_search)); searchView.setQueryHint(getResources().getString(R.string.nc_search));
if (searchManager != null) { if (searchManager != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName())); searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
} }
searchView.setOnQueryTextListener(this); searchView.setOnQueryTextListener(this);
} }
@ -268,8 +275,10 @@ public class ConversationsListController extends BaseController implements Searc
ArrayList<String> names = new ArrayList<>(); ArrayList<String> names = new ArrayList<>();
names.add("userAvatar.transitionTag"); names.add("userAvatar.transitionTag");
getRouter().pushController((RouterTransaction.with(new SettingsController()) getRouter().pushController((RouterTransaction.with(new SettingsController())
.pushChangeHandler(new TransitionChangeHandlerCompat(new SharedElementTransition(names), new VerticalChangeHandler())) .pushChangeHandler(new TransitionChangeHandlerCompat(new SharedElementTransition(names),
.popChangeHandler(new TransitionChangeHandlerCompat(new SharedElementTransition(names), new VerticalChangeHandler())))); new VerticalChangeHandler()))
.popChangeHandler(new TransitionChangeHandlerCompat(new SharedElementTransition(names),
new VerticalChangeHandler()))));
return true; return true;
default: default:
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
@ -370,7 +379,6 @@ public class ConversationsListController extends BaseController implements Searc
if (swipeRefreshLayout != null) { if (swipeRefreshLayout != null) {
swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setRefreshing(false);
} }
}, throwable -> { }, throwable -> {
if (searchItem != null) { if (searchItem != null) {
searchItem.setVisible(false); searchItem.setVisible(false);
@ -412,7 +420,6 @@ public class ConversationsListController extends BaseController implements Searc
isRefreshing = false; isRefreshing = false;
}); });
} }
private void prepareViews() { private void prepareViews() {
@ -528,12 +535,14 @@ public class ConversationsListController extends BaseController implements Searc
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
Conversation conversation = moreMenuClickEvent.getConversation(); Conversation conversation = moreMenuClickEvent.getConversation();
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ROOM(), Parcels.wrap(conversation)); bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ROOM(), Parcels.wrap(conversation));
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_MENU_TYPE(), Parcels.wrap(CallMenuController.MenuType.REGULAR)); bundle.putParcelable(BundleKeys.INSTANCE.getKEY_MENU_TYPE(),
Parcels.wrap(CallMenuController.MenuType.REGULAR));
prepareAndShowBottomSheetWithBundle(bundle, true); prepareAndShowBottomSheetWithBundle(bundle, true);
} }
private void prepareAndShowBottomSheetWithBundle(Bundle bundle, boolean shouldShowCallMenuController) { private void prepareAndShowBottomSheetWithBundle(Bundle bundle,
boolean shouldShowCallMenuController) {
if (view == null) { if (view == null) {
view = getActivity().getLayoutInflater().inflate(R.layout.bottom_sheet, null, false); view = getActivity().getLayoutInflater().inflate(R.layout.bottom_sheet, null, false);
} }
@ -554,12 +563,13 @@ public class ConversationsListController extends BaseController implements Searc
bottomSheet = new BottomSheet.Builder(getActivity()).setView(view).create(); bottomSheet = new BottomSheet.Builder(getActivity()).setView(view).create();
} }
bottomSheet.setOnShowListener(dialog -> new KeyboardUtils(getActivity(), bottomSheet.getLayout(), true)); bottomSheet.setOnShowListener(
bottomSheet.setOnDismissListener(dialog -> getActionBar().setDisplayHomeAsUpEnabled(getRouter().getBackstackSize() > 1)); dialog -> new KeyboardUtils(getActivity(), bottomSheet.getLayout(), true));
bottomSheet.setOnDismissListener(
dialog -> getActionBar().setDisplayHomeAsUpEnabled(getRouter().getBackstackSize() > 1));
bottomSheet.show(); bottomSheet.show();
} }
@Override @Override
public String getTitle() { public String getTitle() {
return getResources().getString(R.string.nc_app_name); return getResources().getString(R.string.nc_app_name);
@ -586,15 +596,18 @@ public class ConversationsListController extends BaseController implements Searc
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), conversation.getToken()); bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), conversation.getToken());
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), conversation.getRoomId()); bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), conversation.getRoomId());
if (conversation.hasPassword && (conversation.getParticipantType().equals(Participant.ParticipantType.GUEST) || if (conversation.hasPassword && (conversation.getParticipantType()
conversation.getParticipantType().equals(Participant.ParticipantType.USER_FOLLOWING_LINK))) { .equals(Participant.ParticipantType.GUEST) ||
conversation.getParticipantType()
.equals(Participant.ParticipantType.USER_FOLLOWING_LINK))) {
bundle.putInt(BundleKeys.INSTANCE.getKEY_OPERATION_CODE(), 99); bundle.putInt(BundleKeys.INSTANCE.getKEY_OPERATION_CODE(), 99);
prepareAndShowBottomSheetWithBundle(bundle, false); prepareAndShowBottomSheetWithBundle(bundle, false);
} else { } else {
currentUser = userUtils.getCurrentUser(); currentUser = userUtils.getCurrentUser();
if (currentUser.hasSpreedFeatureCapability("chat-v2")) { if (currentUser.hasSpreedFeatureCapability("chat-v2")) {
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(), Parcels.wrap(conversation)); bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(),
Parcels.wrap(conversation));
ConductorRemapping.INSTANCE.remapChatController(getRouter(), currentUser.getId(), ConductorRemapping.INSTANCE.remapChatController(getRouter(), currentUser.getId(),
conversation.getToken(), bundle, false); conversation.getToken(), bundle, false);
} else { } else {
@ -644,7 +657,11 @@ public class ConversationsListController extends BaseController implements Searc
} }
private void showDeleteConversationDialog(Bundle savedInstanceState) { private void showDeleteConversationDialog(Bundle savedInstanceState) {
if (getActivity() != null && conversationMenuBundle != null && currentUser != null && conversationMenuBundle.getLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID()) == currentUser.getId()) { if (getActivity() != null
&& conversationMenuBundle != null
&& currentUser != null
&& conversationMenuBundle.getLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID())
== currentUser.getId()) {
Conversation conversation = Conversation conversation =
Parcels.unwrap(conversationMenuBundle.getParcelable(BundleKeys.INSTANCE.getKEY_ROOM())); Parcels.unwrap(conversationMenuBundle.getParcelable(BundleKeys.INSTANCE.getKEY_ROOM()));
@ -707,6 +724,5 @@ public class ConversationsListController extends BaseController implements Searc
default: default:
break; break;
} }
} }
} }

View File

@ -62,7 +62,9 @@ public class LockedController extends BaseController {
@Override @Override
protected void onViewBound(@NonNull View view) { protected void onViewBound(@NonNull View view) {
super.onViewBound(view); super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
if (getActionBar() != null) { if (getActionBar() != null) {
getActionBar().hide(); getActionBar().hide();
} }
@ -87,19 +89,23 @@ public class LockedController extends BaseController {
if (context != null) { if (context != null) {
final BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder() final BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()
.setTitle(String.format(context.getString(R.string.nc_biometric_unlock), context.getString(R.string.nc_app_name))) .setTitle(String.format(context.getString(R.string.nc_biometric_unlock),
context.getString(R.string.nc_app_name)))
.setNegativeButtonText(context.getString(R.string.nc_cancel)) .setNegativeButtonText(context.getString(R.string.nc_cancel))
.build(); .build();
Executor executor = Executors.newSingleThreadExecutor(); Executor executor = Executors.newSingleThreadExecutor();
final BiometricPrompt biometricPrompt = new BiometricPrompt((FragmentActivity) context, executor, final BiometricPrompt biometricPrompt =
new BiometricPrompt((FragmentActivity) context, executor,
new BiometricPrompt.AuthenticationCallback() { new BiometricPrompt.AuthenticationCallback() {
@Override @Override
public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) { public void onAuthenticationSucceeded(
@NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result); super.onAuthenticationSucceeded(result);
Log.d(TAG, "Fingerprint recognised successfully"); Log.d(TAG, "Fingerprint recognised successfully");
new Handler(Looper.getMainLooper()).post(() -> getRouter().popCurrentController()); new Handler(Looper.getMainLooper()).post(
() -> getRouter().popCurrentController());
} }
@Override @Override
@ -128,8 +134,11 @@ public class LockedController extends BaseController {
@RequiresApi(api = Build.VERSION_CODES.M) @RequiresApi(api = Build.VERSION_CODES.M)
private void checkIfWeAreSecure() { private void checkIfWeAreSecure() {
if (getActivity() != null) { if (getActivity() != null) {
KeyguardManager keyguardManager = (KeyguardManager) getActivity().getSystemService(Context.KEYGUARD_SERVICE); KeyguardManager keyguardManager =
if (keyguardManager != null && keyguardManager.isKeyguardSecure() && appPreferences.getIsScreenLocked()) { (KeyguardManager) getActivity().getSystemService(Context.KEYGUARD_SERVICE);
if (keyguardManager != null
&& keyguardManager.isKeyguardSecure()
&& appPreferences.getIsScreenLocked()) {
if (!SecurityUtils.checkIfWeAreAuthenticated(appPreferences.getScreenLockTimeout())) { if (!SecurityUtils.checkIfWeAreAuthenticated(appPreferences.getScreenLockTimeout())) {
showBiometricDialog(); showBiometricDialog();
} else { } else {
@ -141,7 +150,8 @@ public class LockedController extends BaseController {
private void showAuthenticationScreen() { private void showAuthenticationScreen() {
if (getActivity() != null) { if (getActivity() != null) {
KeyguardManager keyguardManager = (KeyguardManager) getActivity().getSystemService(Context.KEYGUARD_SERVICE); KeyguardManager keyguardManager =
(KeyguardManager) getActivity().getSystemService(Context.KEYGUARD_SERVICE);
Intent intent = keyguardManager.createConfirmDeviceCredentialIntent(null, null); Intent intent = keyguardManager.createConfirmDeviceCredentialIntent(null, null);
if (intent != null) { if (intent != null) {
startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS); startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS);

View File

@ -40,11 +40,11 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import autodagger.AutoInjector; import autodagger.AutoInjector;
import butterknife.BindView; import butterknife.BindView;
import com.bluelinelabs.logansquare.LoganSquare; import com.bluelinelabs.logansquare.LoganSquare;
import com.nextcloud.talk.models.RingtoneSettings;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.adapters.items.NotificationSoundItem; import com.nextcloud.talk.adapters.items.NotificationSoundItem;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.controllers.base.BaseController; import com.nextcloud.talk.controllers.base.BaseController;
import com.nextcloud.talk.models.RingtoneSettings;
import com.nextcloud.talk.utils.bundle.BundleKeys; import com.nextcloud.talk.utils.bundle.BundleKeys;
import com.nextcloud.talk.utils.preferences.AppPreferences; import com.nextcloud.talk.utils.preferences.AppPreferences;
import eu.davidea.flexibleadapter.FlexibleAdapter; import eu.davidea.flexibleadapter.FlexibleAdapter;
@ -57,7 +57,8 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
@AutoInjector(NextcloudTalkApplication.class) @AutoInjector(NextcloudTalkApplication.class)
public class RingtoneSelectionController extends BaseController implements FlexibleAdapter.OnItemClickListener { public class RingtoneSelectionController extends BaseController
implements FlexibleAdapter.OnItemClickListener {
private static final String TAG = "RingtoneSelectionController"; private static final String TAG = "RingtoneSelectionController";
@ -84,7 +85,8 @@ public class RingtoneSelectionController extends BaseController implements Flexi
public RingtoneSelectionController(Bundle args) { public RingtoneSelectionController(Bundle args) {
super(); super();
setHasOptionsMenu(true); setHasOptionsMenu(true);
this.callNotificationSounds = args.getBoolean(BundleKeys.INSTANCE.getKEY_ARE_CALL_SOUNDS(), false); this.callNotificationSounds =
args.getBoolean(BundleKeys.INSTANCE.getKEY_ARE_CALL_SOUNDS(), false);
} }
@Override @Override
@ -95,7 +97,9 @@ public class RingtoneSelectionController extends BaseController implements Flexi
@Override @Override
protected void onViewBound(@NonNull View view) { protected void onViewBound(@NonNull View view) {
super.onViewBound(view); super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
if (adapter == null) { if (adapter == null) {
adapter = new FlexibleAdapter<>(abstractFlexibleItemList, getActivity(), false); adapter = new FlexibleAdapter<>(abstractFlexibleItemList, getActivity(), false);
@ -146,7 +150,8 @@ public class RingtoneSelectionController extends BaseController implements Flexi
boolean foundDefault = false; boolean foundDefault = false;
String preferencesString = null; String preferencesString = null;
if ((callNotificationSounds && TextUtils.isEmpty((preferencesString = appPreferences.getCallRingtoneUri()))) if ((callNotificationSounds && TextUtils.isEmpty(
(preferencesString = appPreferences.getCallRingtoneUri())))
|| (!callNotificationSounds && TextUtils.isEmpty((preferencesString = appPreferences || (!callNotificationSounds && TextUtils.isEmpty((preferencesString = appPreferences
.getMessageRingtoneUri())))) { .getMessageRingtoneUri())))) {
adapter.toggleSelection(1); adapter.toggleSelection(1);
@ -155,7 +160,8 @@ public class RingtoneSelectionController extends BaseController implements Flexi
if (!TextUtils.isEmpty(preferencesString) && !foundDefault) { if (!TextUtils.isEmpty(preferencesString) && !foundDefault) {
try { try {
RingtoneSettings ringtoneSettings = LoganSquare.parse(preferencesString, RingtoneSettings.class); RingtoneSettings ringtoneSettings =
LoganSquare.parse(preferencesString, RingtoneSettings.class);
if (ringtoneSettings.getRingtoneUri() == null) { if (ringtoneSettings.getRingtoneUri() == null) {
adapter.toggleSelection(0); adapter.toggleSelection(0);
} else if (ringtoneSettings.getRingtoneUri().toString().equals(getRingtoneString())) { } else if (ringtoneSettings.getRingtoneUri().toString().equals(getRingtoneString())) {
@ -164,7 +170,8 @@ public class RingtoneSelectionController extends BaseController implements Flexi
NotificationSoundItem notificationSoundItem; NotificationSoundItem notificationSoundItem;
for (int i = 2; i < adapter.getItemCount(); i++) { for (int i = 2; i < adapter.getItemCount(); i++) {
notificationSoundItem = (NotificationSoundItem) adapter.getItem(i); notificationSoundItem = (NotificationSoundItem) adapter.getItem(i);
if (notificationSoundItem.getNotificationSoundUri().equals(ringtoneSettings.getRingtoneUri().toString())) { if (notificationSoundItem.getNotificationSoundUri()
.equals(ringtoneSettings.getRingtoneUri().toString())) {
adapter.toggleSelection(i); adapter.toggleSelection(i);
break; break;
} }
@ -187,15 +194,15 @@ public class RingtoneSelectionController extends BaseController implements Flexi
return ("android.resource://" + context.getPackageName() + "/raw" + return ("android.resource://" + context.getPackageName() + "/raw" +
"/librem_by_feandesign_message"); "/librem_by_feandesign_message");
} }
} }
private void fetchNotificationSounds() { private void fetchNotificationSounds() {
abstractFlexibleItemList.add(new NotificationSoundItem(getResources().getString(R.string.nc_settings_no_ringtone), null)); abstractFlexibleItemList.add(
new NotificationSoundItem(getResources().getString(R.string.nc_settings_no_ringtone),
null));
abstractFlexibleItemList.add(new NotificationSoundItem(getResources() abstractFlexibleItemList.add(new NotificationSoundItem(getResources()
.getString(R.string.nc_settings_default_ringtone), getRingtoneString())); .getString(R.string.nc_settings_default_ringtone), getRingtoneString()));
if (getActivity() != null) { if (getActivity() != null) {
RingtoneManager manager = new RingtoneManager(getActivity()); RingtoneManager manager = new RingtoneManager(getActivity());
@ -215,7 +222,8 @@ public class RingtoneSelectionController extends BaseController implements Flexi
String completeNotificationUri = notificationUri + "/" + cursor.getString(RingtoneManager String completeNotificationUri = notificationUri + "/" + cursor.getString(RingtoneManager
.ID_COLUMN_INDEX); .ID_COLUMN_INDEX);
notificationSoundItem = new NotificationSoundItem(notificationTitle, completeNotificationUri); notificationSoundItem =
new NotificationSoundItem(notificationTitle, completeNotificationUri);
abstractFlexibleItemList.add(notificationSoundItem); abstractFlexibleItemList.add(notificationSoundItem);
} }
@ -252,7 +260,8 @@ public class RingtoneSelectionController extends BaseController implements Flexi
mediaPlayer.start(); mediaPlayer.start();
} }
if (adapter.getSelectedPositions().size() == 0 || adapter.getSelectedPositions().get(0) != position) { if (adapter.getSelectedPositions().size() == 0
|| adapter.getSelectedPositions().get(0) != position) {
RingtoneSettings ringtoneSettings = new RingtoneSettings(); RingtoneSettings ringtoneSettings = new RingtoneSettings();
ringtoneSettings.setRingtoneName(notificationSoundItem.getNotificationSoundName()); ringtoneSettings.setRingtoneName(notificationSoundItem.getNotificationSoundName());
ringtoneSettings.setRingtoneUri(ringtoneUri); ringtoneSettings.setRingtoneUri(ringtoneUri);
@ -299,5 +308,4 @@ public class RingtoneSelectionController extends BaseController implements Flexi
endMediaPlayer(); endMediaPlayer();
super.onDestroy(); super.onDestroy();
} }
} }

View File

@ -101,14 +101,16 @@ public class ServerSelectionController extends BaseController {
} }
setCertTextView(); setCertTextView();
}, new String[]{"RSA", "EC"}, null, null, -1, null); }, new String[] { "RSA", "EC" }, null, null, -1, null);
} }
} }
@Override @Override
protected void onViewBound(@NonNull View view) { protected void onViewBound(@NonNull View view) {
super.onViewBound(view); super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
if (getActivity() != null) { if (getActivity() != null) {
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
@ -118,14 +120,16 @@ public class ServerSelectionController extends BaseController {
getActionBar().hide(); getActionBar().hide();
} }
textFieldBoxes.getEndIconImageButton().setBackgroundDrawable(getResources().getDrawable(R.drawable textFieldBoxes.getEndIconImageButton()
.setBackgroundDrawable(getResources().getDrawable(R.drawable
.ic_arrow_forward_white_24px)); .ic_arrow_forward_white_24px));
textFieldBoxes.getEndIconImageButton().setAlpha(0.5f); textFieldBoxes.getEndIconImageButton().setAlpha(0.5f);
textFieldBoxes.getEndIconImageButton().setEnabled(false); textFieldBoxes.getEndIconImageButton().setEnabled(false);
textFieldBoxes.getEndIconImageButton().setVisibility(View.VISIBLE); textFieldBoxes.getEndIconImageButton().setVisibility(View.VISIBLE);
textFieldBoxes.getEndIconImageButton().setOnClickListener(view1 -> checkServerAndProceed()); textFieldBoxes.getEndIconImageButton().setOnClickListener(view1 -> checkServerAndProceed());
if (TextUtils.isEmpty(getResources().getString(R.string.nc_providers_url)) && (TextUtils.isEmpty(getResources if (TextUtils.isEmpty(getResources().getString(R.string.nc_providers_url))
&& (TextUtils.isEmpty(getResources
().getString(R.string.nc_import_account_type)))) { ().getString(R.string.nc_import_account_type)))) {
providersTextView.setVisibility(View.INVISIBLE); providersTextView.setVisibility(View.INVISIBLE);
} else { } else {
@ -145,16 +149,19 @@ public class ServerSelectionController extends BaseController {
.getString(R.string.nc_import_accounts_from)))) { .getString(R.string.nc_import_accounts_from)))) {
if (AccountUtils.INSTANCE.findAccounts(userUtils.getUsers()).size() > 1) { if (AccountUtils.INSTANCE.findAccounts(userUtils.getUsers()).size() > 1) {
providersTextView.setText(String.format(getResources().getString(R.string providersTextView.setText(String.format(getResources().getString(R.string
.nc_server_import_accounts), AccountUtils.INSTANCE.getAppNameBasedOnPackage(getResources() .nc_server_import_accounts),
AccountUtils.INSTANCE.getAppNameBasedOnPackage(getResources()
.getString(R.string.nc_import_accounts_from)))); .getString(R.string.nc_import_accounts_from))));
} else { } else {
providersTextView.setText(String.format(getResources().getString(R.string providersTextView.setText(String.format(getResources().getString(R.string
.nc_server_import_account), AccountUtils.INSTANCE.getAppNameBasedOnPackage(getResources() .nc_server_import_account),
AccountUtils.INSTANCE.getAppNameBasedOnPackage(getResources()
.getString(R.string.nc_import_accounts_from)))); .getString(R.string.nc_import_accounts_from))));
} }
} else { } else {
if (AccountUtils.INSTANCE.findAccounts(userUtils.getUsers()).size() > 1) { if (AccountUtils.INSTANCE.findAccounts(userUtils.getUsers()).size() > 1) {
providersTextView.setText(getResources().getString(R.string.nc_server_import_accounts_plain)); providersTextView.setText(
getResources().getString(R.string.nc_server_import_accounts_plain));
} else { } else {
providersTextView.setText(getResources().getString(R.string providersTextView.setText(getResources().getString(R.string
.nc_server_import_account_plain)); .nc_server_import_account_plain));
@ -281,7 +288,6 @@ public class ServerSelectionController extends BaseController {
, productName), true); , productName), true);
toggleProceedButton(false); toggleProceedButton(false);
} }
}, throwable -> { }, throwable -> {
if (checkForcedHttps) { if (checkForcedHttps) {
checkServer(queryUrl.replace("https://", "http://"), false); checkServer(queryUrl.replace("https://", "http://"), false);
@ -319,7 +325,8 @@ public class ServerSelectionController extends BaseController {
if (ApplicationWideMessageHolder.getInstance().getMessageType() != null) { if (ApplicationWideMessageHolder.getInstance().getMessageType() != null) {
if (ApplicationWideMessageHolder.getInstance().getMessageType() if (ApplicationWideMessageHolder.getInstance().getMessageType()
.equals(ApplicationWideMessageHolder.MessageType.ACCOUNT_SCHEDULED_FOR_DELETION)) { .equals(ApplicationWideMessageHolder.MessageType.ACCOUNT_SCHEDULED_FOR_DELETION)) {
textFieldBoxes.setError(getResources().getString(R.string.nc_account_scheduled_for_deletion), textFieldBoxes.setError(
getResources().getString(R.string.nc_account_scheduled_for_deletion),
false); false);
ApplicationWideMessageHolder.getInstance().setMessageType(null); ApplicationWideMessageHolder.getInstance().setMessageType(null);
} else if (ApplicationWideMessageHolder.getInstance().getMessageType() } else if (ApplicationWideMessageHolder.getInstance().getMessageType()
@ -328,7 +335,8 @@ public class ServerSelectionController extends BaseController {
false); false);
} else if (ApplicationWideMessageHolder.getInstance().getMessageType() } else if (ApplicationWideMessageHolder.getInstance().getMessageType()
.equals(ApplicationWideMessageHolder.MessageType.FAILED_TO_IMPORT_ACCOUNT)) { .equals(ApplicationWideMessageHolder.MessageType.FAILED_TO_IMPORT_ACCOUNT)) {
textFieldBoxes.setError(getResources().getString(R.string.nc_server_failed_to_import_account), textFieldBoxes.setError(
getResources().getString(R.string.nc_server_failed_to_import_account),
false); false);
} }
ApplicationWideMessageHolder.getInstance().setMessageType(null); ApplicationWideMessageHolder.getInstance().setMessageType(null);

View File

@ -52,13 +52,13 @@ import com.bluelinelabs.logansquare.LoganSquare;
import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.drawee.view.SimpleDraweeView;
import com.nextcloud.talk.models.RingtoneSettings;
import com.nextcloud.talk.BuildConfig; import com.nextcloud.talk.BuildConfig;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.controllers.base.BaseController; import com.nextcloud.talk.controllers.base.BaseController;
import com.nextcloud.talk.jobs.AccountRemovalWorker; import com.nextcloud.talk.jobs.AccountRemovalWorker;
import com.nextcloud.talk.models.RingtoneSettings;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.DisplayUtils; import com.nextcloud.talk.utils.DisplayUtils;
@ -182,7 +182,9 @@ public class SettingsController extends BaseController {
setHasOptionsMenu(true); setHasOptionsMenu(true);
ViewCompat.setTransitionName(avatarImageView, "userAvatar.transitionTag"); ViewCompat.setTransitionName(avatarImageView, "userAvatar.transitionTag");
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
getCurrentUser(); getCurrentUser();
@ -190,11 +192,15 @@ public class SettingsController extends BaseController {
saveStateHandler = new LovelySaveStateHandler(); saveStateHandler = new LovelySaveStateHandler();
} }
appPreferences.registerProxyTypeListener(proxyTypeChangeListener = new ProxyTypeChangeListener()); appPreferences.registerProxyTypeListener(
appPreferences.registerProxyCredentialsListener(proxyCredentialsChangeListener = new ProxyCredentialsChangeListener()); proxyTypeChangeListener = new ProxyTypeChangeListener());
appPreferences.registerScreenSecurityListener(screenSecurityChangeListener = new ScreenSecurityChangeListener()); appPreferences.registerProxyCredentialsListener(
proxyCredentialsChangeListener = new ProxyCredentialsChangeListener());
appPreferences.registerScreenSecurityListener(
screenSecurityChangeListener = new ScreenSecurityChangeListener());
appPreferences.registerScreenLockListener(screenLockChangeListener = new ScreenLockListener()); appPreferences.registerScreenLockListener(screenLockChangeListener = new ScreenLockListener());
appPreferences.registerScreenLockTimeoutListener(screenLockTimeoutChangeListener = new ScreenLockTimeoutListener()); appPreferences.registerScreenLockTimeoutListener(
screenLockTimeoutChangeListener = new ScreenLockTimeoutListener());
appPreferences.registerThemeChangeListener(themeChangeListener = new ThemeChangeListener()); appPreferences.registerThemeChangeListener(themeChangeListener = new ThemeChangeListener());
List<String> listWithIntFields = new ArrayList<>(); List<String> listWithIntFields = new ArrayList<>();
@ -232,7 +238,6 @@ public class SettingsController extends BaseController {
getResources().getString(R.string.nc_app_name))); getResources().getString(R.string.nc_app_name)));
} }
if (!TextUtils.isEmpty(getResources().getString(R.string.nc_privacy_url))) { if (!TextUtils.isEmpty(getResources().getString(R.string.nc_privacy_url))) {
privacyButton.addPreferenceClickListener(view12 -> { privacyButton.addPreferenceClickListener(view12 -> {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources(). Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().
@ -297,7 +302,8 @@ public class SettingsController extends BaseController {
String finalHost = host; String finalHost = host;
int finalPort = port; int finalPort = port;
certificateSetup.addPreferenceClickListener(v -> KeyChain.choosePrivateKeyAlias(Objects.requireNonNull(getActivity()), alias -> { certificateSetup.addPreferenceClickListener(
v -> KeyChain.choosePrivateKeyAlias(Objects.requireNonNull(getActivity()), alias -> {
String finalAlias = alias; String finalAlias = alias;
getActivity().runOnUiThread(() -> { getActivity().runOnUiThread(() -> {
if (finalAlias != null) { if (finalAlias != null) {
@ -311,10 +317,11 @@ public class SettingsController extends BaseController {
alias = ""; alias = "";
} }
userUtils.createOrUpdateUser(null, null, null, null, null, null, null,
userUtils.createOrUpdateUser(null, null, null, null, null, null, null, currentUser.getId(), currentUser.getId(),
null, alias, null); null, alias, null);
}, new String[]{"RSA", "EC"}, null, finalHost, finalPort, currentUser.getClientCertificate }, new String[] { "RSA", "EC" }, null, finalHost, finalPort,
currentUser.getClientCertificate
())); ()));
} }
@ -376,7 +383,8 @@ public class SettingsController extends BaseController {
private void removeCurrentAccount() { private void removeCurrentAccount() {
boolean otherUserExists = userUtils.scheduleUserForDeletionWithId(currentUser.getId()); boolean otherUserExists = userUtils.scheduleUserForDeletionWithId(currentUser.getId());
OneTimeWorkRequest accountRemovalWork = new OneTimeWorkRequest.Builder(AccountRemovalWorker.class).build(); OneTimeWorkRequest accountRemovalWork =
new OneTimeWorkRequest.Builder(AccountRemovalWorker.class).build();
WorkManager.getInstance().enqueue(accountRemovalWork); WorkManager.getInstance().enqueue(accountRemovalWork);
if (otherUserExists && getView() != null) { if (otherUserExists && getView() != null) {
@ -407,27 +415,34 @@ public class SettingsController extends BaseController {
} }
if (shouldVibrateSwitchPreference.getVisibility() == View.VISIBLE) { if (shouldVibrateSwitchPreference.getVisibility() == View.VISIBLE) {
((Checkable) shouldVibrateSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.getShouldVibrateSetting()); ((Checkable) shouldVibrateSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(
appPreferences.getShouldVibrateSetting());
} }
((Checkable) screenSecuritySwitchPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.getIsScreenSecured()); ((Checkable) screenSecuritySwitchPreference.findViewById(R.id.mp_checkable)).setChecked(
appPreferences.getIsScreenSecured());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Checkable) incognitoKeyboardSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.getIsKeyboardIncognito()); ((Checkable) incognitoKeyboardSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(
appPreferences.getIsKeyboardIncognito());
} }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
((Checkable) incognitoKeyboardSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.getIsKeyboardIncognito()); ((Checkable) incognitoKeyboardSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(
appPreferences.getIsKeyboardIncognito());
} }
((Checkable) linkPreviewsSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.getAreLinkPreviewsAllowed()); ((Checkable) linkPreviewsSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(
appPreferences.getAreLinkPreviewsAllowed());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); KeyguardManager keyguardManager =
(KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (keyguardManager.isKeyguardSecure()) { if (keyguardManager.isKeyguardSecure()) {
screenLockSwitchPreference.setEnabled(true); screenLockSwitchPreference.setEnabled(true);
screenLockTimeoutChoicePreference.setEnabled(true); screenLockTimeoutChoicePreference.setEnabled(true);
((Checkable) screenLockSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.getIsScreenLocked()); ((Checkable) screenLockSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(
appPreferences.getIsScreenLocked());
screenLockTimeoutChoicePreference.setEnabled(appPreferences.getIsScreenLocked()); screenLockTimeoutChoicePreference.setEnabled(appPreferences.getIsScreenLocked());
@ -453,7 +468,8 @@ public class SettingsController extends BaseController {
RingtoneSettings ringtoneSettings; RingtoneSettings ringtoneSettings;
if (!TextUtils.isEmpty(appPreferences.getCallRingtoneUri())) { if (!TextUtils.isEmpty(appPreferences.getCallRingtoneUri())) {
try { try {
ringtoneSettings = LoganSquare.parse(appPreferences.getCallRingtoneUri(), RingtoneSettings.class); ringtoneSettings =
LoganSquare.parse(appPreferences.getCallRingtoneUri(), RingtoneSettings.class);
ringtoneName = ringtoneSettings.getRingtoneName(); ringtoneName = ringtoneSettings.getRingtoneName();
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, "Failed to parse ringtone name"); Log.e(TAG, "Failed to parse ringtone name");
@ -467,7 +483,8 @@ public class SettingsController extends BaseController {
if (!TextUtils.isEmpty(appPreferences.getMessageRingtoneUri())) { if (!TextUtils.isEmpty(appPreferences.getMessageRingtoneUri())) {
try { try {
ringtoneSettings = LoganSquare.parse(appPreferences.getMessageRingtoneUri(), RingtoneSettings.class); ringtoneSettings =
LoganSquare.parse(appPreferences.getMessageRingtoneUri(), RingtoneSettings.class);
ringtoneName = ringtoneSettings.getRingtoneName(); ringtoneName = ringtoneSettings.getRingtoneName();
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, "Failed to parse ringtone name"); Log.e(TAG, "Failed to parse ringtone name");
@ -524,8 +541,8 @@ public class SettingsController extends BaseController {
.getDisplayNameAlt(); .getDisplayNameAlt();
} }
if ((!TextUtils.isEmpty(displayName) && !displayName.equals(
if ((!TextUtils.isEmpty(displayName) && !displayName.equals(currentUser.getDisplayName()))) { currentUser.getDisplayName()))) {
userUtils.createOrUpdateUser(null, userUtils.createOrUpdateUser(null,
null, null,
@ -539,18 +556,15 @@ public class SettingsController extends BaseController {
}, },
throwable -> { throwable -> {
}, () -> Log.d(TAG, "")); }, () -> Log.d(TAG, ""));
} }
}, throwable -> { }, throwable -> {
}, () -> Log.d(TAG, "")); }, () -> Log.d(TAG, ""));
removeAccountButton.addPreferenceClickListener(view1 -> { removeAccountButton.addPreferenceClickListener(view1 -> {
showLovelyDialog(ID_REMOVE_ACCOUNT_WARNING_DIALOG, null); showLovelyDialog(ID_REMOVE_ACCOUNT_WARNING_DIALOG, null);
}); });
} }
if (userUtils.getUsers().size() <= 1) { if (userUtils.getUsers().size() <= 1) {
switchAccountButton.setVisibility(View.GONE); switchAccountButton.setVisibility(View.GONE);
} }
@ -573,7 +587,8 @@ public class SettingsController extends BaseController {
break; break;
case FAILED_TO_IMPORT_ACCOUNT: case FAILED_TO_IMPORT_ACCOUNT:
messageText.setTextColor(getResources().getColor(R.color.nc_darkRed)); messageText.setTextColor(getResources().getColor(R.color.nc_darkRed));
messageText.setText(getResources().getString(R.string.nc_server_failed_to_import_account)); messageText.setText(
getResources().getString(R.string.nc_server_failed_to_import_account));
messageView.setVisibility(View.VISIBLE); messageView.setVisibility(View.VISIBLE);
break; break;
default: default:
@ -596,7 +611,6 @@ public class SettingsController extends BaseController {
} }
} }
}); });
} else { } else {
if (messageView != null) { if (messageView != null) {
messageView.setVisibility(View.GONE); messageView.setVisibility(View.GONE);
@ -615,7 +629,8 @@ public class SettingsController extends BaseController {
DraweeController draweeController = Fresco.newDraweeControllerBuilder() DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(avatarImageView.getController()) .setOldController(avatarImageView.getController())
.setAutoPlayAnimations(true) .setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(currentUser.getBaseUrl(), .setImageRequest(DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(currentUser.getBaseUrl(),
avatarId, R.dimen.avatar_size_big), null)) avatarId, R.dimen.avatar_size_big), null))
.build(); .build();
avatarImageView.setController(draweeController); avatarImageView.setController(draweeController);
@ -634,7 +649,6 @@ public class SettingsController extends BaseController {
super.onDestroy(); super.onDestroy();
} }
private void hideProxySettings() { private void hideProxySettings() {
appPreferences.removeProxyHost(); appPreferences.removeProxyHost();
appPreferences.removeProxyPort(); appPreferences.removeProxyPort();
@ -711,7 +725,8 @@ public class SettingsController extends BaseController {
} }
} }
private class ProxyCredentialsChangeListener implements OnPreferenceValueChangedListener<Boolean> { private class ProxyCredentialsChangeListener
implements OnPreferenceValueChangedListener<Boolean> {
@Override @Override
public void onChanged(Boolean newValue) { public void onChanged(Boolean newValue) {

View File

@ -37,13 +37,13 @@ import autodagger.AutoInjector;
import butterknife.BindView; import butterknife.BindView;
import com.bluelinelabs.conductor.RouterTransaction; import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler; import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.nextcloud.talk.models.ImportAccount;
import com.nextcloud.talk.models.json.participants.Participant;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.adapters.items.AdvancedUserItem; import com.nextcloud.talk.adapters.items.AdvancedUserItem;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.controllers.base.BaseController; import com.nextcloud.talk.controllers.base.BaseController;
import com.nextcloud.talk.models.ImportAccount;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.participants.Participant;
import com.nextcloud.talk.utils.AccountUtils; import com.nextcloud.talk.utils.AccountUtils;
import com.nextcloud.talk.utils.bundle.BundleKeys; import com.nextcloud.talk.utils.bundle.BundleKeys;
import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.database.user.UserUtils;
@ -77,7 +77,8 @@ public class SwitchAccountController extends BaseController {
private boolean isAccountImport = false; private boolean isAccountImport = false;
private FlexibleAdapter.OnItemClickListener onImportItemClickListener = new FlexibleAdapter.OnItemClickListener() { private FlexibleAdapter.OnItemClickListener onImportItemClickListener =
new FlexibleAdapter.OnItemClickListener() {
@Override @Override
public boolean onItemClick(View view, int position) { public boolean onItemClick(View view, int position) {
if (userItems.size() > position) { if (userItems.size() > position) {
@ -89,7 +90,8 @@ public class SwitchAccountController extends BaseController {
} }
}; };
private FlexibleAdapter.OnItemClickListener onSwitchItemClickListener = new FlexibleAdapter.OnItemClickListener() { private FlexibleAdapter.OnItemClickListener onSwitchItemClickListener =
new FlexibleAdapter.OnItemClickListener() {
@Override @Override
public boolean onItemClick(View view, int position) { public boolean onItemClick(View view, int position) {
if (userItems.size() > position) { if (userItems.size() > position) {
@ -162,7 +164,9 @@ public class SwitchAccountController extends BaseController {
@Override @Override
protected void onViewBound(@NonNull View view) { protected void onViewBound(@NonNull View view) {
super.onViewBound(view); super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
swipeRefreshLayout.setEnabled(false); swipeRefreshLayout.setEnabled(false);
if (getActionBar() != null) { if (getActionBar() != null) {
@ -214,13 +218,11 @@ public class SwitchAccountController extends BaseController {
adapter.addListener(onImportItemClickListener); adapter.addListener(onImportItemClickListener);
adapter.updateDataSet(userItems, false); adapter.updateDataSet(userItems, false);
} }
} }
prepareViews(); prepareViews();
} }
private void prepareViews() { private void prepareViews() {
LinearLayoutManager layoutManager = new SmoothScrollLinearLayoutManager(getActivity()); LinearLayoutManager layoutManager = new SmoothScrollLinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager); recyclerView.setLayoutManager(layoutManager);

View File

@ -50,12 +50,12 @@ import autodagger.AutoInjector;
import butterknife.BindView; import butterknife.BindView;
import com.bluelinelabs.conductor.RouterTransaction; import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler; import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.nextcloud.talk.models.LoginData;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.controllers.base.BaseController; import com.nextcloud.talk.controllers.base.BaseController;
import com.nextcloud.talk.events.CertificateEvent; import com.nextcloud.talk.events.CertificateEvent;
import com.nextcloud.talk.jobs.PushRegistrationWorker; import com.nextcloud.talk.jobs.PushRegistrationWorker;
import com.nextcloud.talk.models.LoginData;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.utils.bundle.BundleKeys; import com.nextcloud.talk.utils.bundle.BundleKeys;
import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.database.user.UserUtils;
@ -102,7 +102,6 @@ public class WebViewLoginController extends BaseController {
@Inject @Inject
CookieManager cookieManager; CookieManager cookieManager;
@BindView(R.id.webview) @BindView(R.id.webview)
WebView webView; WebView webView;
@ -129,7 +128,8 @@ public class WebViewLoginController extends BaseController {
this.isPasswordUpdate = isPasswordUpdate; this.isPasswordUpdate = isPasswordUpdate;
} }
public WebViewLoginController(String baseUrl, boolean isPasswordUpdate, String username, String password) { public WebViewLoginController(String baseUrl, boolean isPasswordUpdate, String username,
String password) {
this.baseUrl = baseUrl; this.baseUrl = baseUrl;
this.isPasswordUpdate = isPasswordUpdate; this.isPasswordUpdate = isPasswordUpdate;
this.username = username; this.username = username;
@ -151,7 +151,9 @@ public class WebViewLoginController extends BaseController {
@Override @Override
protected void onViewBound(@NonNull View view) { protected void onViewBound(@NonNull View view) {
super.onViewBound(view); super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
if (getActivity() != null) { if (getActivity() != null) {
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
@ -161,7 +163,8 @@ public class WebViewLoginController extends BaseController {
getActionBar().hide(); getActionBar().hide();
} }
assembledPrefix = getResources().getString(R.string.nc_talk_login_scheme) + PROTOCOL_SUFFIX + "login/"; assembledPrefix =
getResources().getString(R.string.nc_talk_login_scheme) + PROTOCOL_SUFFIX + "login/";
webView.getSettings().setAllowFileAccess(false); webView.getSettings().setAllowFileAccess(false);
webView.getSettings().setAllowFileAccessFromFileURLs(false); webView.getSettings().setAllowFileAccessFromFileURLs(false);
@ -177,7 +180,8 @@ public class WebViewLoginController extends BaseController {
webView.clearHistory(); webView.clearHistory();
WebView.clearClientCertPreferences(null); WebView.clearClientCertPreferences(null);
webViewFidoBridge = WebViewFidoBridge.createInstanceForWebView((AppCompatActivity) getActivity(), webView); webViewFidoBridge =
WebViewFidoBridge.createInstanceForWebView((AppCompatActivity) getActivity(), webView);
CookieSyncManager.createInstance(getActivity()); CookieSyncManager.createInstance(getActivity());
android.webkit.CookieManager.getInstance().removeAllCookies(null); android.webkit.CookieManager.getInstance().removeAllCookies(null);
@ -230,7 +234,9 @@ public class WebViewLoginController extends BaseController {
} else if (!automatedLoginAttempted) { } else if (!automatedLoginAttempted) {
automatedLoginAttempted = true; automatedLoginAttempted = true;
if (TextUtils.isEmpty(password)) { if (TextUtils.isEmpty(password)) {
webView.loadUrl("javascript:var justStore = document.getElementById('user').value = '" + username + "';"); webView.loadUrl("javascript:var justStore = document.getElementById('user').value = '"
+ username
+ "';");
} else { } else {
webView.loadUrl("javascript: {" + webView.loadUrl("javascript: {" +
"document.getElementById('user').value = '" + username + "';" + "document.getElementById('user').value = '" + username + "';" +
@ -261,7 +267,8 @@ public class WebViewLoginController extends BaseController {
new Thread(() -> { new Thread(() -> {
try { try {
PrivateKey privateKey = KeyChain.getPrivateKey(getActivity(), finalAlias); PrivateKey privateKey = KeyChain.getPrivateKey(getActivity(), finalAlias);
X509Certificate[] certificates = KeyChain.getCertificateChain(getActivity(), finalAlias); X509Certificate[] certificates =
KeyChain.getCertificateChain(getActivity(), finalAlias);
if (privateKey != null && certificates != null) { if (privateKey != null && certificates != null) {
request.proceed(privateKey, certificates); request.proceed(privateKey, certificates);
} else { } else {
@ -279,7 +286,8 @@ public class WebViewLoginController extends BaseController {
PrivateKey privateKey = null; PrivateKey privateKey = null;
try { try {
privateKey = KeyChain.getPrivateKey(getActivity(), chosenAlias); privateKey = KeyChain.getPrivateKey(getActivity(), chosenAlias);
X509Certificate[] certificates = KeyChain.getCertificateChain(getActivity(), chosenAlias); X509Certificate[] certificates =
KeyChain.getCertificateChain(getActivity(), chosenAlias);
if (privateKey != null && certificates != null) { if (privateKey != null && certificates != null) {
request.proceed(privateKey, certificates); request.proceed(privateKey, certificates);
} else { } else {
@ -292,7 +300,7 @@ public class WebViewLoginController extends BaseController {
} else { } else {
request.cancel(); request.cancel();
} }
}, new String[]{"RSA", "EC"}, null, request.getHost(), request.getPort(), null); }, new String[] { "RSA", "EC" }, null, request.getHost(), request.getPort(), null);
} }
} }
@ -308,7 +316,7 @@ public class WebViewLoginController extends BaseController {
handler.cancel(); handler.cancel();
} else { } else {
try { try {
magicTrustManager.checkServerTrusted(new X509Certificate[]{cert}, "generic"); magicTrustManager.checkServerTrusted(new X509Certificate[] { cert }, "generic");
handler.proceed(); handler.proceed();
} catch (CertificateException exception) { } catch (CertificateException exception) {
eventBus.post(new CertificateEvent(cert, magicTrustManager, handler)); eventBus.post(new CertificateEvent(cert, magicTrustManager, handler));
@ -320,7 +328,8 @@ public class WebViewLoginController extends BaseController {
} }
@Override @Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { public void onReceivedError(WebView view, int errorCode, String description,
String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl); super.onReceivedError(view, errorCode, description, failingUrl);
} }
}); });
@ -346,7 +355,8 @@ public class WebViewLoginController extends BaseController {
ApplicationWideMessageHolder.MessageType messageType = null; ApplicationWideMessageHolder.MessageType messageType = null;
if (!isPasswordUpdate && userUtils.getIfUserWithUsernameAndServer(loginData.getUsername(), baseUrl)) { if (!isPasswordUpdate && userUtils.getIfUserWithUsernameAndServer(loginData.getUsername(),
baseUrl)) {
messageType = ApplicationWideMessageHolder.MessageType.ACCOUNT_UPDATED_NOT_ADDED; messageType = ApplicationWideMessageHolder.MessageType.ACCOUNT_UPDATED_NOT_ADDED;
} }
@ -398,7 +408,8 @@ public class WebViewLoginController extends BaseController {
ApplicationWideMessageHolder.getInstance().setMessageType(finalMessageType); ApplicationWideMessageHolder.getInstance().setMessageType(finalMessageType);
} }
OneTimeWorkRequest pushRegistrationWork = new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build(); OneTimeWorkRequest pushRegistrationWork =
new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
WorkManager.getInstance().enqueue(pushRegistrationWork); WorkManager.getInstance().enqueue(pushRegistrationWork);
getRouter().popCurrentController(); getRouter().popCurrentController();
@ -410,7 +421,6 @@ public class WebViewLoginController extends BaseController {
ApplicationWideMessageHolder.getInstance().setMessageType(finalMessageType); ApplicationWideMessageHolder.getInstance().setMessageType(finalMessageType);
} }
getRouter().popToRoot(); getRouter().popToRoot();
} }
} }
} }
@ -447,7 +457,9 @@ public class WebViewLoginController extends BaseController {
} }
} }
if (!TextUtils.isEmpty(loginData.getServerUrl()) && !TextUtils.isEmpty(loginData.getUsername()) && if (!TextUtils.isEmpty(loginData.getServerUrl())
&& !TextUtils.isEmpty(loginData.getUsername())
&&
!TextUtils.isEmpty(loginData.getToken())) { !TextUtils.isEmpty(loginData.getToken())) {
return loginData; return loginData;
} else { } else {

View File

@ -37,9 +37,15 @@ abstract class ButterKnifeController : Controller {
constructor(args: Bundle) : super(args) constructor(args: Bundle) : super(args)
protected abstract fun inflateView(inflater: LayoutInflater, container: ViewGroup): View protected abstract fun inflateView(
inflater: LayoutInflater,
container: ViewGroup
): View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup
): View {
val view = inflateView(inflater, container) val view = inflateView(inflater, container)
unbinder = ButterKnife.bind(this, view) unbinder = ButterKnife.bind(this, view)
onViewBound(view) onViewBound(view)

View File

@ -91,7 +91,6 @@ public class EntryMenuController extends BaseController {
private EmojiPopup emojiPopup; private EmojiPopup emojiPopup;
private Bundle originalBundle; private Bundle originalBundle;
public EntryMenuController(Bundle args) { public EntryMenuController(Bundle args) {
@ -104,7 +103,8 @@ public class EntryMenuController extends BaseController {
} }
if (args.containsKey(BundleKeys.INSTANCE.getKEY_SHARE_INTENT())) { if (args.containsKey(BundleKeys.INSTANCE.getKEY_SHARE_INTENT())) {
this.shareIntent = Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_SHARE_INTENT())); this.shareIntent =
Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_SHARE_INTENT()));
} }
this.name = args.getString(BundleKeys.INSTANCE.getKEY_APP_ITEM_NAME(), ""); this.name = args.getString(BundleKeys.INSTANCE.getKEY_APP_ITEM_NAME(), "");
@ -126,7 +126,9 @@ public class EntryMenuController extends BaseController {
protected void onAttach(@NonNull View view) { protected void onAttach(@NonNull View view) {
super.onAttach(view); super.onAttach(view);
if (ApplicationWideMessageHolder.getInstance().getMessageType() != null && if (ApplicationWideMessageHolder.getInstance().getMessageType() != null &&
ApplicationWideMessageHolder.getInstance().getMessageType().equals(ApplicationWideMessageHolder.MessageType.CALL_PASSWORD_WRONG)) { ApplicationWideMessageHolder.getInstance()
.getMessageType()
.equals(ApplicationWideMessageHolder.MessageType.CALL_PASSWORD_WRONG)) {
textInputLayout.setError(getResources().getString(R.string.nc_wrong_password)); textInputLayout.setError(getResources().getString(R.string.nc_wrong_password));
ApplicationWideMessageHolder.getInstance().setMessageType(null); ApplicationWideMessageHolder.getInstance().setMessageType(null);
if (proceedButton.isEnabled()) { if (proceedButton.isEnabled()) {
@ -144,10 +146,12 @@ public class EntryMenuController extends BaseController {
bundle = new Bundle(); bundle = new Bundle();
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ROOM(), Parcels.wrap(conversation)); bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ROOM(), Parcels.wrap(conversation));
bundle.putString(BundleKeys.INSTANCE.getKEY_CALL_URL(), callUrl); bundle.putString(BundleKeys.INSTANCE.getKEY_CALL_URL(), callUrl);
bundle.putString(BundleKeys.INSTANCE.getKEY_CONVERSATION_PASSWORD(), editText.getText().toString()); bundle.putString(BundleKeys.INSTANCE.getKEY_CONVERSATION_PASSWORD(),
editText.getText().toString());
bundle.putInt(BundleKeys.INSTANCE.getKEY_OPERATION_CODE(), operationCode); bundle.putInt(BundleKeys.INSTANCE.getKEY_OPERATION_CODE(), operationCode);
if (originalBundle.containsKey(BundleKeys.INSTANCE.getKEY_SERVER_CAPABILITIES())) { if (originalBundle.containsKey(BundleKeys.INSTANCE.getKEY_SERVER_CAPABILITIES())) {
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_SERVER_CAPABILITIES(), originalBundle.getParcelable(BundleKeys.INSTANCE.getKEY_SERVER_CAPABILITIES())); bundle.putParcelable(BundleKeys.INSTANCE.getKEY_SERVER_CAPABILITIES(),
originalBundle.getParcelable(BundleKeys.INSTANCE.getKEY_SERVER_CAPABILITIES()));
} }
getRouter().pushController(RouterTransaction.with(new OperationsMenuController(bundle)) getRouter().pushController(RouterTransaction.with(new OperationsMenuController(bundle))
@ -184,28 +188,32 @@ public class EntryMenuController extends BaseController {
getRouter().pushController(RouterTransaction.with(new OperationsMenuController(bundle)) getRouter().pushController(RouterTransaction.with(new OperationsMenuController(bundle))
.pushChangeHandler(new HorizontalChangeHandler()) .pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new HorizontalChangeHandler())); .popChangeHandler(new HorizontalChangeHandler()));
} else if (operationCode == 11) { } else if (operationCode == 11) {
eventBus.post(new BottomSheetLockEvent(false, 0, false, false)); eventBus.post(new BottomSheetLockEvent(false, 0, false, false));
originalBundle.putString(BundleKeys.INSTANCE.getKEY_CONVERSATION_NAME(), editText.getText().toString()); originalBundle.putString(BundleKeys.INSTANCE.getKEY_CONVERSATION_NAME(),
getRouter().pushController(RouterTransaction.with(new OperationsMenuController(originalBundle)) editText.getText().toString());
getRouter().pushController(
RouterTransaction.with(new OperationsMenuController(originalBundle))
.pushChangeHandler(new HorizontalChangeHandler()) .pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new HorizontalChangeHandler())); .popChangeHandler(new HorizontalChangeHandler()));
} }
} }
@Override @Override
protected void onViewBound(@NonNull View view) { protected void onViewBound(@NonNull View view) {
super.onViewBound(view); super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
if (conversation != null && operationCode == 2) { if (conversation != null && operationCode == 2) {
editText.setText(conversation.getName()); editText.setText(conversation.getName());
} }
editText.setOnEditorActionListener((v, actionId, event) -> { editText.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE && proceedButton != null && proceedButton.isEnabled()) { if (actionId == EditorInfo.IME_ACTION_DONE
&& proceedButton != null
&& proceedButton.isEnabled()) {
proceedButton.callOnClick(); proceedButton.callOnClick();
return true; return true;
} }
@ -279,7 +287,8 @@ public class EntryMenuController extends BaseController {
labelText = getResources().getString(R.string.nc_call_name); labelText = getResources().getString(R.string.nc_call_name);
editText.setInputType(InputType.TYPE_CLASS_TEXT); editText.setInputType(InputType.TYPE_CLASS_TEXT);
smileyButton.setVisibility(View.VISIBLE); smileyButton.setVisibility(View.VISIBLE);
emojiPopup = EmojiPopup.Builder.fromRootView(view).setOnEmojiPopupShownListener(new OnEmojiPopupShownListener() { emojiPopup = EmojiPopup.Builder.fromRootView(view)
.setOnEmojiPopupShownListener(new OnEmojiPopupShownListener() {
@Override @Override
public void onEmojiPopupShown() { public void onEmojiPopupShown() {
if (getResources() != null) { if (getResources() != null) {
@ -287,7 +296,8 @@ public class EntryMenuController extends BaseController {
PorterDuff.Mode.SRC_IN); PorterDuff.Mode.SRC_IN);
} }
} }
}).setOnEmojiPopupDismissListener(new OnEmojiPopupDismissListener() { })
.setOnEmojiPopupDismissListener(new OnEmojiPopupDismissListener() {
@Override @Override
public void onEmojiPopupDismiss() { public void onEmojiPopupDismiss() {
if (smileyButton != null) { if (smileyButton != null) {
@ -295,12 +305,14 @@ public class EntryMenuController extends BaseController {
PorterDuff.Mode.SRC_IN); PorterDuff.Mode.SRC_IN);
} }
} }
}).setOnEmojiClickListener(new OnEmojiClickListener() { })
.setOnEmojiClickListener(new OnEmojiClickListener() {
@Override @Override
public void onEmojiClick(@NonNull EmojiImageView emoji, @NonNull Emoji imageView) { public void onEmojiClick(@NonNull EmojiImageView emoji, @NonNull Emoji imageView) {
editText.getEditableText().append(" "); editText.getEditableText().append(" ");
} }
}).build(editText); })
.build(editText);
break; break;
case 4: case 4:
@ -322,7 +334,8 @@ public class EntryMenuController extends BaseController {
break; break;
} }
textInputLayout.setPasswordVisibilityToggleEnabled(operationCode == 99 || operationCode == 4 || operationCode == 6 || operationCode == 7); textInputLayout.setPasswordVisibilityToggleEnabled(
operationCode == 99 || operationCode == 4 || operationCode == 6 || operationCode == 7);
textInputLayout.setHint(labelText); textInputLayout.setHint(labelText);
textInputLayout.requestFocus(); textInputLayout.requestFocus();
} }

View File

@ -42,20 +42,20 @@ import butterknife.BindView;
import com.bluelinelabs.conductor.RouterTransaction; import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler; import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.bluelinelabs.logansquare.LoganSquare; import com.bluelinelabs.logansquare.LoganSquare;
import com.nextcloud.talk.models.RetrofitBucket;
import com.nextcloud.talk.models.json.capabilities.Capabilities;
import com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.models.json.conversations.RoomOverall;
import com.nextcloud.talk.models.json.generic.GenericOverall;
import com.nextcloud.talk.models.json.participants.AddParticipantOverall;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.activities.MagicCallActivity; import com.nextcloud.talk.activities.MagicCallActivity;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.controllers.base.BaseController; import com.nextcloud.talk.controllers.base.BaseController;
import com.nextcloud.talk.events.BottomSheetLockEvent; import com.nextcloud.talk.events.BottomSheetLockEvent;
import com.nextcloud.talk.models.RetrofitBucket;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.capabilities.Capabilities;
import com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.models.json.conversations.RoomOverall;
import com.nextcloud.talk.models.json.generic.GenericOverall;
import com.nextcloud.talk.models.json.participants.AddParticipantOverall;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.ConductorRemapping; import com.nextcloud.talk.utils.ConductorRemapping;
import com.nextcloud.talk.utils.DisplayUtils; import com.nextcloud.talk.utils.DisplayUtils;
@ -131,7 +131,8 @@ public class OperationsMenuController extends BaseController {
this.callUrl = args.getString(BundleKeys.INSTANCE.getKEY_CALL_URL(), ""); this.callUrl = args.getString(BundleKeys.INSTANCE.getKEY_CALL_URL(), "");
if (args.containsKey(BundleKeys.INSTANCE.getKEY_INVITED_PARTICIPANTS())) { if (args.containsKey(BundleKeys.INSTANCE.getKEY_INVITED_PARTICIPANTS())) {
this.invitedUsers = args.getStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_PARTICIPANTS()); this.invitedUsers =
args.getStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_PARTICIPANTS());
} }
if (args.containsKey(BundleKeys.INSTANCE.getKEY_INVITED_GROUP())) { if (args.containsKey(BundleKeys.INSTANCE.getKEY_INVITED_GROUP())) {
@ -139,15 +140,16 @@ public class OperationsMenuController extends BaseController {
} }
if (args.containsKey(BundleKeys.INSTANCE.getKEY_CONVERSATION_TYPE())) { if (args.containsKey(BundleKeys.INSTANCE.getKEY_CONVERSATION_TYPE())) {
this.conversationType = Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_CONVERSATION_TYPE())); this.conversationType =
Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_CONVERSATION_TYPE()));
} }
if (args.containsKey(BundleKeys.INSTANCE.getKEY_SERVER_CAPABILITIES())) { if (args.containsKey(BundleKeys.INSTANCE.getKEY_SERVER_CAPABILITIES())) {
this.serverCapabilities = Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_SERVER_CAPABILITIES())); this.serverCapabilities =
Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_SERVER_CAPABILITIES()));
} }
this.conversationName = args.getString(BundleKeys.INSTANCE.getKEY_CONVERSATION_NAME(), ""); this.conversationName = args.getString(BundleKeys.INSTANCE.getKEY_CONVERSATION_NAME(), "");
} }
@Override @Override
@ -158,7 +160,9 @@ public class OperationsMenuController extends BaseController {
@Override @Override
protected void onViewBound(@NonNull View view) { protected void onViewBound(@NonNull View view) {
super.onViewBound(view); super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
processOperation(); processOperation();
} }
@ -185,7 +189,8 @@ public class OperationsMenuController extends BaseController {
switch (operationCode) { switch (operationCode) {
case 2: case 2:
ncApi.renameRoom(credentials, ApiUtils.getRoom(currentUser.getBaseUrl(), conversation.getToken()), ncApi.renameRoom(credentials,
ApiUtils.getRoom(currentUser.getBaseUrl(), conversation.getToken()),
conversation.getName()) conversation.getName())
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
@ -193,7 +198,8 @@ public class OperationsMenuController extends BaseController {
.subscribe(operationsObserver); .subscribe(operationsObserver);
break; break;
case 3: case 3:
ncApi.makeRoomPublic(credentials, ApiUtils.getUrlForRoomVisibility(currentUser.getBaseUrl(), conversation ncApi.makeRoomPublic(credentials,
ApiUtils.getUrlForRoomVisibility(currentUser.getBaseUrl(), conversation
.getToken())) .getToken()))
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
@ -218,7 +224,8 @@ public class OperationsMenuController extends BaseController {
// Operation 7 is sharing, so we handle this differently // Operation 7 is sharing, so we handle this differently
break; break;
case 8: case 8:
ncApi.makeRoomPrivate(credentials, ApiUtils.getUrlForRoomVisibility(currentUser.getBaseUrl(), conversation ncApi.makeRoomPrivate(credentials,
ApiUtils.getUrlForRoomVisibility(currentUser.getBaseUrl(), conversation
.getToken())) .getToken()))
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
@ -306,7 +313,9 @@ public class OperationsMenuController extends BaseController {
@Override @Override
public void onNext(RoomOverall roomOverall) { public void onNext(RoomOverall roomOverall) {
conversation = roomOverall.getOcs().getData(); conversation = roomOverall.getOcs().getData();
if (conversationType.equals(Conversation.ConversationType.ROOM_PUBLIC_CALL) && isGroupCallWorkaroundFinal) { if (conversationType.equals(
Conversation.ConversationType.ROOM_PUBLIC_CALL)
&& isGroupCallWorkaroundFinal) {
performGroupCallWorkaround(credentials); performGroupCallWorkaround(credentials);
} else { } else {
inviteUsersToAConversation(); inviteUsersToAConversation();
@ -324,7 +333,6 @@ public class OperationsMenuController extends BaseController {
} }
}); });
} }
@Override @Override
@ -343,14 +351,16 @@ public class OperationsMenuController extends BaseController {
case 97: case 97:
case 98: case 98:
if (operationCode == 97) { if (operationCode == 97) {
ncApi.removeConversationFromFavorites(credentials, ApiUtils.getUrlForConversationFavorites(currentUser.getBaseUrl(), ncApi.removeConversationFromFavorites(credentials,
ApiUtils.getUrlForConversationFavorites(currentUser.getBaseUrl(),
conversation.getToken())) conversation.getToken()))
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.retry(1) .retry(1)
.subscribe(operationsObserver); .subscribe(operationsObserver);
} else { } else {
ncApi.addConversationToFavorites(credentials, ApiUtils.getUrlForConversationFavorites(currentUser.getBaseUrl(), ncApi.addConversationToFavorites(credentials,
ApiUtils.getUrlForConversationFavorites(currentUser.getBaseUrl(),
conversation.getToken())) conversation.getToken()))
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
@ -359,7 +369,8 @@ public class OperationsMenuController extends BaseController {
} }
break; break;
case 99: case 99:
ncApi.joinRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, conversationToken), ncApi.joinRoom(credentials,
ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, conversationToken),
callPassword) callPassword)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
@ -373,7 +384,8 @@ public class OperationsMenuController extends BaseController {
} }
private void performGroupCallWorkaround(String credentials) { private void performGroupCallWorkaround(String credentials) {
ncApi.makeRoomPrivate(credentials, ApiUtils.getUrlForRoomVisibility(currentUser.getBaseUrl(), conversation.getToken())) ncApi.makeRoomPrivate(credentials,
ApiUtils.getUrlForRoomVisibility(currentUser.getBaseUrl(), conversation.getToken()))
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.retry(1) .retry(1)
@ -399,8 +411,6 @@ public class OperationsMenuController extends BaseController {
dispose(); dispose();
} }
}); });
} }
private void showResultImage(boolean everythingOK, boolean isGuestSupportError) { private void showResultImage(boolean everythingOK, boolean isGuestSupportError) {
@ -440,7 +450,8 @@ public class OperationsMenuController extends BaseController {
} else { } else {
resultImageView.setImageDrawable(DisplayUtils.getTintedDrawable(getResources(), R.drawable resultImageView.setImageDrawable(DisplayUtils.getTintedDrawable(getResources(), R.drawable
.ic_cancel_black_24dp, R.color.nc_darkRed)); .ic_cancel_black_24dp, R.color.nc_darkRed));
okButton.setOnClickListener(v -> eventBus.post(new BottomSheetLockEvent(true, 0, operationCode != 99 okButton.setOnClickListener(
v -> eventBus.post(new BottomSheetLockEvent(true, 0, operationCode != 99
&& operationCode != 10, true))); && operationCode != 10, true)));
okButton.setVisibility(View.VISIBLE); okButton.setVisibility(View.VISIBLE);
} }
@ -528,11 +539,15 @@ public class OperationsMenuController extends BaseController {
localInvitedGroups.remove(0); localInvitedGroups.remove(0);
} }
if (localInvitedUsers.size() > 0 || (localInvitedGroups.size() > 0 && currentUser.hasSpreedFeatureCapability("invite-groups-and-mails"))) { if (localInvitedUsers.size() > 0 || (localInvitedGroups.size() > 0
if ((localInvitedGroups.size() > 0 && currentUser.hasSpreedFeatureCapability("invite-groups-and-mails"))) { && currentUser.hasSpreedFeatureCapability("invite-groups-and-mails"))) {
if ((localInvitedGroups.size() > 0 && currentUser.hasSpreedFeatureCapability(
"invite-groups-and-mails"))) {
for (int i = 0; i < localInvitedGroups.size(); i++) { for (int i = 0; i < localInvitedGroups.size(); i++) {
final String groupId = localInvitedGroups.get(i); final String groupId = localInvitedGroups.get(i);
retrofitBucket = ApiUtils.getRetrofitBucketForAddGroupParticipant(currentUser.getBaseUrl(), conversation.getToken(), retrofitBucket =
ApiUtils.getRetrofitBucketForAddGroupParticipant(currentUser.getBaseUrl(),
conversation.getToken(),
groupId); groupId);
ncApi.addParticipant(credentials, retrofitBucket.getUrl(), retrofitBucket.getQueryMap()) ncApi.addParticipant(credentials, retrofitBucket.getUrl(), retrofitBucket.getQueryMap())
@ -566,13 +581,13 @@ public class OperationsMenuController extends BaseController {
dispose(); dispose();
} }
}); });
} }
} }
for (int i = 0; i < localInvitedUsers.size(); i++) { for (int i = 0; i < localInvitedUsers.size(); i++) {
final String userId = invitedUsers.get(i); final String userId = invitedUsers.get(i);
retrofitBucket = ApiUtils.getRetrofitBucketForAddParticipant(currentUser.getBaseUrl(), conversation.getToken(), retrofitBucket = ApiUtils.getRetrofitBucketForAddParticipant(currentUser.getBaseUrl(),
conversation.getToken(),
userId); userId);
ncApi.addParticipant(credentials, retrofitBucket.getUrl(), retrofitBucket.getQueryMap()) ncApi.addParticipant(credentials, retrofitBucket.getUrl(), retrofitBucket.getQueryMap())
@ -623,12 +638,14 @@ public class OperationsMenuController extends BaseController {
if (baseUrl != null && !baseUrl.equals(currentUser.getBaseUrl())) { if (baseUrl != null && !baseUrl.equals(currentUser.getBaseUrl())) {
isGuestUser = true; isGuestUser = true;
hasChatCapability = capabilities != null && capabilities.getSpreedCapability() != null && capabilities.getSpreedCapability().getFeatures() != null && capabilities.getSpreedCapability().getFeatures().contains("chat-v2"); hasChatCapability = capabilities != null
&& capabilities.getSpreedCapability() != null
&& capabilities.getSpreedCapability().getFeatures() != null
&& capabilities.getSpreedCapability().getFeatures().contains("chat-v2");
} else { } else {
hasChatCapability = currentUser.hasSpreedFeatureCapability("chat-v2"); hasChatCapability = currentUser.hasSpreedFeatureCapability("chat-v2");
} }
if (hasChatCapability) { if (hasChatCapability) {
eventBus.post(new BottomSheetLockEvent(true, 0, eventBus.post(new BottomSheetLockEvent(true, 0,
true, true, dismissView)); true, true, dismissView));
@ -636,7 +653,8 @@ public class OperationsMenuController extends BaseController {
Intent conversationIntent = new Intent(getActivity(), MagicCallActivity.class); Intent conversationIntent = new Intent(getActivity(), MagicCallActivity.class);
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), conversation.getToken()); bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), conversation.getToken());
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), conversation.getRoomId()); bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), conversation.getRoomId());
bundle.putString(BundleKeys.INSTANCE.getKEY_CONVERSATION_NAME(), conversation.getDisplayName()); bundle.putString(BundleKeys.INSTANCE.getKEY_CONVERSATION_NAME(),
conversation.getDisplayName());
UserEntity conversationUser; UserEntity conversationUser;
if (isGuestUser) { if (isGuestUser) {
conversationUser = new UserEntity(); conversationUser = new UserEntity();
@ -652,13 +670,15 @@ public class OperationsMenuController extends BaseController {
} }
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), conversationUser); bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), conversationUser);
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(), Parcels.wrap(conversation)); bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(),
Parcels.wrap(conversation));
bundle.putString(BundleKeys.INSTANCE.getKEY_CONVERSATION_PASSWORD(), callPassword); bundle.putString(BundleKeys.INSTANCE.getKEY_CONVERSATION_PASSWORD(), callPassword);
conversationIntent.putExtras(bundle); conversationIntent.putExtras(bundle);
if (getParentController() != null) { if (getParentController() != null) {
ConductorRemapping.INSTANCE.remapChatController(getParentController().getRouter(), conversationUser.getId(), ConductorRemapping.INSTANCE.remapChatController(getParentController().getRouter(),
conversationUser.getId(),
conversation.getToken(), bundle, true); conversation.getToken(), bundle, true);
} }
} else { } else {
@ -666,7 +686,6 @@ public class OperationsMenuController extends BaseController {
} }
} }
private void initiateCall() { private void initiateCall() {
eventBus.post(new BottomSheetLockEvent(true, 0, true, true)); eventBus.post(new BottomSheetLockEvent(true, 0, true, true));
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -675,23 +694,24 @@ public class OperationsMenuController extends BaseController {
if (baseUrl != null && !baseUrl.equals(currentUser.getBaseUrl())) { if (baseUrl != null && !baseUrl.equals(currentUser.getBaseUrl())) {
bundle.putString(BundleKeys.INSTANCE.getKEY_MODIFIED_BASE_URL(), baseUrl); bundle.putString(BundleKeys.INSTANCE.getKEY_MODIFIED_BASE_URL(), baseUrl);
} }
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(), Parcels.wrap(conversation)); bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(),
Parcels.wrap(conversation));
if (getActivity() != null) { if (getActivity() != null) {
Intent callIntent = new Intent(getActivity(), MagicCallActivity.class); Intent callIntent = new Intent(getActivity(), MagicCallActivity.class);
callIntent.putExtras(bundle); callIntent.putExtras(bundle);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE); InputMethodManager imm =
(InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm != null) { if (imm != null) {
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
} }
new Handler().postDelayed(() -> getParentController().getRouter().popCurrentController(), 100); new Handler().postDelayed(() -> getParentController().getRouter().popCurrentController(),
100);
startActivity(callIntent); startActivity(callIntent);
} }
} }
private class OperationsObserver implements Observer { private class OperationsObserver implements Observer {
@ -720,7 +740,8 @@ public class OperationsMenuController extends BaseController {
if (((HttpException) e).response().code() == 403) { if (((HttpException) e).response().code() == 403) {
eventBus.post(new BottomSheetLockEvent(true, 0, false, eventBus.post(new BottomSheetLockEvent(true, 0, false,
false)); false));
ApplicationWideMessageHolder.getInstance().setMessageType(ApplicationWideMessageHolder.MessageType.CALL_PASSWORD_WRONG); ApplicationWideMessageHolder.getInstance()
.setMessageType(ApplicationWideMessageHolder.MessageType.CALL_PASSWORD_WRONG);
getRouter().popCurrentController(); getRouter().popCurrentController();
} else { } else {
showResultImage(false, false); showResultImage(false, false);

View File

@ -30,7 +30,8 @@ interface ListItemWithImage {
data class BasicListItemWithImage( data class BasicListItemWithImage(
@DrawableRes val iconRes: Int, @DrawableRes val iconRes: Int,
override val title: String) : ListItemWithImage { override val title: String
) : ListItemWithImage {
override fun populateIcon(imageView: ImageView) { override fun populateIcon(imageView: ImageView) {
imageView.setImageResource(iconRes) imageView.setImageResource(iconRes)

View File

@ -39,7 +39,8 @@ private const val KEY_ACTIVATED_INDEX = "activated_index"
internal class ListItemViewHolder( internal class ListItemViewHolder(
itemView: View, itemView: View,
private val adapter: ListIconDialogAdapter<*>) : RecyclerView.ViewHolder(itemView), View.OnClickListener { private val adapter: ListIconDialogAdapter<*>
) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
init { init {
itemView.setOnClickListener(this) itemView.setOnClickListener(this)
} }
@ -55,7 +56,8 @@ internal class ListIconDialogAdapter<IT : ListItemWithImage>(
private var items: List<IT>, private var items: List<IT>,
disabledItems: IntArray?, disabledItems: IntArray?,
private var waitForPositiveButton: Boolean, private var waitForPositiveButton: Boolean,
private var selection: ListItemListener<IT>) : RecyclerView.Adapter<ListItemViewHolder>(), DialogAdapter<IT, ListItemListener<IT>> { private var selection: ListItemListener<IT>
) : RecyclerView.Adapter<ListItemViewHolder>(), DialogAdapter<IT, ListItemListener<IT>> {
private var disabledIndices: IntArray = disabledItems ?: IntArray(0) private var disabledIndices: IntArray = disabledItems ?: IntArray(0)
@ -80,7 +82,8 @@ internal class ListIconDialogAdapter<IT : ListItemWithImage>(
override fun onCreateViewHolder( override fun onCreateViewHolder(
parent: ViewGroup, parent: ViewGroup,
viewType: Int): ListItemViewHolder { viewType: Int
): ListItemViewHolder {
val listItemView: View = parent.inflate(dialog.windowContext, R.layout.menu_item_sheet) val listItemView: View = parent.inflate(dialog.windowContext, R.layout.menu_item_sheet)
val viewHolder = ListItemViewHolder( val viewHolder = ListItemViewHolder(
itemView = listItemView, itemView = listItemView,
@ -94,7 +97,8 @@ internal class ListIconDialogAdapter<IT : ListItemWithImage>(
override fun onBindViewHolder( override fun onBindViewHolder(
holder: ListItemViewHolder, holder: ListItemViewHolder,
position: Int) { position: Int
) {
holder.itemView.isEnabled = !disabledIndices.contains(position) holder.itemView.isEnabled = !disabledIndices.contains(position)
val currentItem = items[position] val currentItem = items[position]
@ -120,7 +124,8 @@ internal class ListIconDialogAdapter<IT : ListItemWithImage>(
override fun replaceItems( override fun replaceItems(
items: List<IT>, items: List<IT>,
listener: ListItemListener<IT>) { listener: ListItemListener<IT>
) {
this.items = items this.items = items
if (listener != null) { if (listener != null) {
this.selection = listener this.selection = listener

View File

@ -34,7 +34,8 @@ typealias ListItemListener<IT> =
items: List<IT>, items: List<IT>,
disabledIndices: IntArray? = null, disabledIndices: IntArray? = null,
waitForPositiveButton: Boolean = true, waitForPositiveButton: Boolean = true,
selection: ListItemListener<IT> = null): MaterialDialog { selection: ListItemListener<IT> = null
): MaterialDialog {
if (getListAdapter() != null) { if (getListAdapter() != null) {
return updateListItemsWithImage( return updateListItemsWithImage(
@ -58,7 +59,8 @@ typealias ListItemListener<IT> =
fun MaterialDialog.updateListItemsWithImage( fun MaterialDialog.updateListItemsWithImage(
items: List<ListItemWithImage>, items: List<ListItemWithImage>,
disabledIndices: IntArray? = null): MaterialDialog { disabledIndices: IntArray? = null
): MaterialDialog {
val adapter = getListAdapter() val adapter = getListAdapter()
check(adapter != null) { check(adapter != null) {
"updateGridItems(...) can't be used before you've created a bottom sheet grid dialog." "updateGridItems(...) can't be used before you've created a bottom sheet grid dialog."

View File

@ -50,7 +50,8 @@ public class DatabaseModule {
@Provides @Provides
@Singleton @Singleton
public ReactiveEntityStore<Persistable> provideDataStore(@NonNull final SqlCipherDatabaseSource sqlCipherDatabaseSource) { public ReactiveEntityStore<Persistable> provideDataStore(
@NonNull final SqlCipherDatabaseSource sqlCipherDatabaseSource) {
final Configuration configuration = sqlCipherDatabaseSource.getConfiguration(); final Configuration configuration = sqlCipherDatabaseSource.getConfiguration();
return ReactiveSupport.toReactiveStore(new EntityDataStore<Persistable>(configuration)); return ReactiveSupport.toReactiveStore(new EntityDataStore<Persistable>(configuration));
} }

View File

@ -89,7 +89,8 @@ public class RestModule {
@Singleton @Singleton
@Provides @Provides
Proxy provideProxy(AppPreferences appPreferences) { Proxy provideProxy(AppPreferences appPreferences) {
if (!TextUtils.isEmpty(appPreferences.getProxyType()) && !"No proxy".equals(appPreferences.getProxyType()) if (!TextUtils.isEmpty(appPreferences.getProxyType()) && !"No proxy".equals(
appPreferences.getProxyType())
&& !TextUtils.isEmpty(appPreferences.getProxyHost())) { && !TextUtils.isEmpty(appPreferences.getProxyHost())) {
GetProxyRunnable getProxyRunnable = new GetProxyRunnable(appPreferences); GetProxyRunnable getProxyRunnable = new GetProxyRunnable(appPreferences);
Thread getProxyThread = new Thread(getProxyRunnable); Thread getProxyThread = new Thread(getProxyRunnable);
@ -131,7 +132,8 @@ public class RestModule {
try { try {
keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null); keyStore.load(null);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyManagerFactory kmf =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, null); kmf.init(keyStore, null);
X509KeyManager origKm = (X509KeyManager) kmf.getKeyManagers()[0]; X509KeyManager origKm = (X509KeyManager) kmf.getKeyManagers()[0];
return new MagicKeyManager(origKm, userUtils, appPreferences); return new MagicKeyManager(origKm, userUtils, appPreferences);
@ -169,7 +171,8 @@ public class RestModule {
@Provides @Provides
Cache provideCache() { Cache provideCache() {
int cacheSize = 128 * 1024 * 1024; // 128 MB int cacheSize = 128 * 1024 * 1024; // 128 MB
return new Cache(NextcloudTalkApplication.Companion.getSharedApplication().getCacheDir(), cacheSize); return new Cache(NextcloudTalkApplication.Companion.getSharedApplication().getCacheDir(),
cacheSize);
} }
@Singleton @Singleton

View File

@ -30,7 +30,8 @@ public class BottomSheetLockEvent {
private final boolean cancel; private final boolean cancel;
private boolean dismissView; private boolean dismissView;
public BottomSheetLockEvent(boolean cancelable, int delay, boolean shouldRefreshData, boolean cancel) { public BottomSheetLockEvent(boolean cancelable, int delay, boolean shouldRefreshData,
boolean cancel) {
this.cancelable = cancelable; this.cancelable = cancelable;
this.delay = delay; this.delay = delay;
this.shouldRefreshData = shouldRefreshData; this.shouldRefreshData = shouldRefreshData;
@ -38,7 +39,8 @@ public class BottomSheetLockEvent {
this.dismissView = true; this.dismissView = true;
} }
public BottomSheetLockEvent(boolean cancelable, int delay, boolean shouldRefreshData, boolean cancel, boolean public BottomSheetLockEvent(boolean cancelable, int delay, boolean shouldRefreshData,
boolean cancel, boolean
dismissView) { dismissView) {
this.cancelable = cancelable; this.cancelable = cancelable;
this.delay = delay; this.delay = delay;
@ -46,5 +48,4 @@ public class BottomSheetLockEvent {
this.cancel = cancel; this.cancel = cancel;
this.dismissView = dismissView; this.dismissView = dismissView;
} }
} }

View File

@ -37,5 +37,4 @@ public class EventStatus {
public enum EventType { public enum EventType {
PUSH_REGISTRATION, CAPABILITIES_FETCH, SIGNALING_SETTINGS, CONVERSATION_UPDATE, PARTICIPANTS_UPDATE PUSH_REGISTRATION, CAPABILITIES_FETCH, SIGNALING_SETTINGS, CONVERSATION_UPDATE, PARTICIPANTS_UPDATE
} }
} }

View File

@ -30,7 +30,8 @@ public class MediaStreamEvent {
private final String session; private final String session;
private final String videoStreamType; private final String videoStreamType;
public MediaStreamEvent(@Nullable MediaStream mediaStream, String session, String videoStreamType) { public MediaStreamEvent(@Nullable MediaStream mediaStream, String session,
String videoStreamType) {
this.mediaStream = mediaStream; this.mediaStream = mediaStream;
this.session = session; this.session = session;
this.videoStreamType = videoStreamType; this.videoStreamType = videoStreamType;

View File

@ -24,13 +24,13 @@ import lombok.Data;
@Data @Data
public class NetworkEvent { public class NetworkEvent {
public enum NetworkConnectionEvent {
NETWORK_CONNECTED, NETWORK_DISCONNECTED
}
private final NetworkConnectionEvent networkConnectionEvent; private final NetworkConnectionEvent networkConnectionEvent;
public NetworkEvent(NetworkConnectionEvent networkConnectionEvent) { public NetworkEvent(NetworkConnectionEvent networkConnectionEvent) {
this.networkConnectionEvent = networkConnectionEvent; this.networkConnectionEvent = networkConnectionEvent;
} }
public enum NetworkConnectionEvent {
NETWORK_CONNECTED, NETWORK_DISCONNECTED
}
} }

View File

@ -31,7 +31,8 @@ public class PeerConnectionEvent {
private final Boolean changeValue; private final Boolean changeValue;
private final String videoStreamType; private final String videoStreamType;
public PeerConnectionEvent(PeerConnectionEventType peerConnectionEventType, @Nullable String sessionId, public PeerConnectionEvent(PeerConnectionEventType peerConnectionEventType,
@Nullable String sessionId,
@Nullable String nick, Boolean changeValue, @Nullable String videoStreamType) { @Nullable String nick, Boolean changeValue, @Nullable String videoStreamType) {
this.peerConnectionEventType = peerConnectionEventType; this.peerConnectionEventType = peerConnectionEventType;
this.nick = nick; this.nick = nick;

View File

@ -35,7 +35,8 @@ public class SessionDescriptionSendEvent {
private final NCIceCandidate ncIceCandidate; private final NCIceCandidate ncIceCandidate;
private final String videoStreamType; private final String videoStreamType;
public SessionDescriptionSendEvent(@Nullable SessionDescription sessionDescription, String peerId, String type, public SessionDescriptionSendEvent(@Nullable SessionDescription sessionDescription, String peerId,
String type,
@Nullable NCIceCandidate ncIceCandidate, @Nullable String videoStreamType) { @Nullable NCIceCandidate ncIceCandidate, @Nullable String videoStreamType) {
this.sessionDescription = sessionDescription; this.sessionDescription = sessionDescription;
this.peerId = peerId; this.peerId = peerId;

View File

@ -23,5 +23,8 @@ package com.nextcloud.talk.interfaces
import android.os.Bundle import android.os.Bundle
interface ConversationMenuInterface { interface ConversationMenuInterface {
fun openLovelyDialogWithIdAndBundle(dialogId: Int, bundle: Bundle) fun openLovelyDialogWithIdAndBundle(
dialogId: Int,
bundle: Bundle
)
} }

View File

@ -30,12 +30,12 @@ import androidx.work.Worker;
import androidx.work.WorkerParameters; import androidx.work.WorkerParameters;
import autodagger.AutoInjector; import autodagger.AutoInjector;
import com.bluelinelabs.logansquare.LoganSquare; import com.bluelinelabs.logansquare.LoganSquare;
import com.nextcloud.talk.models.json.generic.GenericOverall;
import com.nextcloud.talk.models.json.push.PushConfigurationState;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.generic.GenericOverall;
import com.nextcloud.talk.models.json.push.PushConfigurationState;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.database.arbitrarystorage.ArbitraryStorageUtils; import com.nextcloud.talk.utils.database.arbitrarystorage.ArbitraryStorageUtils;
import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.database.user.UserUtils;
@ -77,7 +77,9 @@ public class AccountRemovalWorker extends Worker {
@NonNull @NonNull
@Override @Override
public Result doWork() { public Result doWork() {
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
PushConfigurationState pushConfigurationState; PushConfigurationState pushConfigurationState;
String credentials; String credentials;
@ -95,7 +97,8 @@ public class AccountRemovalWorker extends Worker {
JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class); JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class);
String finalCredentials = credentials; String finalCredentials = credentials;
ncApi.unregisterDeviceForNotificationsWithNextcloud(credentials, ApiUtils.getUrlNextcloudPush(userEntity ncApi.unregisterDeviceForNotificationsWithNextcloud(credentials,
ApiUtils.getUrlNextcloudPush(userEntity
.getBaseUrl())) .getBaseUrl()))
.blockingSubscribe(new Observer<GenericOverall>() { .blockingSubscribe(new Observer<GenericOverall>() {
@Override @Override
@ -108,7 +111,8 @@ public class AccountRemovalWorker extends Worker {
if (genericOverall.getOcs().getMeta().getStatusCode() == 200 if (genericOverall.getOcs().getMeta().getStatusCode() == 200
|| genericOverall.getOcs().getMeta().getStatusCode() == 202) { || genericOverall.getOcs().getMeta().getStatusCode() == 202) {
HashMap<String, String> queryMap = new HashMap<>(); HashMap<String, String> queryMap = new HashMap<>();
queryMap.put("deviceIdentifier", finalPushConfigurationState.getDeviceIdentifier()); queryMap.put("deviceIdentifier",
finalPushConfigurationState.getDeviceIdentifier());
queryMap.put("userPublicKey", finalPushConfigurationState.getUserPublicKey()); queryMap.put("userPublicKey", finalPushConfigurationState.getUserPublicKey());
queryMap.put("deviceIdentifierSignature", queryMap.put("deviceIdentifierSignature",
finalPushConfigurationState.getDeviceIdentifierSignature()); finalPushConfigurationState.getDeviceIdentifierSignature());
@ -125,9 +129,11 @@ public class AccountRemovalWorker extends Worker {
public void onNext(Void aVoid) { public void onNext(Void aVoid) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String groupName = String.format(getApplicationContext().getResources() String groupName =
String.format(getApplicationContext().getResources()
.getString(R.string .getString(R.string
.nc_notification_channel), userEntity.getUserId(), userEntity.getBaseUrl()); .nc_notification_channel), userEntity.getUserId(),
userEntity.getBaseUrl());
CRC32 crc32 = new CRC32(); CRC32 crc32 = new CRC32();
crc32.update(groupName.getBytes()); crc32.update(groupName.getBytes());
NotificationManager notificationManager = NotificationManager notificationManager =
@ -140,9 +146,11 @@ public class AccountRemovalWorker extends Worker {
} }
} }
WebSocketConnectionHelper.deleteExternalSignalingInstanceForUserEntity(userEntity.getId()); WebSocketConnectionHelper.deleteExternalSignalingInstanceForUserEntity(
userEntity.getId());
arbitraryStorageUtils.deleteAllEntriesForAccountIdentifier(userEntity.getId()).subscribe(new Observer() { arbitraryStorageUtils.deleteAllEntriesForAccountIdentifier(
userEntity.getId()).subscribe(new Observer() {
@Override @Override
public void onSubscribe(Disposable d) { public void onSubscribe(Disposable d) {
@ -150,7 +158,8 @@ public class AccountRemovalWorker extends Worker {
@Override @Override
public void onNext(Object o) { public void onNext(Object o) {
userUtils.deleteUser(userEntity.getId()).subscribe(new CompletableObserver() { userUtils.deleteUser(userEntity.getId())
.subscribe(new CompletableObserver() {
@Override @Override
public void onSubscribe(Disposable d) { public void onSubscribe(Disposable d) {

View File

@ -26,10 +26,10 @@ import androidx.work.Data;
import androidx.work.Worker; import androidx.work.Worker;
import androidx.work.WorkerParameters; import androidx.work.WorkerParameters;
import autodagger.AutoInjector; import autodagger.AutoInjector;
import com.nextcloud.talk.models.RetrofitBucket;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.events.EventStatus; import com.nextcloud.talk.events.EventStatus;
import com.nextcloud.talk.models.RetrofitBucket;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.bundle.BundleKeys; import com.nextcloud.talk.utils.bundle.BundleKeys;
@ -49,9 +49,12 @@ public class AddParticipantsToConversation extends Worker {
@Inject @Inject
EventBus eventBus; EventBus eventBus;
public AddParticipantsToConversation(@NonNull Context context, @NonNull WorkerParameters workerParams) { public AddParticipantsToConversation(@NonNull Context context,
@NonNull WorkerParameters workerParams) {
super(context, workerParams); super(context, workerParams);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
} }
@NonNull @NonNull
@ -60,13 +63,15 @@ public class AddParticipantsToConversation extends Worker {
Data data = getInputData(); Data data = getInputData();
String[] selectedUserIds = data.getStringArray(BundleKeys.INSTANCE.getKEY_SELECTED_USERS()); String[] selectedUserIds = data.getStringArray(BundleKeys.INSTANCE.getKEY_SELECTED_USERS());
String[] selectedGroupIds = data.getStringArray(BundleKeys.INSTANCE.getKEY_SELECTED_GROUPS()); String[] selectedGroupIds = data.getStringArray(BundleKeys.INSTANCE.getKEY_SELECTED_GROUPS());
UserEntity user = userUtils.getUserWithInternalId(data.getLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), -1)); UserEntity user = userUtils.getUserWithInternalId(
data.getLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), -1));
String conversationToken = data.getString(BundleKeys.INSTANCE.getKEY_TOKEN()); String conversationToken = data.getString(BundleKeys.INSTANCE.getKEY_TOKEN());
String credentials = ApiUtils.getCredentials(user.getUsername(), user.getToken()); String credentials = ApiUtils.getCredentials(user.getUsername(), user.getToken());
RetrofitBucket retrofitBucket; RetrofitBucket retrofitBucket;
for (String userId : selectedUserIds) { for (String userId : selectedUserIds) {
retrofitBucket = ApiUtils.getRetrofitBucketForAddParticipant(user.getBaseUrl(), conversationToken, retrofitBucket =
ApiUtils.getRetrofitBucketForAddParticipant(user.getBaseUrl(), conversationToken,
userId); userId);
ncApi.addParticipant(credentials, retrofitBucket.getUrl(), retrofitBucket.getQueryMap()) ncApi.addParticipant(credentials, retrofitBucket.getUrl(), retrofitBucket.getQueryMap())
@ -75,7 +80,8 @@ public class AddParticipantsToConversation extends Worker {
} }
for (String groupId : selectedGroupIds) { for (String groupId : selectedGroupIds) {
retrofitBucket = ApiUtils.getRetrofitBucketForAddGroupParticipant(user.getBaseUrl(), conversationToken, retrofitBucket =
ApiUtils.getRetrofitBucketForAddGroupParticipant(user.getBaseUrl(), conversationToken,
groupId); groupId);
ncApi.addParticipant(credentials, retrofitBucket.getUrl(), retrofitBucket.getQueryMap()) ncApi.addParticipant(credentials, retrofitBucket.getUrl(), retrofitBucket.getQueryMap())

View File

@ -28,11 +28,11 @@ import androidx.work.Worker;
import androidx.work.WorkerParameters; import androidx.work.WorkerParameters;
import autodagger.AutoInjector; import autodagger.AutoInjector;
import com.bluelinelabs.logansquare.LoganSquare; import com.bluelinelabs.logansquare.LoganSquare;
import com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.events.EventStatus; import com.nextcloud.talk.events.EventStatus;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.bundle.BundleKeys; import com.nextcloud.talk.utils.bundle.BundleKeys;
import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.database.user.UserUtils;
@ -68,7 +68,6 @@ public class CapabilitiesWorker extends Worker {
public CapabilitiesWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) { public CapabilitiesWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams); super(context, workerParams);
} }
private void updateUser(CapabilitiesOverall capabilitiesOverall, UserEntity internalUserEntity) { private void updateUser(CapabilitiesOverall capabilitiesOverall, UserEntity internalUserEntity) {
@ -76,7 +75,8 @@ public class CapabilitiesWorker extends Worker {
userUtils.createOrUpdateUser(null, null, userUtils.createOrUpdateUser(null, null,
null, null, null, null,
null, null, null, internalUserEntity.getId(), null, null, null, internalUserEntity.getId(),
LoganSquare.serialize(capabilitiesOverall.getOcs().getData().getCapabilities()), null, null) LoganSquare.serialize(capabilitiesOverall.getOcs().getData().getCapabilities()), null,
null)
.blockingSubscribe(new Observer<UserEntity>() { .blockingSubscribe(new Observer<UserEntity>() {
@Override @Override
public void onSubscribe(Disposable d) { public void onSubscribe(Disposable d) {
@ -103,13 +103,14 @@ public class CapabilitiesWorker extends Worker {
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, "Failed to create or update user"); Log.e(TAG, "Failed to create or update user");
} }
} }
@NonNull @NonNull
@Override @Override
public Result doWork() { public Result doWork() {
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
Data data = getInputData(); Data data = getInputData();
@ -118,7 +119,8 @@ public class CapabilitiesWorker extends Worker {
UserEntity userEntity; UserEntity userEntity;
List userEntityObjectList = new ArrayList(); List userEntityObjectList = new ArrayList();
if (internalUserId == -1 || (userEntity = userUtils.getUserWithInternalId(internalUserId)) == null) { if (internalUserId == -1
|| (userEntity = userUtils.getUserWithInternalId(internalUserId)) == null) {
userEntityObjectList = userUtils.getUsers(); userEntityObjectList = userUtils.getUsers();
} else { } else {
userEntityObjectList.add(userEntity); userEntityObjectList.add(userEntity);
@ -131,7 +133,8 @@ public class CapabilitiesWorker extends Worker {
JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class); JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class);
ncApi.getCapabilities(ApiUtils.getCredentials(internalUserEntity.getUsername(), ncApi.getCapabilities(ApiUtils.getCredentials(internalUserEntity.getUsername(),
internalUserEntity.getToken()), ApiUtils.getUrlForCapabilities(internalUserEntity.getBaseUrl())) internalUserEntity.getToken()),
ApiUtils.getUrlForCapabilities(internalUserEntity.getBaseUrl()))
.retry(3) .retry(3)
.blockingSubscribe(new Observer<CapabilitiesOverall>() { .blockingSubscribe(new Observer<CapabilitiesOverall>() {
@Override @Override
@ -148,7 +151,6 @@ public class CapabilitiesWorker extends Worker {
public void onError(Throwable e) { public void onError(Throwable e) {
eventBus.post(new EventStatus(internalUserEntity.getId(), eventBus.post(new EventStatus(internalUserEntity.getId(),
EventStatus.EventType.CAPABILITIES_FETCH, false)); EventStatus.EventType.CAPABILITIES_FETCH, false));
} }
@Override @Override

View File

@ -26,11 +26,11 @@ import androidx.work.Data;
import androidx.work.Worker; import androidx.work.Worker;
import androidx.work.WorkerParameters; import androidx.work.WorkerParameters;
import autodagger.AutoInjector; import autodagger.AutoInjector;
import com.nextcloud.talk.models.json.generic.GenericOverall;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.events.EventStatus; import com.nextcloud.talk.events.EventStatus;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.generic.GenericOverall;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.bundle.BundleKeys; import com.nextcloud.talk.utils.bundle.BundleKeys;
import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.database.user.UserUtils;
@ -60,9 +60,12 @@ public class DeleteConversationWorker extends Worker {
NcApi ncApi; NcApi ncApi;
public DeleteConversationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) { public DeleteConversationWorker(@NonNull Context context,
@NonNull WorkerParameters workerParams) {
super(context, workerParams); super(context, workerParams);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
} }
@NonNull @NonNull
@ -74,7 +77,8 @@ public class DeleteConversationWorker extends Worker {
UserEntity operationUser = userUtils.getUserWithId(operationUserId); UserEntity operationUser = userUtils.getUserWithId(operationUserId);
if (operationUser != null) { if (operationUser != null) {
String credentials = ApiUtils.getCredentials(operationUser.getUsername(), operationUser.getToken()); String credentials =
ApiUtils.getCredentials(operationUser.getUsername(), operationUser.getToken());
ncApi = retrofit.newBuilder().client(okHttpClient.newBuilder().cookieJar(new ncApi = retrofit.newBuilder().client(okHttpClient.newBuilder().cookieJar(new
JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class); JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class);
@ -89,13 +93,11 @@ public class DeleteConversationWorker extends Worker {
@Override @Override
public void onSubscribe(Disposable d) { public void onSubscribe(Disposable d) {
disposable = d; disposable = d;
} }
@Override @Override
public void onNext(GenericOverall genericOverall) { public void onNext(GenericOverall genericOverall) {
eventBus.postSticky(eventStatus); eventBus.postSticky(eventStatus);
} }
@Override @Override

View File

@ -26,11 +26,11 @@ import androidx.work.Data;
import androidx.work.Worker; import androidx.work.Worker;
import androidx.work.WorkerParameters; import androidx.work.WorkerParameters;
import autodagger.AutoInjector; import autodagger.AutoInjector;
import com.nextcloud.talk.models.json.generic.GenericOverall;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.events.EventStatus; import com.nextcloud.talk.events.EventStatus;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.generic.GenericOverall;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.bundle.BundleKeys; import com.nextcloud.talk.utils.bundle.BundleKeys;
import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.database.user.UserUtils;
@ -62,7 +62,9 @@ public class LeaveConversationWorker extends Worker {
public LeaveConversationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) { public LeaveConversationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams); super(context, workerParams);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
} }
@NonNull @NonNull
@ -74,14 +76,16 @@ public class LeaveConversationWorker extends Worker {
UserEntity operationUser = userUtils.getUserWithId(operationUserId); UserEntity operationUser = userUtils.getUserWithId(operationUserId);
if (operationUser != null) { if (operationUser != null) {
String credentials = ApiUtils.getCredentials(operationUser.getUsername(), operationUser.getToken()); String credentials =
ApiUtils.getCredentials(operationUser.getUsername(), operationUser.getToken());
ncApi = retrofit.newBuilder().client(okHttpClient.newBuilder().cookieJar(new ncApi = retrofit.newBuilder().client(okHttpClient.newBuilder().cookieJar(new
JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class); JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class);
EventStatus eventStatus = new EventStatus(operationUser.getId(), EventStatus eventStatus = new EventStatus(operationUser.getId(),
EventStatus.EventType.CONVERSATION_UPDATE, true); EventStatus.EventType.CONVERSATION_UPDATE, true);
ncApi.removeSelfFromRoom(credentials, ApiUtils.getUrlForRemoveSelfFromRoom(operationUser.getBaseUrl(), conversationToken)) ncApi.removeSelfFromRoom(credentials,
ApiUtils.getUrlForRemoveSelfFromRoom(operationUser.getBaseUrl(), conversationToken))
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.blockingSubscribe(new Observer<GenericOverall>() { .blockingSubscribe(new Observer<GenericOverall>() {
Disposable disposable; Disposable disposable;
@ -89,13 +93,11 @@ public class LeaveConversationWorker extends Worker {
@Override @Override
public void onSubscribe(Disposable d) { public void onSubscribe(Disposable d) {
disposable = d; disposable = d;
} }
@Override @Override
public void onNext(GenericOverall genericOverall) { public void onNext(GenericOverall genericOverall) {
eventBus.postSticky(eventStatus); eventBus.postSticky(eventStatus);
} }
@Override @Override

View File

@ -55,7 +55,9 @@ public class ShareOperationWorker extends Worker {
public ShareOperationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) { public ShareOperationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams); super(context, workerParams);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
Data data = workerParams.getInputData(); Data data = workerParams.getInputData();
userId = data.getLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), 0); userId = data.getLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), 0);
roomToken = data.getString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN()); roomToken = data.getString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN());
@ -65,7 +67,6 @@ public class ShareOperationWorker extends Worker {
baseUrl = operationsUser.getBaseUrl(); baseUrl = operationsUser.getBaseUrl();
} }
@NonNull @NonNull
@Override @Override
public Result doWork() { public Result doWork() {

View File

@ -30,12 +30,12 @@ import androidx.work.Worker;
import androidx.work.WorkerParameters; import androidx.work.WorkerParameters;
import autodagger.AutoInjector; import autodagger.AutoInjector;
import com.bluelinelabs.logansquare.LoganSquare; import com.bluelinelabs.logansquare.LoganSquare;
import com.nextcloud.talk.models.ExternalSignalingServer;
import com.nextcloud.talk.models.json.signaling.settings.SignalingSettingsOverall;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.events.EventStatus; import com.nextcloud.talk.events.EventStatus;
import com.nextcloud.talk.models.ExternalSignalingServer;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.signaling.settings.SignalingSettingsOverall;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.bundle.BundleKeys; import com.nextcloud.talk.utils.bundle.BundleKeys;
import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.database.user.UserUtils;
@ -67,7 +67,9 @@ public class SignalingSettingsWorker extends Worker {
@NonNull @NonNull
@Override @Override
public Result doWork() { public Result doWork() {
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
Data data = getInputData(); Data data = getInputData();
@ -75,7 +77,8 @@ public class SignalingSettingsWorker extends Worker {
List<UserEntity> userEntityList = new ArrayList<>(); List<UserEntity> userEntityList = new ArrayList<>();
UserEntity userEntity; UserEntity userEntity;
if (internalUserId == -1 || (userEntity = userUtils.getUserWithInternalId(internalUserId)) == null) { if (internalUserId == -1
|| (userEntity = userUtils.getUserWithInternalId(internalUserId)) == null) {
userEntityList = userUtils.getUsers(); userEntityList = userUtils.getUsers();
} else { } else {
userEntityList.add(userEntity); userEntityList.add(userEntity);
@ -84,7 +87,8 @@ public class SignalingSettingsWorker extends Worker {
for (int i = 0; i < userEntityList.size(); i++) { for (int i = 0; i < userEntityList.size(); i++) {
userEntity = userEntityList.get(i); userEntity = userEntityList.get(i);
UserEntity finalUserEntity = userEntity; UserEntity finalUserEntity = userEntity;
ncApi.getSignalingSettings(ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()), ncApi.getSignalingSettings(
ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()),
ApiUtils.getUrlForSignalingSettings(userEntity.getBaseUrl())) ApiUtils.getUrlForSignalingSettings(userEntity.getBaseUrl()))
.blockingSubscribe(new Observer<SignalingSettingsOverall>() { .blockingSubscribe(new Observer<SignalingSettingsOverall>() {
@Override @Override
@ -96,12 +100,15 @@ public class SignalingSettingsWorker extends Worker {
public void onNext(SignalingSettingsOverall signalingSettingsOverall) { public void onNext(SignalingSettingsOverall signalingSettingsOverall) {
ExternalSignalingServer externalSignalingServer; ExternalSignalingServer externalSignalingServer;
externalSignalingServer = new ExternalSignalingServer(); externalSignalingServer = new ExternalSignalingServer();
externalSignalingServer.setExternalSignalingServer(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer()); externalSignalingServer.setExternalSignalingServer(
externalSignalingServer.setExternalSignalingTicket(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket()); signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer());
externalSignalingServer.setExternalSignalingTicket(
signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket());
try { try {
userUtils.createOrUpdateUser(null, null, null, null, null, userUtils.createOrUpdateUser(null, null, null, null, null,
null, null, finalUserEntity.getId(), null, null, LoganSquare.serialize(externalSignalingServer)) null, null, finalUserEntity.getId(), null, null,
LoganSquare.serialize(externalSignalingServer))
.subscribe(new Observer<UserEntity>() { .subscribe(new Observer<UserEntity>() {
@Override @Override
public void onSubscribe(Disposable d) { public void onSubscribe(Disposable d) {
@ -110,12 +117,14 @@ public class SignalingSettingsWorker extends Worker {
@Override @Override
public void onNext(UserEntity userEntity) { public void onNext(UserEntity userEntity) {
eventBus.post(new EventStatus(finalUserEntity.getId(), EventStatus.EventType.SIGNALING_SETTINGS, true)); eventBus.post(new EventStatus(finalUserEntity.getId(),
EventStatus.EventType.SIGNALING_SETTINGS, true));
} }
@Override @Override
public void onError(Throwable e) { public void onError(Throwable e) {
eventBus.post(new EventStatus(finalUserEntity.getId(), EventStatus.EventType.SIGNALING_SETTINGS, false)); eventBus.post(new EventStatus(finalUserEntity.getId(),
EventStatus.EventType.SIGNALING_SETTINGS, false));
} }
@Override @Override
@ -130,7 +139,9 @@ public class SignalingSettingsWorker extends Worker {
@Override @Override
public void onError(Throwable e) { public void onError(Throwable e) {
eventBus.post(new EventStatus(finalUserEntity.getId(), EventStatus.EventType.SIGNALING_SETTINGS, false)); eventBus.post(
new EventStatus(finalUserEntity.getId(), EventStatus.EventType.SIGNALING_SETTINGS,
false));
} }
@Override @Override
@ -140,7 +151,8 @@ public class SignalingSettingsWorker extends Worker {
}); });
} }
OneTimeWorkRequest websocketConnectionsWorker = new OneTimeWorkRequest.Builder(WebsocketConnectionsWorker.class).build(); OneTimeWorkRequest websocketConnectionsWorker =
new OneTimeWorkRequest.Builder(WebsocketConnectionsWorker.class).build();
WorkManager.getInstance().enqueue(websocketConnectionsWorker); WorkManager.getInstance().enqueue(websocketConnectionsWorker);
return Result.success(); return Result.success();

View File

@ -29,8 +29,8 @@ import androidx.work.Worker;
import androidx.work.WorkerParameters; import androidx.work.WorkerParameters;
import autodagger.AutoInjector; import autodagger.AutoInjector;
import com.bluelinelabs.logansquare.LoganSquare; import com.bluelinelabs.logansquare.LoganSquare;
import com.nextcloud.talk.models.ExternalSignalingServer;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.models.ExternalSignalingServer;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.database.user.UserUtils;
import com.nextcloud.talk.webrtc.WebSocketConnectionHelper; import com.nextcloud.talk.webrtc.WebSocketConnectionHelper;
@ -46,7 +46,8 @@ public class WebsocketConnectionsWorker extends Worker {
@Inject @Inject
UserUtils userUtils; UserUtils userUtils;
public WebsocketConnectionsWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) { public WebsocketConnectionsWorker(@NonNull Context context,
@NonNull WorkerParameters workerParams) {
super(context, workerParams); super(context, workerParams);
} }
@ -54,7 +55,9 @@ public class WebsocketConnectionsWorker extends Worker {
@NonNull @NonNull
@Override @Override
public Result doWork() { public Result doWork() {
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
List<UserEntity> userEntityList = userUtils.getUsers(); List<UserEntity> userEntityList = userUtils.getUsers();
UserEntity userEntity; UserEntity userEntity;
@ -64,7 +67,8 @@ public class WebsocketConnectionsWorker extends Worker {
userEntity = userEntityList.get(i); userEntity = userEntityList.get(i);
if (!TextUtils.isEmpty(userEntity.getExternalSignalingServer())) { if (!TextUtils.isEmpty(userEntity.getExternalSignalingServer())) {
try { try {
externalSignalingServer = LoganSquare.parse(userEntity.getExternalSignalingServer(), ExternalSignalingServer.class); externalSignalingServer = LoganSquare.parse(userEntity.getExternalSignalingServer(),
ExternalSignalingServer.class);
if (!TextUtils.isEmpty(externalSignalingServer.getExternalSignalingServer()) && if (!TextUtils.isEmpty(externalSignalingServer.getExternalSignalingServer()) &&
!TextUtils.isEmpty(externalSignalingServer.getExternalSignalingTicket())) { !TextUtils.isEmpty(externalSignalingServer.getExternalSignalingTicket())) {
WebSocketConnectionHelper.getExternalSignalingInstanceForServer( WebSocketConnectionHelper.getExternalSignalingInstanceForServer(

View File

@ -20,7 +20,6 @@
package com.nextcloud.talk.models; package com.nextcloud.talk.models;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import lombok.Data; import lombok.Data;
import org.parceler.Parcel; import org.parceler.Parcel;

View File

@ -65,7 +65,8 @@ public interface User extends Parcelable, Persistable, Serializable {
if (getCapabilities() != null) { if (getCapabilities() != null) {
try { try {
Capabilities capabilities = LoganSquare.parse(getCapabilities(), Capabilities.class); Capabilities capabilities = LoganSquare.parse(getCapabilities(), Capabilities.class);
if (capabilities.getNotificationsCapability() != null && capabilities.getNotificationsCapability().getFeatures() != null) { if (capabilities.getNotificationsCapability() != null
&& capabilities.getNotificationsCapability().getFeatures() != null) {
return capabilities.getSpreedCapability().getFeatures().contains(capabilityName); return capabilities.getSpreedCapability().getFeatures().contains(capabilityName);
} }
} catch (IOException e) { } catch (IOException e) {
@ -79,7 +80,8 @@ public interface User extends Parcelable, Persistable, Serializable {
if (getCapabilities() != null) { if (getCapabilities() != null) {
try { try {
Capabilities capabilities = LoganSquare.parse(getCapabilities(), Capabilities.class); Capabilities capabilities = LoganSquare.parse(getCapabilities(), Capabilities.class);
if (capabilities.getExternalCapability() != null && capabilities.getExternalCapability().containsKey("v1")) { if (capabilities.getExternalCapability() != null && capabilities.getExternalCapability()
.containsKey("v1")) {
return capabilities.getExternalCapability().get("v1").contains("capabilityName"); return capabilities.getExternalCapability().get("v1").contains("capabilityName");
} }
} catch (IOException e) { } catch (IOException e) {
@ -109,9 +111,12 @@ public interface User extends Parcelable, Persistable, Serializable {
Capabilities capabilities = null; Capabilities capabilities = null;
try { try {
capabilities = LoganSquare.parse(getCapabilities(), Capabilities.class); capabilities = LoganSquare.parse(getCapabilities(), Capabilities.class);
if (capabilities != null && capabilities.getSpreedCapability() != null && capabilities.getSpreedCapability().getConfig() != null if (capabilities != null
&& capabilities.getSpreedCapability() != null
&& capabilities.getSpreedCapability().getConfig() != null
&& capabilities.getSpreedCapability().getConfig().containsKey("chat")) { && capabilities.getSpreedCapability().getConfig().containsKey("chat")) {
HashMap<String, String> chatConfigHashMap = capabilities.getSpreedCapability().getConfig().get("chat"); HashMap<String, String> chatConfigHashMap =
capabilities.getSpreedCapability().getConfig().get("chat");
if (chatConfigHashMap != null && chatConfigHashMap.containsKey("max-length")) { if (chatConfigHashMap != null && chatConfigHashMap.containsKey("max-length")) {
int chatSize = Integer.parseInt(chatConfigHashMap.get("max-length")); int chatSize = Integer.parseInt(chatConfigHashMap.get("max-length"));
if (chatSize > 0) { if (chatSize > 0) {

View File

@ -55,9 +55,6 @@ public class ChatMessage implements IMessage, MessageContentType, MessageContent
public Map<String, String> selectedIndividualHashMap; public Map<String, String> selectedIndividualHashMap;
@JsonIgnore @JsonIgnore
public boolean isLinkPreviewAllowed; public boolean isLinkPreviewAllowed;
List<MessageType> messageTypesToIgnore = Arrays.asList(MessageType.REGULAR_TEXT_MESSAGE,
MessageType.SYSTEM_MESSAGE, MessageType.SINGLE_LINK_VIDEO_MESSAGE,
MessageType.SINGLE_LINK_AUDIO_MESSAGE, MessageType.SINGLE_LINK_MESSAGE);
@JsonField(name = "id") @JsonField(name = "id")
public int jsonMessageId; public int jsonMessageId;
@JsonField(name = "token") @JsonField(name = "token")
@ -79,6 +76,9 @@ public class ChatMessage implements IMessage, MessageContentType, MessageContent
public HashMap<String, HashMap<String, String>> messageParameters; public HashMap<String, HashMap<String, String>> messageParameters;
@JsonField(name = "systemMessage", typeConverter = EnumSystemMessageTypeConverter.class) @JsonField(name = "systemMessage", typeConverter = EnumSystemMessageTypeConverter.class)
public SystemMessageType systemMessageType; public SystemMessageType systemMessageType;
List<MessageType> messageTypesToIgnore = Arrays.asList(MessageType.REGULAR_TEXT_MESSAGE,
MessageType.SYSTEM_MESSAGE, MessageType.SINGLE_LINK_VIDEO_MESSAGE,
MessageType.SINGLE_LINK_AUDIO_MESSAGE, MessageType.SINGLE_LINK_MESSAGE);
private boolean hasFileAttachment() { private boolean hasFileAttachment() {
if (messageParameters != null && messageParameters.size() > 0) { if (messageParameters != null && messageParameters.size() > 0) {
@ -102,7 +102,9 @@ public class ChatMessage implements IMessage, MessageContentType, MessageContent
if (individualHashMap.get("type").equals("file")) { if (individualHashMap.get("type").equals("file")) {
selectedIndividualHashMap = individualHashMap; selectedIndividualHashMap = individualHashMap;
return (ApiUtils.getUrlForFilePreviewWithFileId(getActiveUser().getBaseUrl(), return (ApiUtils.getUrlForFilePreviewWithFileId(getActiveUser().getBaseUrl(),
individualHashMap.get("id"), NextcloudTalkApplication.Companion.getSharedApplication().getResources().getDimensionPixelSize(R.dimen.maximum_file_preview_size))); individualHashMap.get("id"), NextcloudTalkApplication.Companion.getSharedApplication()
.getResources()
.getDimensionPixelSize(R.dimen.maximum_file_preview_size)));
} }
} }
} }
@ -145,52 +147,83 @@ public class ChatMessage implements IMessage, MessageContentType, MessageContent
} }
public String getLastMessageDisplayText() { public String getLastMessageDisplayText() {
if (getMessageType().equals(MessageType.REGULAR_TEXT_MESSAGE) || getMessageType().equals(MessageType.SYSTEM_MESSAGE)) { if (getMessageType().equals(MessageType.REGULAR_TEXT_MESSAGE) || getMessageType().equals(
MessageType.SYSTEM_MESSAGE)) {
return getText(); return getText();
} else { } else {
if (getMessageType().equals(MessageType.SINGLE_LINK_GIPHY_MESSAGE) if (getMessageType().equals(MessageType.SINGLE_LINK_GIPHY_MESSAGE)
|| getMessageType().equals(MessageType.SINGLE_LINK_TENOR_MESSAGE) || getMessageType().equals(MessageType.SINGLE_LINK_TENOR_MESSAGE)
|| getMessageType().equals(MessageType.SINGLE_LINK_GIF_MESSAGE)) { || getMessageType().equals(MessageType.SINGLE_LINK_GIF_MESSAGE)) {
if (getActorId().equals(getActiveUser().getUserId())) { if (getActorId().equals(getActiveUser().getUserId())) {
return (NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_sent_a_gif_you)); return (NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_sent_a_gif_you));
} else { } else {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_a_gif), return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest))); .getResources()
.getString(R.string.nc_sent_a_gif),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName()
: NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_guest)));
} }
} else if (getMessageType().equals(MessageType.SINGLE_NC_ATTACHMENT_MESSAGE)) { } else if (getMessageType().equals(MessageType.SINGLE_NC_ATTACHMENT_MESSAGE)) {
if (getActorId().equals(getActiveUser().getUserId())) { if (getActorId().equals(getActiveUser().getUserId())) {
return (NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_sent_an_attachment_you)); return (NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_sent_an_attachment_you));
} else { } else {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_an_attachment), return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest))); .getResources()
.getString(R.string.nc_sent_an_attachment),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName()
: NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_guest)));
} }
} else if (getMessageType().equals(MessageType.SINGLE_LINK_MESSAGE)) { } else if (getMessageType().equals(MessageType.SINGLE_LINK_MESSAGE)) {
if (getActorId().equals(getActiveUser().getUserId())) { if (getActorId().equals(getActiveUser().getUserId())) {
return (NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_sent_a_link_you)); return (NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_sent_a_link_you));
} else { } else {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_a_link), return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest))); .getResources()
.getString(R.string.nc_sent_a_link),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName()
: NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_guest)));
} }
} else if (getMessageType().equals(MessageType.SINGLE_LINK_AUDIO_MESSAGE)) { } else if (getMessageType().equals(MessageType.SINGLE_LINK_AUDIO_MESSAGE)) {
if (getActorId().equals(getActiveUser().getUserId())) { if (getActorId().equals(getActiveUser().getUserId())) {
return (NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_sent_an_audio_you)); return (NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_sent_an_audio_you));
} else { } else {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_an_audio), return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest))); .getResources()
.getString(R.string.nc_sent_an_audio),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName()
: NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_guest)));
} }
} else if (getMessageType().equals(MessageType.SINGLE_LINK_VIDEO_MESSAGE)) { } else if (getMessageType().equals(MessageType.SINGLE_LINK_VIDEO_MESSAGE)) {
if (getActorId().equals(getActiveUser().getUserId())) { if (getActorId().equals(getActiveUser().getUserId())) {
return (NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_sent_a_video_you)); return (NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_sent_a_video_you));
} else { } else {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_a_video), return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest))); .getResources()
.getString(R.string.nc_sent_a_video),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName()
: NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_guest)));
} }
} else if (getMessageType().equals(MessageType.SINGLE_LINK_IMAGE_MESSAGE)) { } else if (getMessageType().equals(MessageType.SINGLE_LINK_IMAGE_MESSAGE)) {
if (getActorId().equals(getActiveUser().getUserId())) { if (getActorId().equals(getActiveUser().getUserId())) {
return (NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_sent_an_image_you)); return (NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_sent_an_image_you));
} else { } else {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_an_image), return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest))); .getResources()
.getString(R.string.nc_sent_an_image),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName()
: NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_guest)));
} }
} }
} }
@ -214,15 +247,18 @@ public class ChatMessage implements IMessage, MessageContentType, MessageContent
@Override @Override
public String getAvatar() { public String getAvatar() {
if (getActorType().equals("users")) { if (getActorType().equals("users")) {
return ApiUtils.getUrlForAvatarWithName(getActiveUser().getBaseUrl(), actorId, R.dimen.avatar_size); return ApiUtils.getUrlForAvatarWithName(getActiveUser().getBaseUrl(), actorId,
R.dimen.avatar_size);
} else if (getActorType().equals("guests")) { } else if (getActorType().equals("guests")) {
String apiId = String apiId =
NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest); NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_guest);
if (!TextUtils.isEmpty(getActorDisplayName())) { if (!TextUtils.isEmpty(getActorDisplayName())) {
apiId = getActorDisplayName(); apiId = getActorDisplayName();
} }
return ApiUtils.getUrlForAvatarWithNameForGuests(getActiveUser().getBaseUrl(), apiId, R.dimen.avatar_size); return ApiUtils.getUrlForAvatarWithNameForGuests(getActiveUser().getBaseUrl(), apiId,
R.dimen.avatar_size);
} else { } else {
return null; return null;
} }

View File

@ -24,11 +24,13 @@ import java.util.HashMap;
public class ChatUtils { public class ChatUtils {
public static String getParsedMessage(String message, HashMap<String, HashMap<String, String>> messageParameters) { public static String getParsedMessage(String message,
HashMap<String, HashMap<String, String>> messageParameters) {
if (messageParameters != null && messageParameters.size() > 0) { if (messageParameters != null && messageParameters.size() > 0) {
for (String key : messageParameters.keySet()) { for (String key : messageParameters.keySet()) {
HashMap<String, String> individualHashMap = messageParameters.get(key); HashMap<String, String> individualHashMap = messageParameters.get(key);
if (individualHashMap.get("type").equals("user") || individualHashMap.get("type").equals("guest") || individualHashMap.get("type").equals("call")) { if (individualHashMap.get("type").equals("user") || individualHashMap.get("type")
.equals("guest") || individualHashMap.get("type").equals("call")) {
message = message.replaceAll("\\{" + key + "\\}", "@" + message = message.replaceAll("\\{" + key + "\\}", "@" +
messageParameters.get(key).get("name")); messageParameters.get(key).get("name"));
} else if (individualHashMap.get("type").equals("file")) { } else if (individualHashMap.get("type").equals("file")) {
@ -37,7 +39,6 @@ public class ChatUtils {
} }
} }
return message; return message;
} }
} }

View File

@ -100,30 +100,35 @@ public class Conversation {
Participant.ParticipantType.USER_FOLLOWING_LINK.equals(participantType)); Participant.ParticipantType.USER_FOLLOWING_LINK.equals(participantType));
} }
private boolean isLockedOneToOne(UserEntity conversationUser) { private boolean isLockedOneToOne(UserEntity conversationUser) {
return (getType() == ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL && conversationUser.hasSpreedFeatureCapability("locked-one-to-one-rooms")); return (getType() == ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL
&& conversationUser.hasSpreedFeatureCapability("locked-one-to-one-rooms"));
} }
public boolean canModerate(UserEntity conversationUser) { public boolean canModerate(UserEntity conversationUser) {
return ((Participant.ParticipantType.OWNER.equals(participantType) return ((Participant.ParticipantType.OWNER.equals(participantType)
|| Participant.ParticipantType.MODERATOR.equals(participantType)) && !isLockedOneToOne(conversationUser)); || Participant.ParticipantType.MODERATOR.equals(participantType)) && !isLockedOneToOne(
conversationUser));
} }
public boolean shouldShowLobby(UserEntity conversationUser) { public boolean shouldShowLobby(UserEntity conversationUser) {
return LobbyState.LOBBY_STATE_MODERATORS_ONLY.equals(getLobbyState()) && !canModerate(conversationUser); return LobbyState.LOBBY_STATE_MODERATORS_ONLY.equals(getLobbyState()) && !canModerate(
conversationUser);
} }
public boolean isLobbyViewApplicable(UserEntity conversationUser) { public boolean isLobbyViewApplicable(UserEntity conversationUser) {
return !canModerate(conversationUser) && (getType() == ConversationType.ROOM_GROUP_CALL || getType() == ConversationType.ROOM_PUBLIC_CALL); return !canModerate(conversationUser) && (getType() == ConversationType.ROOM_GROUP_CALL
|| getType() == ConversationType.ROOM_PUBLIC_CALL);
} }
public boolean isNameEditable(UserEntity conversationUser) { public boolean isNameEditable(UserEntity conversationUser) {
return (canModerate(conversationUser) && !ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL.equals(type)); return (canModerate(conversationUser) && !ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL.equals(
type));
} }
public boolean canLeave(UserEntity conversationUser) { public boolean canLeave(UserEntity conversationUser) {
return !canModerate(conversationUser) || (getType() != ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL && getParticipants().size() > 1); return !canModerate(conversationUser) || (getType()
!= ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL && getParticipants().size() > 1);
} }
public String getDeleteWarningMessage() { public String getDeleteWarningMessage() {
@ -163,5 +168,4 @@ public class Conversation {
ROOM_PUBLIC_CALL, ROOM_PUBLIC_CALL,
ROOM_SYSTEM ROOM_SYSTEM
} }
} }

View File

@ -23,7 +23,8 @@ package com.nextcloud.talk.models.json.converters;
import com.bluelinelabs.logansquare.typeconverters.IntBasedTypeConverter; import com.bluelinelabs.logansquare.typeconverters.IntBasedTypeConverter;
import com.nextcloud.talk.models.json.conversations.Conversation; import com.nextcloud.talk.models.json.conversations.Conversation;
public class EnumNotificationLevelConverter extends IntBasedTypeConverter<Conversation.NotificationLevel> { public class EnumNotificationLevelConverter
extends IntBasedTypeConverter<Conversation.NotificationLevel> {
@Override @Override
public Conversation.NotificationLevel getFromInt(int i) { public Conversation.NotificationLevel getFromInt(int i) {
switch (i) { switch (i) {
@ -55,5 +56,4 @@ public class EnumNotificationLevelConverter extends IntBasedTypeConverter<Conver
return 0; return 0;
} }
} }
} }

View File

@ -23,7 +23,8 @@ package com.nextcloud.talk.models.json.converters;
import com.bluelinelabs.logansquare.typeconverters.IntBasedTypeConverter; import com.bluelinelabs.logansquare.typeconverters.IntBasedTypeConverter;
import com.nextcloud.talk.models.json.participants.Participant; import com.nextcloud.talk.models.json.participants.Participant;
public class EnumParticipantTypeConverter extends IntBasedTypeConverter<Participant.ParticipantType> { public class EnumParticipantTypeConverter
extends IntBasedTypeConverter<Participant.ParticipantType> {
@Override @Override
public Participant.ParticipantType getFromInt(int i) { public Participant.ParticipantType getFromInt(int i) {
switch (i) { switch (i) {
@ -40,7 +41,6 @@ public class EnumParticipantTypeConverter extends IntBasedTypeConverter<Particip
default: default:
return Participant.ParticipantType.DUMMY; return Participant.ParticipantType.DUMMY;
} }
} }
@Override @Override

View File

@ -23,7 +23,8 @@ package com.nextcloud.talk.models.json.converters;
import com.bluelinelabs.logansquare.typeconverters.IntBasedTypeConverter; import com.bluelinelabs.logansquare.typeconverters.IntBasedTypeConverter;
import com.nextcloud.talk.models.json.conversations.Conversation; import com.nextcloud.talk.models.json.conversations.Conversation;
public class EnumReadOnlyConversationConverter extends IntBasedTypeConverter<Conversation.ConversationReadOnlyState> { public class EnumReadOnlyConversationConverter
extends IntBasedTypeConverter<Conversation.ConversationReadOnlyState> {
@Override @Override
public Conversation.ConversationReadOnlyState getFromInt(int i) { public Conversation.ConversationReadOnlyState getFromInt(int i) {
switch (i) { switch (i) {
@ -47,5 +48,4 @@ public class EnumReadOnlyConversationConverter extends IntBasedTypeConverter<Con
return 0; return 0;
} }
} }
} }

View File

@ -43,7 +43,8 @@ public class LoganSquareJodaTimeConverter implements TypeConverter<DateTime> {
} }
@Override @Override
public void serialize(DateTime object, String fieldName, boolean writeFieldNameForObject, JsonGenerator jsonGenerator) throws IOException { public void serialize(DateTime object, String fieldName, boolean writeFieldNameForObject,
JsonGenerator jsonGenerator) throws IOException {
if (fieldName != null) { if (fieldName != null) {
jsonGenerator.writeStringField(fieldName, object != null ? object.toString() : null); jsonGenerator.writeStringField(fieldName, object != null ? object.toString() : null);
} else { } else {

View File

@ -35,7 +35,9 @@ public class Participant {
@JsonField(name = "userId") @JsonField(name = "userId")
public String userId; public String userId;
@JsonField(name = {"type", "participantType"}, typeConverter = EnumParticipantTypeConverter.class) @JsonField(name = {
"type", "participantType"
}, typeConverter = EnumParticipantTypeConverter.class)
public ParticipantType type; public ParticipantType type;
@JsonField(name = "name") @JsonField(name = "name")
@ -60,7 +62,6 @@ public class Participant {
public boolean selected; public boolean selected;
public ParticipantFlags getParticipantFlags() { public ParticipantFlags getParticipantFlags() {
ParticipantFlags participantFlags = ParticipantFlags.NOT_IN_CALL; ParticipantFlags participantFlags = ParticipantFlags.NOT_IN_CALL;
if (inCall != null) { if (inCall != null) {
@ -119,6 +120,5 @@ public class Participant {
public long getValue() { public long getValue() {
return value; return value;
} }
} }
} }

View File

@ -20,7 +20,6 @@
package com.nextcloud.talk.models.json.push; package com.nextcloud.talk.models.json.push;
import com.bluelinelabs.logansquare.annotation.JsonField; import com.bluelinelabs.logansquare.annotation.JsonField;
import com.bluelinelabs.logansquare.annotation.JsonObject; import com.bluelinelabs.logansquare.annotation.JsonObject;
import lombok.Data; import lombok.Data;

View File

@ -35,5 +35,4 @@ public class SharesData {
@JsonField(name = "exact") @JsonField(name = "exact")
ExactSharees exactUsers; ExactSharees exactUsers;
} }

View File

@ -39,7 +39,8 @@ public class HelloResponseWebSocketMessage {
ServerHelloResponseFeaturesWebSocketMessage serverHelloResponseFeaturesWebSocketMessage; ServerHelloResponseFeaturesWebSocketMessage serverHelloResponseFeaturesWebSocketMessage;
public boolean serverHasMCUSupport() { public boolean serverHasMCUSupport() {
return serverHelloResponseFeaturesWebSocketMessage != null && serverHelloResponseFeaturesWebSocketMessage.getFeatures() != null return serverHelloResponseFeaturesWebSocketMessage != null
&& serverHelloResponseFeaturesWebSocketMessage.getFeatures() != null
&& serverHelloResponseFeaturesWebSocketMessage.getFeatures().contains("mcu"); && serverHelloResponseFeaturesWebSocketMessage.getFeatures().contains("mcu");
} }
} }

View File

@ -21,7 +21,6 @@
package com.nextcloud.talk.newarch.features.conversationsList package com.nextcloud.talk.newarch.features.conversationsList
import android.app.Application import android.app.Application
import android.content.res.Resources
import android.graphics.Bitmap import android.graphics.Bitmap
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory

View File

@ -25,12 +25,12 @@ import android.view.View;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import autodagger.AutoInjector; import autodagger.AutoInjector;
import com.nextcloud.talk.models.json.mention.Mention;
import com.nextcloud.talk.models.json.mention.MentionOverall;
import com.nextcloud.talk.adapters.items.MentionAutocompleteItem; import com.nextcloud.talk.adapters.items.MentionAutocompleteItem;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.mention.Mention;
import com.nextcloud.talk.models.json.mention.MentionOverall;
import com.nextcloud.talk.utils.ApiUtils; import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.database.user.UserUtils;
import com.otaliastudios.autocomplete.RecyclerViewPresenter; import com.otaliastudios.autocomplete.RecyclerViewPresenter;
@ -45,7 +45,8 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
@AutoInjector(NextcloudTalkApplication.class) @AutoInjector(NextcloudTalkApplication.class)
public class MentionAutocompletePresenter extends RecyclerViewPresenter<Mention> implements FlexibleAdapter.OnItemClickListener { public class MentionAutocompletePresenter extends RecyclerViewPresenter<Mention>
implements FlexibleAdapter.OnItemClickListener {
@Inject @Inject
NcApi ncApi; NcApi ncApi;
@Inject @Inject
@ -61,7 +62,9 @@ public class MentionAutocompletePresenter extends RecyclerViewPresenter<Mention>
public MentionAutocompletePresenter(Context context) { public MentionAutocompletePresenter(Context context) {
super(context); super(context);
this.context = context; this.context = context;
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
currentUser = userUtils.getCurrentUser(); currentUser = userUtils.getCurrentUser();
} }
@ -69,7 +72,9 @@ public class MentionAutocompletePresenter extends RecyclerViewPresenter<Mention>
super(context); super(context);
this.roomToken = roomToken; this.roomToken = roomToken;
this.context = context; this.context = context;
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
currentUser = userUtils.getCurrentUser(); currentUser = userUtils.getCurrentUser();
} }
@ -91,7 +96,8 @@ public class MentionAutocompletePresenter extends RecyclerViewPresenter<Mention>
} }
adapter.setFilter(queryString); adapter.setFilter(queryString);
ncApi.getMentionAutocompleteSuggestions(ApiUtils.getCredentials(currentUser.getUsername(), currentUser ncApi.getMentionAutocompleteSuggestions(
ApiUtils.getCredentials(currentUser.getUsername(), currentUser
.getToken()), ApiUtils.getUrlForMentionSuggestions(currentUser.getBaseUrl(), roomToken), .getToken()), ApiUtils.getUrlForMentionSuggestions(currentUser.getBaseUrl(), roomToken),
queryString, 5) queryString, 5)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
@ -137,11 +143,11 @@ public class MentionAutocompletePresenter extends RecyclerViewPresenter<Mention>
}); });
} }
@Override @Override
public boolean onItemClick(View view, int position) { public boolean onItemClick(View view, int position) {
Mention mention = new Mention(); Mention mention = new Mention();
MentionAutocompleteItem mentionAutocompleteItem = (MentionAutocompleteItem) adapter.getItem(position); MentionAutocompleteItem mentionAutocompleteItem =
(MentionAutocompleteItem) adapter.getItem(position);
if (mentionAutocompleteItem != null) { if (mentionAutocompleteItem != null) {
mention.setId(mentionAutocompleteItem.getObjectId()); mention.setId(mentionAutocompleteItem.getObjectId());
mention.setLabel(mentionAutocompleteItem.getDisplayName()); mention.setLabel(mentionAutocompleteItem.getDisplayName());

View File

@ -43,16 +43,22 @@ class PackageReplacedReceiver : BroadcastReceiver() {
@Inject @Inject
lateinit var appPreferences: AppPreferences lateinit var appPreferences: AppPreferences
override fun onReceive(context: Context, intent: Intent?) { override fun onReceive(
context: Context,
intent: Intent?
) {
NextcloudTalkApplication.sharedApplication!!.componentApplication.inject(this) NextcloudTalkApplication.sharedApplication!!.componentApplication.inject(this)
if (intent != null && intent.action != null && if (intent != null && intent.action != null &&
intent.action == "android.intent.action.MY_PACKAGE_REPLACED") { intent.action == "android.intent.action.MY_PACKAGE_REPLACED"
) {
try { try {
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0) val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
if (packageInfo.versionCode > 43 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (packageInfo.versionCode > 43 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = context.getSystemService(Context val notificationManager = context.getSystemService(
.NOTIFICATION_SERVICE) as NotificationManager Context
.NOTIFICATION_SERVICE
) as NotificationManager
if (notificationManager != null) { if (notificationManager != null) {
if (!appPreferences.isNotificationChannelUpgradedToV2) { if (!appPreferences.isNotificationChannelUpgradedToV2) {
@ -61,15 +67,23 @@ class PackageReplacedReceiver : BroadcastReceiver() {
notificationManager.deleteNotificationChannelGroup(notificationChannelGroup.id) notificationManager.deleteNotificationChannelGroup(notificationChannelGroup.id)
} }
notificationManager.deleteNotificationChannel(NotificationUtils.NOTIFICATION_CHANNEL_CALLS) notificationManager.deleteNotificationChannel(
notificationManager.deleteNotificationChannel(NotificationUtils.NOTIFICATION_CHANNEL_MESSAGES) NotificationUtils.NOTIFICATION_CHANNEL_CALLS
)
notificationManager.deleteNotificationChannel(
NotificationUtils.NOTIFICATION_CHANNEL_MESSAGES
)
appPreferences.setNotificationChannelIsUpgradedToV2(true) appPreferences.setNotificationChannelIsUpgradedToV2(true)
} }
if (!appPreferences.isNotificationChannelUpgradedToV3 && packageInfo.versionCode > 51) { if (!appPreferences.isNotificationChannelUpgradedToV3 && packageInfo.versionCode > 51) {
notificationManager.deleteNotificationChannel(NotificationUtils.NOTIFICATION_CHANNEL_MESSAGES_V2) notificationManager.deleteNotificationChannel(
notificationManager.deleteNotificationChannel(NotificationUtils.NOTIFICATION_CHANNEL_CALLS_V2) NotificationUtils.NOTIFICATION_CHANNEL_MESSAGES_V2
)
notificationManager.deleteNotificationChannel(
NotificationUtils.NOTIFICATION_CHANNEL_CALLS_V2
)
appPreferences.setNotificationChannelIsUpgradedToV3(true) appPreferences.setNotificationChannelIsUpgradedToV3(true)
} }
} }

View File

@ -28,9 +28,9 @@ import android.accounts.AccountManager
import android.content.Context import android.content.Context
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.util.Log import android.util.Log
import com.nextcloud.talk.models.ImportAccount
import com.nextcloud.talk.R import com.nextcloud.talk.R
import com.nextcloud.talk.application.NextcloudTalkApplication import com.nextcloud.talk.application.NextcloudTalkApplication
import com.nextcloud.talk.models.ImportAccount
import com.nextcloud.talk.models.database.UserEntity import com.nextcloud.talk.models.database.UserEntity
import java.util.ArrayList import java.util.ArrayList
import java.util.Arrays import java.util.Arrays
@ -55,7 +55,10 @@ object AccountUtils {
internalUserEntity = userEntitiesList[i] internalUserEntity = userEntitiesList[i]
importAccount = getInformationFromAccount(account) importAccount = getInformationFromAccount(account)
if (importAccount.token != null) { if (importAccount.token != null) {
if (importAccount.baseUrl.startsWith("http://") || importAccount.baseUrl.startsWith("https://")) { if (importAccount.baseUrl.startsWith("http://") || importAccount.baseUrl.startsWith(
"https://"
)
) {
if (internalUserEntity.username == importAccount.username && internalUserEntity.baseUrl == importAccount.baseUrl) { if (internalUserEntity.username == importAccount.username && internalUserEntity.baseUrl == importAccount.baseUrl) {
accountFound = true accountFound = true
break break
@ -64,7 +67,8 @@ object AccountUtils {
if (internalUserEntity.username == importAccount.username && (internalUserEntity if (internalUserEntity.username == importAccount.username && (internalUserEntity
.baseUrl == "http://" + importAccount.baseUrl || .baseUrl == "http://" + importAccount.baseUrl ||
internalUserEntity.baseUrl == "https://" + importAccount internalUserEntity.baseUrl == "https://" + importAccount
.baseUrl)) { .baseUrl)
) {
accountFound = true accountFound = true
break break
} }
@ -89,8 +93,12 @@ object AccountUtils {
val packageManager = context.packageManager val packageManager = context.packageManager
var appName = "" var appName = ""
try { try {
appName = packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, appName = packageManager.getApplicationLabel(
PackageManager.GET_META_DATA)) as String packageManager.getApplicationInfo(
packageName,
PackageManager.GET_META_DATA
)
) as String
} catch (e: PackageManager.NameNotFoundException) { } catch (e: PackageManager.NameNotFoundException) {
Log.e(TAG, "Failed to get app name based on package") Log.e(TAG, "Failed to get app name based on package")
} }
@ -98,17 +106,25 @@ object AccountUtils {
return appName return appName
} }
fun canWeOpenFilesApp(context: Context, accountName: String): Boolean { fun canWeOpenFilesApp(
context: Context,
accountName: String
): Boolean {
val pm = context.packageManager val pm = context.packageManager
try { try {
val packageInfo = pm.getPackageInfo(context.getString(R.string.nc_import_accounts_from), 0) val packageInfo = pm.getPackageInfo(context.getString(R.string.nc_import_accounts_from), 0)
if (packageInfo.versionCode >= 30060151) { if (packageInfo.versionCode >= 30060151) {
val ownSignatures = pm.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES).signatures val ownSignatures = pm.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES)
val filesAppSignatures = pm.getPackageInfo(context.getString(R.string.nc_import_accounts_from), PackageManager.GET_SIGNATURES).signatures .signatures
val filesAppSignatures = pm.getPackageInfo(
context.getString(R.string.nc_import_accounts_from), PackageManager.GET_SIGNATURES
)
.signatures
if (Arrays.equals(ownSignatures, filesAppSignatures)) { if (Arrays.equals(ownSignatures, filesAppSignatures)) {
val accMgr = AccountManager.get(context) val accMgr = AccountManager.get(context)
val accounts = accMgr.getAccountsByType(context.getString(R.string.nc_import_account_type)) val accounts =
accMgr.getAccountsByType(context.getString(R.string.nc_import_account_type))
for (account in accounts) { for (account in accounts) {
if (account.name == accountName) { if (account.name == accountName) {
return true return true

View File

@ -22,10 +22,10 @@ package com.nextcloud.talk.utils;
import android.net.Uri; import android.net.Uri;
import android.text.TextUtils; import android.text.TextUtils;
import androidx.annotation.DimenRes; import androidx.annotation.DimenRes;
import com.nextcloud.talk.models.RetrofitBucket;
import com.nextcloud.talk.BuildConfig; import com.nextcloud.talk.BuildConfig;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.models.RetrofitBucket;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -45,7 +45,8 @@ public class ApiUtils {
return getRoom(baseUrl, token) + "/webinary/lobby"; return getRoom(baseUrl, token) + "/webinary/lobby";
} }
public static String getUrlForRemovingParticipantFromConversation(String baseUrl, String roomToken, boolean isGuest) { public static String getUrlForRemovingParticipantFromConversation(String baseUrl,
String roomToken, boolean isGuest) {
String url = getUrlForParticipants(baseUrl, roomToken); String url = getUrlForParticipants(baseUrl, roomToken);
if (isGuest) { if (isGuest) {
@ -55,7 +56,8 @@ public class ApiUtils {
return url; return url;
} }
public static RetrofitBucket getRetrofitBucketForContactsSearch(String baseUrl, @Nullable String searchQuery) { public static RetrofitBucket getRetrofitBucketForContactsSearch(String baseUrl,
@Nullable String searchQuery) {
RetrofitBucket retrofitBucket = new RetrofitBucket(); RetrofitBucket retrofitBucket = new RetrofitBucket();
retrofitBucket.setUrl(baseUrl + ocsApiVersion + "/apps/files_sharing/api/v1/sharees"); retrofitBucket.setUrl(baseUrl + ocsApiVersion + "/apps/files_sharing/api/v1/sharees");
@ -73,7 +75,8 @@ public class ApiUtils {
return retrofitBucket; return retrofitBucket;
} }
public static String getUrlForFilePreviewWithRemotePath(String baseUrl, String remotePath, int px) { public static String getUrlForFilePreviewWithRemotePath(String baseUrl, String remotePath,
int px) {
return baseUrl + "/index.php/core/preview.png?file=" return baseUrl + "/index.php/core/preview.png?file="
+ Uri.encode(remotePath, "UTF-8") + Uri.encode(remotePath, "UTF-8")
+ "&x=" + px + "&y=" + px + "&a=1&mode=cover&forceIcon=1"; + "&x=" + px + "&y=" + px + "&a=1&mode=cover&forceIcon=1";
@ -88,7 +91,8 @@ public class ApiUtils {
return baseUrl + ocsApiVersion + "/apps/files_sharing/api/v1/shares"; return baseUrl + ocsApiVersion + "/apps/files_sharing/api/v1/shares";
} }
public static RetrofitBucket getRetrofitBucketForContactsSearchFor14(String baseUrl, @Nullable String searchQuery) { public static RetrofitBucket getRetrofitBucketForContactsSearchFor14(String baseUrl,
@Nullable String searchQuery) {
RetrofitBucket retrofitBucket = getRetrofitBucketForContactsSearch(baseUrl, searchQuery); RetrofitBucket retrofitBucket = getRetrofitBucketForContactsSearch(baseUrl, searchQuery);
retrofitBucket.setUrl(baseUrl + ocsApiVersion + "/core/autocomplete/get"); retrofitBucket.setUrl(baseUrl + ocsApiVersion + "/core/autocomplete/get");
@ -98,7 +102,6 @@ public class ApiUtils {
return retrofitBucket; return retrofitBucket;
} }
public static String getUrlForSettingNotificationlevel(String baseUrl, String token) { public static String getUrlForSettingNotificationlevel(String baseUrl, String token) {
return getRoom(baseUrl, token) + "/notify"; return getRoom(baseUrl, token) + "/notify";
} }
@ -107,7 +110,6 @@ public class ApiUtils {
return getRoom(baseUrl, token) + "/participants/active"; return getRoom(baseUrl, token) + "/participants/active";
} }
public static String getUrlForParticipants(String baseUrl, String token) { public static String getUrlForParticipants(String baseUrl, String token) {
return getRoom(baseUrl, token) + "/participants"; return getRoom(baseUrl, token) + "/participants";
} }
@ -145,9 +147,11 @@ public class ApiUtils {
return retrofitBucket; return retrofitBucket;
} }
public static RetrofitBucket getRetrofitBucketForAddParticipant(String baseUrl, String token, String user) { public static RetrofitBucket getRetrofitBucketForAddParticipant(String baseUrl, String token,
String user) {
RetrofitBucket retrofitBucket = new RetrofitBucket(); RetrofitBucket retrofitBucket = new RetrofitBucket();
retrofitBucket.setUrl(baseUrl + ocsApiVersion + spreedApiVersion + "/room/" + token + "/participants"); retrofitBucket.setUrl(
baseUrl + ocsApiVersion + spreedApiVersion + "/room/" + token + "/participants");
Map<String, String> queryMap = new HashMap<>(); Map<String, String> queryMap = new HashMap<>();
@ -156,16 +160,17 @@ public class ApiUtils {
retrofitBucket.setQueryMap(queryMap); retrofitBucket.setQueryMap(queryMap);
return retrofitBucket; return retrofitBucket;
} }
public static RetrofitBucket getRetrofitBucketForAddGroupParticipant(String baseUrl, String token, String group) { public static RetrofitBucket getRetrofitBucketForAddGroupParticipant(String baseUrl, String token,
String group) {
RetrofitBucket retrofitBucket = getRetrofitBucketForAddParticipant(baseUrl, token, group); RetrofitBucket retrofitBucket = getRetrofitBucketForAddParticipant(baseUrl, token, group);
retrofitBucket.getQueryMap().put("source", "groups"); retrofitBucket.getQueryMap().put("source", "groups");
return retrofitBucket; return retrofitBucket;
} }
public static RetrofitBucket getRetrofitBucketForAddMailParticipant(String baseUrl, String token, String mail) { public static RetrofitBucket getRetrofitBucketForAddMailParticipant(String baseUrl, String token,
String mail) {
RetrofitBucket retrofitBucket = getRetrofitBucketForAddParticipant(baseUrl, token, mail); RetrofitBucket retrofitBucket = getRetrofitBucketForAddParticipant(baseUrl, token, mail);
retrofitBucket.getQueryMap().put("source", "emails"); retrofitBucket.getQueryMap().put("source", "emails");
return retrofitBucket; return retrofitBucket;
@ -181,7 +186,6 @@ public class ApiUtils {
public static String getUrlForCall(String baseUrl, String token) { public static String getUrlForCall(String baseUrl, String token) {
return baseUrl + ocsApiVersion + spreedApiVersion + "/call/" + token; return baseUrl + ocsApiVersion + spreedApiVersion + "/call/" + token;
} }
public static String getUrlForCallPing(String baseUrl, String token) { public static String getUrlForCallPing(String baseUrl, String token) {
@ -217,7 +221,6 @@ public class ApiUtils {
return getUrlForSignaling(baseUrl, null) + "/settings"; return getUrlForSignaling(baseUrl, null) + "/settings";
} }
public static String getUrlForUserProfile(String baseUrl) { public static String getUrlForUserProfile(String baseUrl) {
return baseUrl + ocsApiVersion + "/cloud/user"; return baseUrl + ocsApiVersion + "/cloud/user";
} }
@ -226,11 +229,13 @@ public class ApiUtils {
return "/status.php"; return "/status.php";
} }
public static String getUrlForAvatarWithNameAndPixels(String baseUrl, String name, int avatarSize) { public static String getUrlForAvatarWithNameAndPixels(String baseUrl, String name,
int avatarSize) {
return baseUrl + "/index.php/avatar/" + Uri.encode(name) + "/" + avatarSize; return baseUrl + "/index.php/avatar/" + Uri.encode(name) + "/" + avatarSize;
} }
public static String getUrlForAvatarWithName(String baseUrl, String name, @DimenRes int avatarSize) { public static String getUrlForAvatarWithName(String baseUrl, String name,
@DimenRes int avatarSize) {
avatarSize = Math.round(NextcloudTalkApplication avatarSize = Math.round(NextcloudTalkApplication
.Companion.getSharedApplication().getResources().getDimension(avatarSize)); .Companion.getSharedApplication().getResources().getDimension(avatarSize));

View File

@ -31,8 +31,10 @@ object DateUtils {
val tz = cal.timeZone val tz = cal.timeZone
/* date formatter in local timezone */ /* date formatter in local timezone */
val format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, Locale val format = DateFormat.getDateTimeInstance(
.getDefault()) DateFormat.DEFAULT, DateFormat.SHORT, Locale
.getDefault()
)
format.timeZone = tz format.timeZone = tz
return format.format(Date(timestamp)) return format.format(Date(timestamp))

View File

@ -34,15 +34,20 @@ public class DeviceUtils {
private static final String TAG = "DeviceUtils"; private static final String TAG = "DeviceUtils";
public static void ignoreSpecialBatteryFeatures() { public static void ignoreSpecialBatteryFeatures() {
if (Build.MANUFACTURER.equalsIgnoreCase("xiaomi") || Build.MANUFACTURER.equalsIgnoreCase("meizu")) { if (Build.MANUFACTURER.equalsIgnoreCase("xiaomi") || Build.MANUFACTURER.equalsIgnoreCase(
"meizu")) {
try { try {
@SuppressLint("PrivateApi") Class<?> appOpsUtilsClass = Class.forName("android.miui.AppOpsUtils"); @SuppressLint("PrivateApi") Class<?> appOpsUtilsClass =
Class.forName("android.miui.AppOpsUtils");
if (appOpsUtilsClass != null) { if (appOpsUtilsClass != null) {
Method setApplicationAutoStartMethod = appOpsUtilsClass.getMethod("setApplicationAutoStart", Context Method setApplicationAutoStartMethod =
appOpsUtilsClass.getMethod("setApplicationAutoStart", Context
.class, String.class, Boolean.TYPE); .class, String.class, Boolean.TYPE);
if (setApplicationAutoStartMethod != null) { if (setApplicationAutoStartMethod != null) {
Context applicationContext = NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext(); Context applicationContext =
setApplicationAutoStartMethod.invoke(appOpsUtilsClass, applicationContext, applicationContext NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext();
setApplicationAutoStartMethod.invoke(appOpsUtilsClass, applicationContext,
applicationContext
.getPackageName(), Boolean.TRUE); .getPackageName(), Boolean.TRUE);
} }
} }
@ -57,17 +62,20 @@ public class DeviceUtils {
} }
} else if (Build.MANUFACTURER.equalsIgnoreCase("huawei")) { } else if (Build.MANUFACTURER.equalsIgnoreCase("huawei")) {
try { try {
@SuppressLint("PrivateApi") Class<?> protectAppControlClass = Class.forName("com.huawei.systemmanager.optimize.process" + @SuppressLint("PrivateApi") Class<?> protectAppControlClass =
Class.forName("com.huawei.systemmanager.optimize.process" +
".ProtectAppControl"); ".ProtectAppControl");
if (protectAppControlClass != null) { if (protectAppControlClass != null) {
Context applicationContext = NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext(); Context applicationContext =
NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext();
Method getInstanceMethod = protectAppControlClass.getMethod("getInstance", Context.class); Method getInstanceMethod = protectAppControlClass.getMethod("getInstance", Context.class);
// ProtectAppControl instance // ProtectAppControl instance
if (getInstanceMethod != null) { if (getInstanceMethod != null) {
Object protectAppControlInstance = getInstanceMethod.invoke(null, applicationContext); Object protectAppControlInstance = getInstanceMethod.invoke(null, applicationContext);
Method setProtectMethod = protectAppControlClass.getDeclaredMethod("setProtect", List.class); Method setProtectMethod =
protectAppControlClass.getDeclaredMethod("setProtect", List.class);
if (setProtectMethod != null) { if (setProtectMethod != null) {
List<String> appsList = new ArrayList<>(); List<String> appsList = new ArrayList<>();
appsList.add(applicationContext.getPackageName()); appsList.add(applicationContext.getPackageName());

View File

@ -105,7 +105,9 @@ public class DisplayUtils {
public void onClick(@Nonnull View widget) { public void onClick(@Nonnull View widget) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext().startActivity(browserIntent); NextcloudTalkApplication.Companion.getSharedApplication()
.getApplicationContext()
.startActivity(browserIntent);
} }
@Override @Override
@ -120,8 +122,11 @@ public class DisplayUtils {
private static void updateViewSize(@Nullable ImageInfo imageInfo, SimpleDraweeView draweeView) { private static void updateViewSize(@Nullable ImageInfo imageInfo, SimpleDraweeView draweeView) {
if (imageInfo != null) { if (imageInfo != null) {
int maxSize = draweeView.getContext().getResources().getDimensionPixelSize(R.dimen.maximum_file_preview_size); int maxSize = draweeView.getContext()
draweeView.getLayoutParams().width = imageInfo.getWidth() > maxSize ? maxSize : imageInfo.getWidth(); .getResources()
.getDimensionPixelSize(R.dimen.maximum_file_preview_size);
draweeView.getLayoutParams().width =
imageInfo.getWidth() > maxSize ? maxSize : imageInfo.getWidth();
draweeView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT; draweeView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
draweeView.setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight()); draweeView.setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight());
draweeView.requestLayout(); draweeView.requestLayout();
@ -134,14 +139,16 @@ public class DisplayUtils {
return new BitmapDrawable(bitmap); return new BitmapDrawable(bitmap);
} }
public static Bitmap getRoundedBitmapFromVectorDrawableResource(Resources resources, int resource) { public static Bitmap getRoundedBitmapFromVectorDrawableResource(Resources resources,
int resource) {
VectorDrawable vectorDrawable = (VectorDrawable) resources.getDrawable(resource); VectorDrawable vectorDrawable = (VectorDrawable) resources.getDrawable(resource);
Bitmap bitmap = getBitmap(vectorDrawable); Bitmap bitmap = getBitmap(vectorDrawable);
new RoundPostprocessor(true).process(bitmap); new RoundPostprocessor(true).process(bitmap);
return bitmap; return bitmap;
} }
public static Drawable getRoundedBitmapDrawableFromVectorDrawableResource(Resources resources, int resource) { public static Drawable getRoundedBitmapDrawableFromVectorDrawableResource(Resources resources,
int resource) {
return new BitmapDrawable(getRoundedBitmapFromVectorDrawableResource(resources, resource)); return new BitmapDrawable(getRoundedBitmapFromVectorDrawableResource(resources, resource));
} }
@ -156,8 +163,10 @@ public class DisplayUtils {
public static ImageRequest getImageRequestForUrl(String url, @Nullable UserEntity userEntity) { public static ImageRequest getImageRequestForUrl(String url, @Nullable UserEntity userEntity) {
Map<String, String> headers = new HashMap<>(); Map<String, String> headers = new HashMap<>();
if (userEntity != null && url.startsWith(userEntity.getBaseUrl()) && url.contains("index.php/core/preview?fileId=")) { if (userEntity != null && url.startsWith(userEntity.getBaseUrl()) && url.contains(
headers.put("Authorization", ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken())); "index.php/core/preview?fileId=")) {
headers.put("Authorization",
ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()));
} }
return ImageRequestBuilder.newBuilderWithSource(Uri.parse(url)) return ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
@ -176,7 +185,8 @@ public class DisplayUtils {
} }
@Override @Override
public void onFinalImageSet(String id, @javax.annotation.Nullable Object imageInfo, @javax.annotation.Nullable Animatable animatable) { public void onFinalImageSet(String id, @javax.annotation.Nullable Object imageInfo,
@javax.annotation.Nullable Animatable animatable) {
updateViewSize((ImageInfo) imageInfo, draweeView); updateViewSize((ImageInfo) imageInfo, draweeView);
} }
@ -211,9 +221,12 @@ public class DisplayUtils {
public static void useCompatVectorIfNeeded() { public static void useCompatVectorIfNeeded() {
if (Build.VERSION.SDK_INT < 23) { if (Build.VERSION.SDK_INT < 23) {
try { try {
@SuppressLint("RestrictedApi") AppCompatDrawableManager drawableManager = AppCompatDrawableManager.get(); @SuppressLint("RestrictedApi") AppCompatDrawableManager drawableManager =
Class<?> inflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$InflateDelegate"); AppCompatDrawableManager.get();
Class<?> vdcInflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$VdcInflateDelegate"); Class<?> inflateDelegateClass =
Class.forName("android.support.v7.widget.AppCompatDrawableManager$InflateDelegate");
Class<?> vdcInflateDelegateClass =
Class.forName("android.support.v7.widget.AppCompatDrawableManager$VdcInflateDelegate");
Constructor<?> constructor = vdcInflateDelegateClass.getDeclaredConstructor(); Constructor<?> constructor = vdcInflateDelegateClass.getDeclaredConstructor();
constructor.setAccessible(true); constructor.setAccessible(true);
@ -230,15 +243,16 @@ public class DisplayUtils {
} }
} }
public static Drawable getTintedDrawable(Resources res, @DrawableRes int drawableResId, @ColorRes int colorResId) { public static Drawable getTintedDrawable(Resources res, @DrawableRes int drawableResId,
@ColorRes int colorResId) {
Drawable drawable = res.getDrawable(drawableResId); Drawable drawable = res.getDrawable(drawableResId);
int color = res.getColor(colorResId); int color = res.getColor(colorResId);
drawable.setTint(color); drawable.setTint(color);
return drawable; return drawable;
} }
public static Drawable getDrawableForMentionChipSpan(Context context, String id,
public static Drawable getDrawableForMentionChipSpan(Context context, String id, CharSequence label, CharSequence label,
UserEntity conversationUser, String type, UserEntity conversationUser, String type,
@XmlRes int chipResource, @XmlRes int chipResource,
@Nullable EditText emojiEditText) { @Nullable EditText emojiEditText) {
@ -264,19 +278,23 @@ public class DisplayUtils {
chip.setChipIcon(context.getDrawable(drawable)); chip.setChipIcon(context.getDrawable(drawable));
} else { } else {
chip.setChipIcon(getRoundedDrawable(context.getDrawable(R.drawable.ic_people_group_white_24px))); chip.setChipIcon(
getRoundedDrawable(context.getDrawable(R.drawable.ic_people_group_white_24px)));
} }
chip.setBounds(0, 0, chip.getIntrinsicWidth(), chip.getIntrinsicHeight()); chip.setBounds(0, 0, chip.getIntrinsicWidth(), chip.getIntrinsicHeight());
if (!isCall) { if (!isCall) {
String url = ApiUtils.getUrlForAvatarWithName(conversationUser.getBaseUrl(), id, R.dimen.avatar_size_big); String url = ApiUtils.getUrlForAvatarWithName(conversationUser.getBaseUrl(), id,
R.dimen.avatar_size_big);
if ("guests".equals(type) || "guest".equals(type)) { if ("guests".equals(type) || "guest".equals(type)) {
url = ApiUtils.getUrlForAvatarWithNameForGuests(conversationUser.getBaseUrl(), String.valueOf(label), R.dimen.avatar_size_big); url = ApiUtils.getUrlForAvatarWithNameForGuests(conversationUser.getBaseUrl(),
String.valueOf(label), R.dimen.avatar_size_big);
} }
ImageRequest imageRequest = getImageRequestForUrl(url, null); ImageRequest imageRequest = getImageRequestForUrl(url, null);
ImagePipeline imagePipeline = Fresco.getImagePipeline(); ImagePipeline imagePipeline = Fresco.getImagePipeline();
DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context); DataSource<CloseableReference<CloseableImage>> dataSource =
imagePipeline.fetchDecodedImage(imageRequest, context);
dataSource.subscribe( dataSource.subscribe(
new BaseBitmapDataSubscriber() { new BaseBitmapDataSubscriber() {
@ -287,13 +305,15 @@ public class DisplayUtils {
// A hack to refresh the chip icon // A hack to refresh the chip icon
if (emojiEditText != null) { if (emojiEditText != null) {
emojiEditText.post(() -> emojiEditText.setTextKeepState(emojiEditText.getText(), TextView.BufferType.SPANNABLE)); emojiEditText.post(() -> emojiEditText.setTextKeepState(emojiEditText.getText(),
TextView.BufferType.SPANNABLE));
} }
} }
} }
@Override @Override
protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { protected void onFailureImpl(
DataSource<CloseableReference<CloseableImage>> dataSource) {
} }
}, },
UiThreadImmediateExecutorService.getInstance()); UiThreadImmediateExecutorService.getInstance());
@ -302,7 +322,6 @@ public class DisplayUtils {
return chip; return chip;
} }
public static Spannable searchAndReplaceWithMentionSpan(Context context, Spannable text, public static Spannable searchAndReplaceWithMentionSpan(Context context, Spannable text,
String id, String label, String type, String id, String label, String type,
UserEntity conversationUser, UserEntity conversationUser,
@ -328,7 +347,8 @@ public class DisplayUtils {
int start = stringText.indexOf(m.group(), lastStartIndex); int start = stringText.indexOf(m.group(), lastStartIndex);
int end = start + m.group().length(); int end = start + m.group().length();
lastStartIndex = end; lastStartIndex = end;
mentionChipSpan = new Spans.MentionChipSpan(DisplayUtils.getDrawableForMentionChipSpan(context, mentionChipSpan =
new Spans.MentionChipSpan(DisplayUtils.getDrawableForMentionChipSpan(context,
id, label, conversationUser, type, chipXmlRes, null), id, label, conversationUser, type, chipXmlRes, null),
BetterImageSpan.ALIGN_CENTER, id, BetterImageSpan.ALIGN_CENTER, id,
label); label);
@ -339,7 +359,6 @@ public class DisplayUtils {
} }
return spannableString; return spannableString;
} }
public static Spannable searchAndColor(Spannable text, String searchText, @ColorInt int color) { public static Spannable searchAndColor(Spannable text, String searchText, @ColorInt int color) {
@ -354,8 +373,9 @@ public class DisplayUtils {
Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.MULTILINE) Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.MULTILINE)
.matcher(spannableString); .matcher(spannableString);
int textSize = NextcloudTalkApplication.Companion.getSharedApplication()
int textSize = NextcloudTalkApplication.Companion.getSharedApplication().getResources().getDimensionPixelSize(R.dimen .getResources()
.getDimensionPixelSize(R.dimen
.chat_text_size); .chat_text_size);
int lastStartIndex = -1; int lastStartIndex = -1;
@ -365,8 +385,10 @@ public class DisplayUtils {
lastStartIndex = end; lastStartIndex = end;
spannableString.setSpan(new ForegroundColorSpan(color), start, end, spannableString.setSpan(new ForegroundColorSpan(color), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new StyleSpan(Typeface.BOLD), start, end,
spannableString.setSpan(new AbsoluteSizeSpan(textSize), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new AbsoluteSizeSpan(textSize), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} }
return spannableString; return spannableString;
@ -375,19 +397,20 @@ public class DisplayUtils {
public static Drawable getMessageSelector(@ColorInt int normalColor, @ColorInt int selectedColor, public static Drawable getMessageSelector(@ColorInt int normalColor, @ColorInt int selectedColor,
@ColorInt int pressedColor, @DrawableRes int shape) { @ColorInt int pressedColor, @DrawableRes int shape) {
Drawable vectorDrawable = ContextCompat.getDrawable(NextcloudTalkApplication.Companion.getSharedApplication() Drawable vectorDrawable =
ContextCompat.getDrawable(NextcloudTalkApplication.Companion.getSharedApplication()
.getApplicationContext(), .getApplicationContext(),
shape); shape);
Drawable drawable = DrawableCompat.wrap(vectorDrawable).mutate(); Drawable drawable = DrawableCompat.wrap(vectorDrawable).mutate();
DrawableCompat.setTintList( DrawableCompat.setTintList(
drawable, drawable,
new ColorStateList( new ColorStateList(
new int[][]{ new int[][] {
new int[]{android.R.attr.state_selected}, new int[] { android.R.attr.state_selected },
new int[]{android.R.attr.state_pressed}, new int[] { android.R.attr.state_pressed },
new int[]{-android.R.attr.state_pressed, -android.R.attr.state_selected} new int[] { -android.R.attr.state_pressed, -android.R.attr.state_selected }
}, },
new int[]{selectedColor, pressedColor, normalColor} new int[] { selectedColor, pressedColor, normalColor }
)); ));
return drawable; return drawable;
} }

View File

@ -28,16 +28,18 @@ import android.os.Vibrator
import com.nextcloud.talk.application.NextcloudTalkApplication import com.nextcloud.talk.application.NextcloudTalkApplication
object DoNotDisturbUtils { object DoNotDisturbUtils {
fun isDnDActive() : Boolean { fun isDnDActive(): Boolean {
val context = NextcloudTalkApplication.sharedApplication?.applicationContext val context = NextcloudTalkApplication.sharedApplication?.applicationContext
val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager =
context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (notificationManager.currentInterruptionFilter == NotificationManager if (notificationManager.currentInterruptionFilter == NotificationManager
.INTERRUPTION_FILTER_NONE || notificationManager .INTERRUPTION_FILTER_NONE || notificationManager
.currentInterruptionFilter == NotificationManager .currentInterruptionFilter == NotificationManager
.INTERRUPTION_FILTER_ALARMS || notificationManager .INTERRUPTION_FILTER_ALARMS || notificationManager
.currentInterruptionFilter == NotificationManager.INTERRUPTION_FILTER_PRIORITY) { .currentInterruptionFilter == NotificationManager.INTERRUPTION_FILTER_PRIORITY
) {
return true return true
} }
} }
@ -49,7 +51,8 @@ object DoNotDisturbUtils {
fun isInDoNotDisturbWithPriority(): Boolean { fun isInDoNotDisturbWithPriority(): Boolean {
val context = NextcloudTalkApplication.sharedApplication?.applicationContext val context = NextcloudTalkApplication.sharedApplication?.applicationContext
val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager =
context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (notificationManager.currentInterruptionFilter == NotificationManager.INTERRUPTION_FILTER_PRIORITY) { if (notificationManager.currentInterruptionFilter == NotificationManager.INTERRUPTION_FILTER_PRIORITY) {
return true return true
@ -62,7 +65,8 @@ object DoNotDisturbUtils {
fun shouldPlaySound(): Boolean { fun shouldPlaySound(): Boolean {
val context = NextcloudTalkApplication.sharedApplication?.applicationContext val context = NextcloudTalkApplication.sharedApplication?.applicationContext
val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager =
context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
var shouldPlaySound = true var shouldPlaySound = true

View File

@ -26,7 +26,6 @@ import java.util.HashMap
object DrawableUtils { object DrawableUtils {
fun getDrawableResourceIdForMimeType(mimetype: String): Int { fun getDrawableResourceIdForMimeType(mimetype: String): Int {
var localMimetype = mimetype var localMimetype = mimetype
val drawableMap = HashMap<String, Int>() val drawableMap = HashMap<String, Int>()
@ -48,44 +47,72 @@ object DrawableUtils {
drawableMap["application/octet-stream"] = R.drawable.ic_mimetype_file drawableMap["application/octet-stream"] = R.drawable.ic_mimetype_file
drawableMap["application/postscript"] = R.drawable.ic_mimetype_image drawableMap["application/postscript"] = R.drawable.ic_mimetype_image
drawableMap["application/rss+xml"] = R.drawable.ic_mimetype_text_code drawableMap["application/rss+xml"] = R.drawable.ic_mimetype_text_code
drawableMap["application/vnd.android.package-archive"] = R.drawable.ic_mimetype_package_x_generic drawableMap["application/vnd.android.package-archive"] =
R.drawable.ic_mimetype_package_x_generic
drawableMap["application/vnd.lotus-wordpro"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.lotus-wordpro"] = R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.garmin.tcx+xml"] = R.drawable.ic_mimetype_location drawableMap["application/vnd.garmin.tcx+xml"] = R.drawable.ic_mimetype_location
drawableMap["application/vnd.google-earth.kml+xml"] = R.drawable.ic_mimetype_location drawableMap["application/vnd.google-earth.kml+xml"] = R.drawable.ic_mimetype_location
drawableMap["application/vnd.google-earth.kmz"] = R.drawable.ic_mimetype_location drawableMap["application/vnd.google-earth.kmz"] = R.drawable.ic_mimetype_location
drawableMap["application/vnd.ms-excel"] = R.drawable.ic_mimetype_x_office_spreadsheet drawableMap["application/vnd.ms-excel"] = R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.ms-excel.addin.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_spreadsheet drawableMap["application/vnd.ms-excel.addin.macroEnabled.12"] =
drawableMap["application/vnd.ms-excel.sheet.binary.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_spreadsheet R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.ms-excel.sheet.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_spreadsheet drawableMap["application/vnd.ms-excel.sheet.binary.macroEnabled.12"] =
drawableMap["application/vnd.ms-excel.template.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_spreadsheet R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.ms-excel.sheet.macroEnabled.12"] =
R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.ms-excel.template.macroEnabled.12"] =
R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.ms-fontobject"] = R.drawable.ic_mimetype_image drawableMap["application/vnd.ms-fontobject"] = R.drawable.ic_mimetype_image
drawableMap["application/vnd.ms-powerpoint"] = R.drawable.ic_mimetype_x_office_presentation drawableMap["application/vnd.ms-powerpoint"] = R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.ms-powerpoint.addin.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_presentation drawableMap["application/vnd.ms-powerpoint.addin.macroEnabled.12"] =
drawableMap["application/vnd.ms-powerpoint.presentation.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_presentation R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.ms-powerpoint.slideshow.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_presentation drawableMap["application/vnd.ms-powerpoint.presentation.macroEnabled.12"] =
drawableMap["application/vnd.ms-powerpoint.template.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_presentation R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.ms-visio.drawing.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.ms-powerpoint.slideshow.macroEnabled.12"] =
R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.ms-powerpoint.template.macroEnabled.12"] =
R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.ms-visio.drawing.macroEnabled.12"] =
R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.ms-visio.drawing"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.ms-visio.drawing"] = R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.ms-visio.stencil.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.ms-visio.stencil.macroEnabled.12"] =
R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.ms-visio.stencil"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.ms-visio.stencil"] = R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.ms-visio.template.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.ms-visio.template.macroEnabled.12"] =
R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.ms-visio.template"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.ms-visio.template"] = R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.ms-word.template.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.ms-word.template.macroEnabled.12"] =
drawableMap["application/vnd.oasis.opendocument.presentation"] = R.drawable.ic_mimetype_x_office_presentation R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.oasis.opendocument.presentation-template"] = R.drawable.ic_mimetype_x_office_presentation drawableMap["application/vnd.oasis.opendocument.presentation"] =
drawableMap["application/vnd.oasis.opendocument.spreadsheet"] = R.drawable.ic_mimetype_x_office_spreadsheet R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.oasis.opendocument.spreadsheet-template"] = R.drawable.ic_mimetype_x_office_spreadsheet drawableMap["application/vnd.oasis.opendocument.presentation-template"] =
drawableMap["application/vnd.oasis.opendocument.text"] = R.drawable.ic_mimetype_x_office_document R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.oasis.opendocument.text-master"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.oasis.opendocument.spreadsheet"] =
drawableMap["application/vnd.oasis.opendocument.text-template"] = R.drawable.ic_mimetype_x_office_document R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.oasis.opendocument.text-web"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.oasis.opendocument.spreadsheet-template"] =
drawableMap["application/vnd.openxmlformats-officedocument.presentationml.presentation"] = R.drawable.ic_mimetype_x_office_presentation R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.openxmlformats-officedocument.presentationml.slideshow"] = R.drawable.ic_mimetype_x_office_presentation drawableMap["application/vnd.oasis.opendocument.text"] =
drawableMap["application/vnd.openxmlformats-officedocument.presentationml.template"] = R.drawable.ic_mimetype_x_office_presentation R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"] = R.drawable.ic_mimetype_x_office_spreadsheet drawableMap["application/vnd.oasis.opendocument.text-master"] =
drawableMap["application/vnd.openxmlformats-officedocument.spreadsheetml.template"] = R.drawable.ic_mimetype_x_office_spreadsheet R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.openxmlformats-officedocument.wordprocessingml.document"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.oasis.opendocument.text-template"] =
drawableMap["application/vnd.openxmlformats-officedocument.wordprocessingml.template"] = R.drawable.ic_mimetype_x_office_document R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.oasis.opendocument.text-web"] =
R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.openxmlformats-officedocument.presentationml.presentation"] =
R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.openxmlformats-officedocument.presentationml.slideshow"] =
R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.openxmlformats-officedocument.presentationml.template"] =
R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"] =
R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.openxmlformats-officedocument.spreadsheetml.template"] =
R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.openxmlformats-officedocument.wordprocessingml.document"] =
R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.openxmlformats-officedocument.wordprocessingml.template"] =
R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.visio"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.visio"] = R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.wordperfect"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/vnd.wordperfect"] = R.drawable.ic_mimetype_x_office_document
drawableMap["application/x-7z-compressed"] = R.drawable.ic_mimetype_package_x_generic drawableMap["application/x-7z-compressed"] = R.drawable.ic_mimetype_package_x_generic
@ -99,7 +126,8 @@ object DrawableUtils {
drawableMap["application/x-gimp"] = R.drawable.ic_mimetype_image drawableMap["application/x-gimp"] = R.drawable.ic_mimetype_image
drawableMap["application/x-gzip"] = R.drawable.ic_mimetype_package_x_generic drawableMap["application/x-gzip"] = R.drawable.ic_mimetype_package_x_generic
drawableMap["application/x-iwork-keynote-sffkey"] = R.drawable.ic_mimetype_x_office_presentation drawableMap["application/x-iwork-keynote-sffkey"] = R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/x-iwork-numbers-sffnumbers"] = R.drawable.ic_mimetype_x_office_spreadsheet drawableMap["application/x-iwork-numbers-sffnumbers"] =
R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/x-iwork-pages-sffpages"] = R.drawable.ic_mimetype_x_office_document drawableMap["application/x-iwork-pages-sffpages"] = R.drawable.ic_mimetype_x_office_document
drawableMap["application/x-mobipocket-ebook"] = R.drawable.ic_mimetype_text drawableMap["application/x-mobipocket-ebook"] = R.drawable.ic_mimetype_text
drawableMap["application/x-perl"] = R.drawable.ic_mimetype_text_code drawableMap["application/x-perl"] = R.drawable.ic_mimetype_text_code

View File

@ -41,14 +41,16 @@ public class FABAwareScrollingViewBehavior extends AppBarLayout.ScrollingViewBeh
final View directTargetChild, final View target, final int nestedScrollAxes) { final View directTargetChild, final View target, final int nestedScrollAxes) {
// Ensure we react to vertical scrolling // Ensure we react to vertical scrolling
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
|| super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes); || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
nestedScrollAxes);
} }
@Override @Override
public void onNestedScroll(final CoordinatorLayout coordinatorLayout, final View child, public void onNestedScroll(final CoordinatorLayout coordinatorLayout, final View child,
final View target, final int dxConsumed, final int dyConsumed, final View target, final int dxConsumed, final int dyConsumed,
final int dxUnconsumed, final int dyUnconsumed) { final int dxUnconsumed, final int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed); super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed,
dyUnconsumed);
if (dyConsumed > 0) { if (dyConsumed > 0) {
// User scrolled down -> hide the FAB // User scrolled down -> hide the FAB
List<View> dependencies = coordinatorLayout.getDependencies(child); List<View> dependencies = coordinatorLayout.getDependencies(child);

View File

@ -33,7 +33,8 @@ public class KeyboardUtils {
private View contentView; private View contentView;
private boolean isUsedInBottomSheet; private boolean isUsedInBottomSheet;
//a small helper to allow showing the editText focus //a small helper to allow showing the editText focus
ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener =
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override @Override
public void onGlobalLayout() { public void onGlobalLayout() {
Rect r = new Rect(); Rect r = new Rect();
@ -72,12 +73,11 @@ public class KeyboardUtils {
/** /**
* Helper to hide the keyboard * Helper to hide the keyboard
*
* @param act
*/ */
public static void hideKeyboard(Activity act) { public static void hideKeyboard(Activity act) {
if (act != null && act.getCurrentFocus() != null) { if (act != null && act.getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) act.getSystemService(Activity.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager =
(InputMethodManager) act.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(act.getCurrentFocus().getWindowToken(), 0); inputMethodManager.hideSoftInputFromWindow(act.getCurrentFocus().getWindowToken(), 0);
} }
} }

View File

@ -32,14 +32,19 @@ import java.text.SimpleDateFormat
import java.util.Date import java.util.Date
object LoggingUtils { object LoggingUtils {
fun writeLogEntryToFile(context: Context, logEntry: String) { fun writeLogEntryToFile(
context: Context,
logEntry: String
) {
val dateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss") val dateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
val date = Date() val date = Date()
val logEntryWithDateTime = dateFormat.format(date) + ": " + logEntry + "\n" val logEntryWithDateTime = dateFormat.format(date) + ": " + logEntry + "\n"
try { try {
val outputStream = context.openFileOutput("nc_log.txt", val outputStream = context.openFileOutput(
Context.MODE_PRIVATE or Context.MODE_APPEND) "nc_log.txt",
Context.MODE_PRIVATE or Context.MODE_APPEND
)
outputStream.write(logEntryWithDateTime.toByteArray()) outputStream.write(logEntryWithDateTime.toByteArray())
outputStream.flush() outputStream.flush()
outputStream.close() outputStream.close()

View File

@ -43,7 +43,7 @@ public class MagicCharPolicy implements AutocompletePolicy {
// Do absolutely nothing // Do absolutely nothing
} }
QuerySpan sp = span[0]; QuerySpan sp = span[0];
return new int[]{text.getSpanStart(sp), text.getSpanEnd(sp)}; return new int[] { text.getSpanStart(sp), text.getSpanEnd(sp) };
} }
private int[] checkText(Spannable text, int cursorPos) { private int[] checkText(Spannable text, int cursorPos) {

View File

@ -41,17 +41,27 @@ object NotificationUtils {
val NOTIFICATION_CHANNEL_CALLS_V3 = "NOTIFICATION_CHANNEL_CALLS_V3" val NOTIFICATION_CHANNEL_CALLS_V3 = "NOTIFICATION_CHANNEL_CALLS_V3"
@TargetApi(Build.VERSION_CODES.O) @TargetApi(Build.VERSION_CODES.O)
fun createNotificationChannel(context: Context, fun createNotificationChannel(
channelId: String, channelName: String, context: Context,
channelDescription: String, enableLights: Boolean, channelId: String,
importance: Int) { channelName: String,
channelDescription: String,
enableLights: Boolean,
importance: Int
) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && notificationManager.getNotificationChannel(channelId) == null) { if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && notificationManager.getNotificationChannel(
channelId
) == null
) {
val channel = NotificationChannel(channelId, channelName, val channel = NotificationChannel(
importance) channelId, channelName,
importance
)
channel.description = channelDescription channel.description = channelDescription
channel.enableLights(enableLights) channel.enableLights(enableLights)
@ -63,10 +73,14 @@ object NotificationUtils {
} }
@TargetApi(Build.VERSION_CODES.O) @TargetApi(Build.VERSION_CODES.O)
fun createNotificationChannelGroup(context: Context, fun createNotificationChannelGroup(
groupId: String, groupName: CharSequence) { context: Context,
groupId: String,
groupName: CharSequence
) {
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationChannelGroup = NotificationChannelGroup(groupId, groupName) val notificationChannelGroup = NotificationChannelGroup(groupId, groupName)
if (!notificationManager.notificationChannelGroups.contains(notificationChannelGroup)) { if (!notificationManager.notificationChannelGroups.contains(notificationChannelGroup)) {
@ -75,10 +89,14 @@ object NotificationUtils {
} }
} }
fun cancelAllNotificationsForAccount(context: Context?, conversationUser: UserEntity) { fun cancelAllNotificationsForAccount(
context: Context?,
conversationUser: UserEntity
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && conversationUser.id != -1L && context != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && conversationUser.id != -1L && context != null) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val statusBarNotifications = notificationManager.activeNotifications val statusBarNotifications = notificationManager.activeNotifications
var notification: Notification? var notification: Notification?
@ -95,11 +113,17 @@ object NotificationUtils {
} }
fun cancelExistingNotificationWithId(context: Context?, conversationUser: UserEntity, notificationId: Long) { fun cancelExistingNotificationWithId(
context: Context?,
conversationUser: UserEntity,
notificationId: Long
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && conversationUser.id != -1L && if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && conversationUser.id != -1L &&
context != null) { context != null
) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val statusBarNotifications = notificationManager.activeNotifications val statusBarNotifications = notificationManager.activeNotifications
var notification: Notification? var notification: Notification?
@ -107,7 +131,10 @@ object NotificationUtils {
notification = statusBarNotification.notification notification = statusBarNotification.notification
if (notification != null && !notification.extras.isEmpty) { if (notification != null && !notification.extras.isEmpty) {
if (conversationUser.id == notification.extras.getLong(BundleKeys.KEY_INTERNAL_USER_ID) && notificationId == notification.extras.getLong(BundleKeys.KEY_NOTIFICATION_ID)) { if (conversationUser.id == notification.extras.getLong(
BundleKeys.KEY_INTERNAL_USER_ID
) && notificationId == notification.extras.getLong(BundleKeys.KEY_NOTIFICATION_ID)
) {
notificationManager.cancel(statusBarNotification.id) notificationManager.cancel(statusBarNotification.id)
} }
} }
@ -115,13 +142,17 @@ object NotificationUtils {
} }
} }
fun findNotificationForRoom(context: Context?, fun findNotificationForRoom(
context: Context?,
conversationUser: UserEntity, conversationUser: UserEntity,
roomTokenOrId: String): StatusBarNotification? { roomTokenOrId: String
): StatusBarNotification? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && conversationUser.id != -1L && if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && conversationUser.id != -1L &&
context != null) { context != null
) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val statusBarNotifications = notificationManager.activeNotifications val statusBarNotifications = notificationManager.activeNotifications
var notification: Notification? var notification: Notification?
@ -129,7 +160,12 @@ object NotificationUtils {
notification = statusBarNotification.notification notification = statusBarNotification.notification
if (notification != null && !notification.extras.isEmpty) { if (notification != null && !notification.extras.isEmpty) {
if (conversationUser.id == notification.extras.getLong(BundleKeys.KEY_INTERNAL_USER_ID) && roomTokenOrId == statusBarNotification.notification.extras.getString(BundleKeys.KEY_ROOM_TOKEN)) { if (conversationUser.id == notification.extras.getLong(
BundleKeys.KEY_INTERNAL_USER_ID
) && roomTokenOrId == statusBarNotification.notification.extras.getString(
BundleKeys.KEY_ROOM_TOKEN
)
) {
return statusBarNotification return statusBarNotification
} }
} }
@ -139,12 +175,17 @@ object NotificationUtils {
return null return null
} }
fun cancelExistingNotificationsForRoom(context: Context?, conversationUser: UserEntity, fun cancelExistingNotificationsForRoom(
roomTokenOrId: String) { context: Context?,
conversationUser: UserEntity,
roomTokenOrId: String
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && conversationUser.id != -1L && if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && conversationUser.id != -1L &&
context != null) { context != null
) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val statusBarNotifications = notificationManager.activeNotifications val statusBarNotifications = notificationManager.activeNotifications
var notification: Notification? var notification: Notification?
@ -152,7 +193,12 @@ object NotificationUtils {
notification = statusBarNotification.notification notification = statusBarNotification.notification
if (notification != null && !notification.extras.isEmpty) { if (notification != null && !notification.extras.isEmpty) {
if (conversationUser.id == notification.extras.getLong(BundleKeys.KEY_INTERNAL_USER_ID) && roomTokenOrId == statusBarNotification.notification.extras.getString(BundleKeys.KEY_ROOM_TOKEN)) { if (conversationUser.id == notification.extras.getLong(
BundleKeys.KEY_INTERNAL_USER_ID
) && roomTokenOrId == statusBarNotification.notification.extras.getString(
BundleKeys.KEY_ROOM_TOKEN
)
) {
notificationManager.cancel(statusBarNotification.id) notificationManager.cancel(statusBarNotification.id)
} }
} }

View File

@ -34,7 +34,8 @@ public class OkHttpNetworkFetcherWithCache extends OkHttpNetworkFetcher {
super(callFactory, cancellationExecutor); super(callFactory, cancellationExecutor);
} }
public OkHttpNetworkFetcherWithCache(Call.Factory callFactory, Executor cancellationExecutor, boolean disableOkHttpCache) { public OkHttpNetworkFetcherWithCache(Call.Factory callFactory, Executor cancellationExecutor,
boolean disableOkHttpCache) {
super(callFactory, cancellationExecutor, true); super(callFactory, cancellationExecutor, true);
} }
} }

View File

@ -26,14 +26,14 @@ import android.util.Base64;
import android.util.Log; import android.util.Log;
import autodagger.AutoInjector; import autodagger.AutoInjector;
import com.bluelinelabs.logansquare.LoganSquare; import com.bluelinelabs.logansquare.LoganSquare;
import com.nextcloud.talk.models.SignatureVerification;
import com.nextcloud.talk.models.json.push.PushConfigurationState;
import com.nextcloud.talk.models.json.push.PushRegistrationOverall;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.api.NcApi; import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication; import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.events.EventStatus; import com.nextcloud.talk.events.EventStatus;
import com.nextcloud.talk.models.SignatureVerification;
import com.nextcloud.talk.models.database.UserEntity; import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.models.json.push.PushConfigurationState;
import com.nextcloud.talk.models.json.push.PushRegistrationOverall;
import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.database.user.UserUtils;
import com.nextcloud.talk.utils.preferences.AppPreferences; import com.nextcloud.talk.utils.preferences.AppPreferences;
import io.reactivex.Observer; import io.reactivex.Observer;
@ -86,13 +86,18 @@ public class PushUtils {
private String proxyServer; private String proxyServer;
public PushUtils() { public PushUtils() {
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this); NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
keysFile = NextcloudTalkApplication.Companion.getSharedApplication().getDir("PushKeyStore", Context.MODE_PRIVATE); keysFile = NextcloudTalkApplication.Companion.getSharedApplication()
.getDir("PushKeyStore", Context.MODE_PRIVATE);
publicKeyFile = new File(NextcloudTalkApplication.Companion.getSharedApplication().getDir("PushKeystore", publicKeyFile =
new File(NextcloudTalkApplication.Companion.getSharedApplication().getDir("PushKeystore",
Context.MODE_PRIVATE), "push_key.pub"); Context.MODE_PRIVATE), "push_key.pub");
privateKeyFile = new File(NextcloudTalkApplication.Companion.getSharedApplication().getDir("PushKeystore", privateKeyFile =
new File(NextcloudTalkApplication.Companion.getSharedApplication().getDir("PushKeystore",
Context.MODE_PRIVATE), "push_key.priv"); Context.MODE_PRIVATE), "push_key.priv");
proxyServer = NextcloudTalkApplication.Companion.getSharedApplication().getResources(). proxyServer = NextcloudTalkApplication.Companion.getSharedApplication().getResources().
getString(R.string.nc_push_server_url); getString(R.string.nc_push_server_url);
@ -203,7 +208,6 @@ public class PushUtils {
} else { } else {
return -2; return -2;
} }
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
Log.d(TAG, "RSA algorithm not supported"); Log.d(TAG, "RSA algorithm not supported");
} }
@ -247,9 +251,11 @@ public class PushUtils {
accountPushData = null; accountPushData = null;
} }
if (((TextUtils.isEmpty(providerValue) || accountPushData == null) && !userEntity.getScheduledForDeletion()) || if (((TextUtils.isEmpty(providerValue) || accountPushData == null)
(accountPushData != null && !accountPushData.getPushToken().equals(token) && !userEntity.getScheduledForDeletion())) { && !userEntity.getScheduledForDeletion()) ||
(accountPushData != null
&& !accountPushData.getPushToken().equals(token)
&& !userEntity.getScheduledForDeletion())) {
Map<String, String> queryMap = new HashMap<>(); Map<String, String> queryMap = new HashMap<>();
queryMap.put("format", "json"); queryMap.put("format", "json");
@ -257,7 +263,8 @@ public class PushUtils {
queryMap.put("devicePublicKey", publicKey); queryMap.put("devicePublicKey", publicKey);
queryMap.put("proxyServer", proxyServer); queryMap.put("proxyServer", proxyServer);
credentials = ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()); credentials =
ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken());
String finalCredentials = credentials; String finalCredentials = credentials;
ncApi.registerDeviceForNotificationsWithNextcloud( ncApi.registerDeviceForNotificationsWithNextcloud(
@ -280,7 +287,6 @@ public class PushUtils {
proxyMap.put("userPublicKey", pushRegistrationOverall.getOcs() proxyMap.put("userPublicKey", pushRegistrationOverall.getOcs()
.getData().getPublicKey()); .getData().getPublicKey());
ncApi.registerDeviceForNotificationsWithProxy( ncApi.registerDeviceForNotificationsWithProxy(
ApiUtils.getUrlPushProxy(), proxyMap) ApiUtils.getUrlPushProxy(), proxyMap)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
@ -320,7 +326,8 @@ public class PushUtils {
@Override @Override
public void onNext(UserEntity userEntity) { public void onNext(UserEntity userEntity) {
eventBus.post(new EventStatus(userEntity.getId(), EventStatus.EventType.PUSH_REGISTRATION, true)); eventBus.post(new EventStatus(userEntity.getId(),
EventStatus.EventType.PUSH_REGISTRATION, true));
} }
@Override @Override
@ -339,8 +346,6 @@ public class PushUtils {
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, "IOException while updating user"); Log.e(TAG, "IOException while updating user");
} }
} }
@Override @Override
@ -360,7 +365,6 @@ public class PushUtils {
public void onError(Throwable e) { public void onError(Throwable e) {
eventBus.post(new EventStatus(userEntity.getId(), eventBus.post(new EventStatus(userEntity.getId(),
EventStatus.EventType.PUSH_REGISTRATION, false)); EventStatus.EventType.PUSH_REGISTRATION, false));
} }
@Override @Override
@ -387,13 +391,14 @@ public class PushUtils {
try { try {
keyFactory = KeyFactory.getInstance("RSA"); keyFactory = KeyFactory.getInstance("RSA");
if (readPublicKey) { if (readPublicKey) {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT)); X509EncodedKeySpec keySpec =
new X509EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT));
return keyFactory.generatePublic(keySpec); return keyFactory.generatePublic(keySpec);
} else { } else {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT)); PKCS8EncodedKeySpec keySpec =
new PKCS8EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT));
return keyFactory.generatePrivate(keySpec); return keyFactory.generatePrivate(keySpec);
} }
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
Log.d("TAG", "No such algorithm while reading key from string"); Log.d("TAG", "No such algorithm while reading key from string");
} catch (InvalidKeySpecException e) { } catch (InvalidKeySpecException e) {
@ -425,7 +430,6 @@ public class PushUtils {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
return keyFactory.generatePrivate(keySpec); return keyFactory.generatePrivate(keySpec);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Log.d(TAG, "Failed to find path while reading the Key"); Log.d(TAG, "Failed to find path while reading the Key");
} catch (IOException e) { } catch (IOException e) {

View File

@ -52,7 +52,7 @@ import javax.crypto.SecretKey;
public class SecurityUtils { public class SecurityUtils {
private static final String TAG = "SecurityUtils"; private static final String TAG = "SecurityUtils";
private static final String CREDENTIALS_KEY = "KEY_CREDENTIALS"; private static final String CREDENTIALS_KEY = "KEY_CREDENTIALS";
private static final byte[] SECRET_BYTE_ARRAY = new byte[]{1, 2, 3, 4, 5, 6}; private static final byte[] SECRET_BYTE_ARRAY = new byte[] { 1, 2, 3, 4, 5, 6 };
private static BiometricPrompt.CryptoObject cryptoObject; private static BiometricPrompt.CryptoObject cryptoObject;
@ -63,7 +63,11 @@ public class SecurityUtils {
keyStore.load(null); keyStore.load(null);
SecretKey secretKey = (SecretKey) keyStore.getKey(CREDENTIALS_KEY, null); SecretKey secretKey = (SecretKey) keyStore.getKey(CREDENTIALS_KEY, null);
Cipher cipher = Cipher cipher =
Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_GCM + "/" + KeyProperties.ENCRYPTION_PADDING_NONE); Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES
+ "/"
+ KeyProperties.BLOCK_MODE_GCM
+ "/"
+ KeyProperties.ENCRYPTION_PADDING_NONE);
// Try encrypting something, it will only work if the user authenticated within // Try encrypting something, it will only work if the user authenticated within
// the last AUTHENTICATION_DURATION_SECONDS seconds. // the last AUTHENTICATION_DURATION_SECONDS seconds.
@ -123,7 +127,8 @@ public class SecurityUtils {
private static int getIntegerFromStringTimeout(String validity) { private static int getIntegerFromStringTimeout(String validity) {
Resources resources = NextcloudTalkApplication.Companion.getSharedApplication().getResources(); Resources resources = NextcloudTalkApplication.Companion.getSharedApplication().getResources();
List<String> entryValues = Arrays.asList(resources.getStringArray(R.array.screen_lock_timeout_entry_values)); List<String> entryValues =
Arrays.asList(resources.getStringArray(R.array.screen_lock_timeout_entry_values));
int[] entryIntValues = resources.getIntArray(R.array.screen_lock_timeout_entry_int_values); int[] entryIntValues = resources.getIntArray(R.array.screen_lock_timeout_entry_int_values);
int indexOfValidity = entryValues.indexOf(validity); int indexOfValidity = entryValues.indexOf(validity);
return entryIntValues[indexOfValidity]; return entryIntValues[indexOfValidity];

View File

@ -41,7 +41,8 @@ import java.util.Set;
public class ShareUtils { public class ShareUtils {
public static String getStringForIntent(Context context, @Nullable String password, UserUtils userUtils, Conversation public static String getStringForIntent(Context context, @Nullable String password,
UserUtils userUtils, Conversation
conversation) { conversation) {
UserEntity userEntity = userUtils.getCurrentUser(); UserEntity userEntity = userUtils.getCurrentUser();
@ -51,7 +52,8 @@ public class ShareUtils {
userEntity.getBaseUrl(), conversation.getToken()); userEntity.getBaseUrl(), conversation.getToken());
if (!TextUtils.isEmpty(password)) { if (!TextUtils.isEmpty(password)) {
shareString += String.format(context.getResources().getString(R.string.nc_share_text_pass), password); shareString +=
String.format(context.getResources().getString(R.string.nc_share_text_pass), password);
} }
} }
@ -96,10 +98,8 @@ public class ShareUtils {
} }
return appResources; return appResources;
} }
return null; return null;
} }
} }

View File

@ -65,7 +65,8 @@ public final class TextMatchers {
MimeUtil.registerMimeDetector(ExtensionMimeDetector.class.getName()); MimeUtil.registerMimeDetector(ExtensionMimeDetector.class.getName());
MimeUtil.registerMimeDetector(OpendesktopMimeDetector.class.getName()); MimeUtil.registerMimeDetector(OpendesktopMimeDetector.class.getName());
String mimeType = MimeUtil.getMostSpecificMimeType(MimeUtil.getMimeTypes(specialLink)).toString(); String mimeType =
MimeUtil.getMostSpecificMimeType(MimeUtil.getMimeTypes(specialLink)).toString();
if (mimeType.startsWith("image/")) { if (mimeType.startsWith("image/")) {
if (mimeType.equalsIgnoreCase("image/gif")) { if (mimeType.equalsIgnoreCase("image/gif")) {
return ChatMessage.MessageType.SINGLE_LINK_GIF_MESSAGE; return ChatMessage.MessageType.SINGLE_LINK_GIF_MESSAGE;

Some files were not shown because too many files have changed in this diff Show More