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,
sslErrorHandler: SslErrorHandler?) {
fun showCertificateDialog(
cert: X509Certificate,
magicTrustManager: MagicTrustManager,
sslErrorHandler: SslErrorHandler?
) {
val formatter = DateFormat.getDateInstance(DateFormat.LONG)
val validFrom = formatter.format(cert.notBefore)
val validUntil = formatter.format(cert.notAfter)
@ -93,7 +96,11 @@ open class BaseActivity : AppCompatActivity() {
val type = list[0] as Int
if (type == 2) {
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()
@ -101,9 +108,11 @@ open class BaseActivity : AppCompatActivity() {
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),
issuedBy, issuedFor, validFrom, validUntil)
issuedBy, issuedFor, validFrom, validUntil
)
LovelyStandardDialog(this)
.setTopColorRes(R.color.nc_darkRed)

View File

@ -53,10 +53,12 @@ class MagicCallActivity : BaseActivity() {
NextcloudTalkApplication.sharedApplication!!.componentApplication.inject(this)
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_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
setContentView(R.layout.activity_magic_call)
@ -67,13 +69,17 @@ class MagicCallActivity : BaseActivity() {
if (!router!!.hasRootController()) {
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())
.popChangeHandler(HorizontalChangeHandler()))
.popChangeHandler(HorizontalChangeHandler())
)
} else {
router!!.setRoot(RouterTransaction.with(CallController(intent.extras))
router!!.setRoot(
RouterTransaction.with(CallController(intent.extras))
.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.application.NextcloudTalkApplication
import com.nextcloud.talk.controllers.CallNotificationController
import com.nextcloud.talk.controllers.ConversationsListController
import com.nextcloud.talk.controllers.LockedController
import com.nextcloud.talk.controllers.ServerSelectionController
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 (!router!!.hasRootController()) {
router!!.setRoot(RouterTransaction.with(ConversationsListView())
router!!.setRoot(
RouterTransaction.with(ConversationsListView())
.pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler()))
.popChangeHandler(HorizontalChangeHandler())
)
}
onNewIntent(intent)
} else if (!router!!.hasRootController()) {
if (hasDb) {
if (userUtils.anyUserExists()) {
router!!.setRoot(RouterTransaction.with(ConversationsListView())
router!!.setRoot(
RouterTransaction.with(ConversationsListView())
.pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler()))
.popChangeHandler(HorizontalChangeHandler())
)
} else {
router!!.setRoot(RouterTransaction.with(ServerSelectionController())
router!!.setRoot(
RouterTransaction.with(ServerSelectionController())
.pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler()))
.popChangeHandler(HorizontalChangeHandler())
)
}
} else {
router!!.setRoot(RouterTransaction.with(ServerSelectionController())
router!!.setRoot(
RouterTransaction.with(ServerSelectionController())
.pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler()))
.popChangeHandler(HorizontalChangeHandler())
)
}
}
@ -124,34 +131,38 @@ class MainActivity : BaseActivity(), ActionBarProvider {
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
fun checkIfWeAreSecure() {
val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
if (keyguardManager.isKeyguardSecure && appPreferences.isScreenLocked) {
if (!SecurityUtils.checkIfWeAreAuthenticated(appPreferences.screenLockTimeout)) {
if (router != null && router!!.getControllerWithTag(LockedController.TAG) == null) {
router!!.pushController(RouterTransaction.with(LockedController())
router!!.pushController(
RouterTransaction.with(LockedController())
.pushChangeHandler(VerticalChangeHandler())
.popChangeHandler(VerticalChangeHandler())
.tag(LockedController.TAG))
.tag(LockedController.TAG)
)
}
}
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
if (intent.hasExtra(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL)) {
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())
.popChangeHandler(HorizontalChangeHandler()))
.popChangeHandler(HorizontalChangeHandler())
)
} else {
ConductorRemapping.remapChatController(router!!, intent.getLongExtra(BundleKeys.KEY_INTERNAL_USER_ID, -1),
intent.getStringExtra(BundleKeys.KEY_ROOM_TOKEN), intent.extras!!, false)
ConductorRemapping.remapChatController(
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.regex.Pattern;
public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.UserItemViewHolder> implements
public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.UserItemViewHolder>
implements
IFilterable<String> {
private Participant participant;
@ -56,7 +57,8 @@ public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.User
@Nullable
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.userEntity = userEntity;
this.account = account;
@ -104,12 +106,14 @@ public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.User
}
@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);
if (adapter.hasFilter()) {
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));
} else {
holder.contactDisplayName.setText(participant.getName());
@ -117,21 +121,24 @@ public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.User
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);
DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(holder.avatarImageView.getController())
.setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(),
.setImageRequest(DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(),
participant.getUserId(), R.dimen.avatar_size), null))
.build();
holder.avatarImageView.setController(draweeController);
} else {
holder.avatarImageView.setVisibility(View.GONE);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) holder.linearLayout.getLayoutParams();
layoutParams.setMarginStart((int) NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext()
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) holder.linearLayout.getLayoutParams();
layoutParams.setMarginStart(
(int) NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext()
.getResources().getDimension(R.dimen.activity_horizontal_margin));
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START);
holder.linearLayout.setLayoutParams(layoutParams);
@ -141,10 +148,11 @@ public class AdvancedUserItem extends AbstractFlexibleItem<AdvancedUserItem.User
@Override
public boolean filter(String constraint) {
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 {
@BindView(R.id.name_text)

View File

@ -56,7 +56,9 @@ public class AppItem extends AbstractFlexibleItem<AppItem.AppItemViewHolder> {
public boolean equals(Object o) {
if (o instanceof AppItem) {
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());
}
@ -81,7 +83,8 @@ public class AppItem extends AbstractFlexibleItem<AppItem.AppItemViewHolder> {
}
@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) {
holder.iconImageView.setVisibility(View.VISIBLE);
holder.iconImageView.setImageDrawable(drawable);
@ -91,7 +94,8 @@ public class AppItem extends AbstractFlexibleItem<AppItem.AppItemViewHolder> {
if (position == 0) {
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,
spannableString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
@ -120,5 +124,4 @@ public class AppItem extends AbstractFlexibleItem<AppItem.AppItemViewHolder> {
ButterKnife.bind(this, view);
}
}
}

View File

@ -48,7 +48,8 @@ import java.util.List;
import java.util.regex.Pattern;
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 UserEntity userEntity;
@ -95,10 +96,12 @@ public class CallItem extends AbstractFlexibleItem<CallItem.RoomItemViewHolder>
}
@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()) {
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));
} else {
holder.roomDisplayName.setText(conversation.getDisplayName());
@ -107,7 +110,8 @@ public class CallItem extends AbstractFlexibleItem<CallItem.RoomItemViewHolder>
if (conversation.getLastPing() == 0) {
holder.roomLastPing.setText(R.string.nc_never);
} else {
holder.roomLastPing.setText(DateUtils.getRelativeTimeSpanString(conversation.getLastPing() * 1000L,
holder.roomLastPing.setText(
DateUtils.getRelativeTimeSpanString(conversation.getLastPing() * 1000L,
System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
}
@ -129,7 +133,8 @@ public class CallItem extends AbstractFlexibleItem<CallItem.RoomItemViewHolder>
DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(holder.avatarImageView.getController())
.setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(),
.setImageRequest(DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(userEntity.getBaseUrl(),
conversation.getName(),
R.dimen.avatar_size), null))
.build();
@ -152,16 +157,18 @@ public class CallItem extends AbstractFlexibleItem<CallItem.RoomItemViewHolder>
break;
default:
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
public boolean filter(String constraint) {
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 {

View File

@ -35,11 +35,11 @@ import butterknife.ButterKnife;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nextcloud.talk.models.json.conversations.Conversation;
import com.nextcloud.talk.R;
import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.models.database.UserEntity;
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.DisplayUtils;
import eu.davidea.flexibleadapter.FlexibleAdapter;
@ -51,10 +51,10 @@ import eu.davidea.viewholders.FlexibleViewHolder;
import java.util.List;
import java.util.regex.Pattern;
public class ConversationItem extends AbstractFlexibleItem<ConversationItem.ConversationItemViewHolder> implements
public class ConversationItem
extends AbstractFlexibleItem<ConversationItem.ConversationItemViewHolder> implements
IFilterable<String> {
private Conversation conversation;
private UserEntity userEntity;
private Context context;
@ -90,12 +90,14 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
}
@Override
public ConversationItemViewHolder createViewHolder(View view, FlexibleAdapter<IFlexible> adapter) {
public ConversationItemViewHolder createViewHolder(View view,
FlexibleAdapter<IFlexible> adapter) {
return new ConversationItemViewHolder(view, adapter);
}
@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 =
NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext();
@ -103,7 +105,8 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
if (adapter.hasFilter()) {
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));
} else {
holder.dialogName.setText(conversation.getDisplayName());
@ -118,15 +121,16 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
}
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 {
holder.dialogUnreadBubble.setBackground(context.getDrawable(R.drawable.bubble_circle_unread));
holder.dialogUnreadBubble.setBackground(
context.getDrawable(R.drawable.bubble_circle_unread));
}
} else {
holder.dialogUnreadBubble.setVisibility(View.GONE);
}
if (conversation.isHasPassword()) {
holder.passwordProtectedRoomImageView.setVisibility(View.VISIBLE);
} else {
@ -141,23 +145,29 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
if (conversation.getLastMessage() != null) {
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));
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());
} else {
String authorDisplayName = "";
conversation.getLastMessage().setActiveUser(userEntity);
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())) {
text = String.format(appContext.getString(R.string.nc_formatted_message_you),
conversation.getLastMessage().getLastMessageDisplayText());
} else {
authorDisplayName = !TextUtils.isEmpty(conversation.getLastMessage().getActorDisplayName()) ?
authorDisplayName =
!TextUtils.isEmpty(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),
authorDisplayName,
conversation.getLastMessage().getLastMessageDisplayText());
@ -202,7 +212,8 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground);
LayerDrawable layerDrawable = new LayerDrawable(layers);
holder.dialogAvatar.getHierarchy().setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable));
holder.dialogAvatar.getHierarchy()
.setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable));
shouldLoadAvatar = false;
}
@ -214,7 +225,9 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(holder.dialogAvatar.getController())
.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();
holder.dialogAvatar.setController(draweeController);
} else {
@ -222,7 +235,10 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
}
break;
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;
case ROOM_PUBLIC_CALL:
holder.dialogAvatar.getHierarchy().setImage(new BitmapDrawable(DisplayUtils
@ -238,7 +254,9 @@ public class ConversationItem extends AbstractFlexibleItem<ConversationItem.Conv
@Override
public boolean filter(String constraint) {
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 {

View File

@ -32,7 +32,8 @@ import eu.davidea.flexibleadapter.items.IFlexible;
import eu.davidea.viewholders.FlexibleViewHolder;
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 String title;
@ -63,13 +64,13 @@ public class GenericTextHeaderItem extends AbstractHeaderItem<GenericTextHeaderI
}
@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) {
Log.d(TAG, "We have payloads, so ignoring!");
} else {
holder.titleTextView.setText(title);
}
}
@Override
@ -90,5 +91,4 @@ public class GenericTextHeaderItem extends AbstractHeaderItem<GenericTextHeaderI
ButterKnife.bind(this, view);
}
}
}

View File

@ -45,7 +45,8 @@ public class MentionAutocompleteItem extends AbstractFlexibleItem<UserItem.UserI
private String source;
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.displayName = displayName;
this.source = source;
@ -84,22 +85,25 @@ public class MentionAutocompleteItem extends AbstractFlexibleItem<UserItem.UserI
}
@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);
}
@SuppressLint("SetTextI18n")
@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()) {
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));
if (holder.contactMentionId != null) {
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));
}
} else {
@ -110,7 +114,10 @@ public class MentionAutocompleteItem extends AbstractFlexibleItem<UserItem.UserI
}
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 {
String avatarId = objectId;
String avatarUrl = ApiUtils.getUrlForAvatarWithName(currentUser.getBaseUrl(),
@ -118,7 +125,8 @@ public class MentionAutocompleteItem extends AbstractFlexibleItem<UserItem.UserI
if (source.equals("guests")) {
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);
@ -135,6 +143,7 @@ public class MentionAutocompleteItem extends AbstractFlexibleItem<UserItem.UserI
public boolean filter(String constraint) {
return objectId != null && Pattern.compile(constraint,
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
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) {
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,
spannableString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

View File

@ -36,7 +36,8 @@ import eu.davidea.flexibleadapter.items.IFlexible;
import eu.davidea.viewholders.FlexibleViewHolder;
import java.util.List;
public class NotificationSoundItem extends AbstractFlexibleItem<NotificationSoundItem.NotificationSoundItemViewHolder> {
public class NotificationSoundItem
extends AbstractFlexibleItem<NotificationSoundItem.NotificationSoundItemViewHolder> {
private String notificationSoundName;
private String notificationSoundUri;
@ -65,12 +66,14 @@ public class NotificationSoundItem extends AbstractFlexibleItem<NotificationSoun
}
@Override
public NotificationSoundItemViewHolder createViewHolder(View view, FlexibleAdapter<IFlexible> adapter) {
public NotificationSoundItemViewHolder createViewHolder(View view,
FlexibleAdapter<IFlexible> adapter) {
return new NotificationSoundItemViewHolder(view, adapter);
}
@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);
if (adapter.isSelected(position)) {
@ -80,12 +83,15 @@ public class NotificationSoundItem extends AbstractFlexibleItem<NotificationSoun
}
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) {
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);
} 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);
}
}
@ -106,6 +112,4 @@ public class NotificationSoundItem extends AbstractFlexibleItem<NotificationSoun
ButterKnife.bind(this, view);
}
}
}

View File

@ -68,7 +68,8 @@ public class ProgressItem extends AbstractFlexibleItem<ProgressItem.ProgressView
}
@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();
holder.progressBar.setVisibility(View.GONE);
holder.progressMessage.setVisibility(View.VISIBLE);
@ -111,7 +112,6 @@ public class ProgressItem extends AbstractFlexibleItem<ProgressItem.ProgressView
return new ProgressViewHolder(view, adapter);
}
public enum StatusEnum {
MORE_TO_LOAD, //Default = should have an empty Payload
DISABLE_ENDLESS, //Endless is disabled because user has set limits
@ -133,9 +133,9 @@ public class ProgressItem extends AbstractFlexibleItem<ProgressItem.ProgressView
}
@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);
}
}
}

View File

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

View File

@ -82,12 +82,13 @@ public class MagicIncomingTextMessageViewHolder
public MagicIncomingTextMessageViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
this.itemView = itemView;
}
@Override
public void onBind(ChatMessage message) {
super.onBind(message);
@ -103,17 +104,20 @@ public class MagicIncomingTextMessageViewHolder
messageUserAvatarView.setVisibility(View.VISIBLE);
if (message.getActorType().equals("guests")) {
// 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);
Drawable[] layers = new Drawable[2];
layers[0] = context.getDrawable(R.drawable.ic_launcher_background);
layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground);
LayerDrawable layerDrawable = new LayerDrawable(layers);
messageUserAvatarView.getHierarchy().setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable));
messageUserAvatarView.getHierarchy()
.setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable));
} else if (message.getActorType().equals("bots")) {
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));
messageUserAvatarView.setVisibility(View.VISIBLE);
messageUserAvatarView.getHierarchy().setPlaceholderImage(drawable);
@ -147,7 +151,8 @@ public class MagicIncomingTextMessageViewHolder
itemView.setSelected(false);
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);
Spannable messageString = new SpannableString(message.getText());
@ -158,7 +163,8 @@ public class MagicIncomingTextMessageViewHolder
for (String key : messageParameters.keySet()) {
Map<String, String> individualHashMap = message.getMessageParameters().get(key);
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())) {
messageString =
DisplayUtils.searchAndReplaceWithMentionSpan(messageText.getContext(),
@ -178,17 +184,15 @@ public class MagicIncomingTextMessageViewHolder
userUtils.getUserById(message.getActiveUser().getUserId()),
R.xml.chip_others);
}
} else if (individualHashMap.get("type").equals("file")) {
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);
});
}
}
}
} else if (TextMatchers.isMessageWithSingleEmoticonOnly(message.getText())) {
textSize = (float) (textSize * 2.5);
layoutParams.setWrapBefore(true);

View File

@ -48,7 +48,8 @@ import java.util.Map;
import javax.inject.Inject;
@AutoInjector(NextcloudTalkApplication.class)
public class MagicOutcomingTextMessageViewHolder extends MessageHolders.OutcomingTextMessageViewHolder<ChatMessage> {
public class MagicOutcomingTextMessageViewHolder
extends MessageHolders.OutcomingTextMessageViewHolder<ChatMessage> {
@BindView(R.id.messageText)
EmojiTextView messageText;
@ -66,7 +67,9 @@ public class MagicOutcomingTextMessageViewHolder extends MessageHolders.Outcomin
public MagicOutcomingTextMessageViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
this.itemView = itemView;
}
@ -82,7 +85,8 @@ public class MagicOutcomingTextMessageViewHolder extends MessageHolders.Outcomin
itemView.setSelected(false);
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);
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()) {
Map<String, String> individualHashMap = message.getMessageParameters().get(key);
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 =
DisplayUtils.searchAndReplaceWithMentionSpan(messageText.getContext(),
messageString,
@ -102,14 +107,13 @@ public class MagicOutcomingTextMessageViewHolder extends MessageHolders.Outcomin
R.xml.chip_others);
} else if (individualHashMap.get("type").equals("file")) {
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);
});
}
}
}
} else if (TextMatchers.isMessageWithSingleEmoticonOnly(message.getText())) {
textSize = (float) (textSize * 2.5);
layoutParams.setWrapBefore(true);
@ -120,14 +124,18 @@ public class MagicOutcomingTextMessageViewHolder extends MessageHolders.Outcomin
Resources resources = NextcloudTalkApplication.Companion.getSharedApplication().getResources();
if (message.isGrouped) {
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.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);
} 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.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);
}

View File

@ -55,7 +55,8 @@ import javax.inject.Inject;
import okhttp3.OkHttpClient;
@AutoInjector(NextcloudTalkApplication.class)
public class MagicPreviewMessageViewHolder extends MessageHolders.IncomingImageMessageViewHolder<ChatMessage> {
public class MagicPreviewMessageViewHolder
extends MessageHolders.IncomingImageMessageViewHolder<ChatMessage> {
@BindView(R.id.messageText)
EmojiTextView messageText;
@ -69,7 +70,9 @@ public class MagicPreviewMessageViewHolder extends MessageHolders.IncomingImageM
public MagicPreviewMessageViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
}
@SuppressLint("SetTextI18n")
@ -92,7 +95,8 @@ public class MagicPreviewMessageViewHolder extends MessageHolders.IncomingImageM
layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground);
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) {
// it's a preview for a Nextcloud share
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")) {
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 {
fetchFileInformation("/" + message.getSelectedIndividualHashMap().get("path"), message.getActiveUser());
fetchFileInformation("/" + message.getSelectedIndividualHashMap().get("path"),
message.getActiveUser());
}
image.setOnClickListener(v -> {
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)) {
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.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
filesAppIntent.setPackage(context.getString(R.string.nc_import_accounts_from));
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);
} 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);
context.startActivity(browserIntent);
}
@ -166,7 +182,10 @@ public class MagicPreviewMessageViewHolder extends MessageHolders.IncomingImageM
if (davResponse.getData() != null) {
List<BrowserFile> browserFileList = (List<BrowserFile>) davResponse.getData();
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) {
}
});
}
}

View File

@ -38,7 +38,8 @@ import java.util.Map;
import javax.inject.Inject;
@AutoInjector(NextcloudTalkApplication.class)
public class MagicSystemMessageViewHolder extends MessageHolders.IncomingTextMessageViewHolder<ChatMessage> {
public class MagicSystemMessageViewHolder
extends MessageHolders.IncomingTextMessageViewHolder<ChatMessage> {
@Inject
AppPreferences appPreferences;
@ -48,7 +49,9 @@ public class MagicSystemMessageViewHolder extends MessageHolders.IncomingTextMes
public MagicSystemMessageViewHolder(View itemView) {
super(itemView);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
}
@Override
@ -60,7 +63,6 @@ public class MagicSystemMessageViewHolder extends MessageHolders.IncomingTextMes
int pressedColor;
int mentionColor;
pressedColor = normalColor;
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) {
for (String key : message.getMessageParameters().keySet()) {
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"))) {
messageString = DisplayUtils.searchAndColor(messageString, "@" + individualHashMap.get("name"), mentionColor);
if (individualHashMap != null && (individualHashMap.get("type").equals("user")
|| 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.stfalcon.chatkit.messages.MessageHolders;
public class MagicUnreadNoticeMessageViewHolder extends MessageHolders.SystemMessageViewHolder<ChatMessage> {
public class MagicUnreadNoticeMessageViewHolder
extends MessageHolders.SystemMessageViewHolder<ChatMessage> {
public MagicUnreadNoticeMessageViewHolder(View itemView) {
super(itemView);

View File

@ -69,9 +69,10 @@ public interface NcApi {
*/
@GET
Observable<ResponseBody> getContactsWithSearchParam(@Header("Authorization") String authorization, @Url String url,
@Nullable @Query("shareTypes[]") List<String> listOfShareTypes, @QueryMap Map<String, Object> options);
Observable<ResponseBody> getContactsWithSearchParam(@Header("Authorization") String authorization,
@Url String url,
@Nullable @Query("shareTypes[]") List<String> listOfShareTypes,
@QueryMap Map<String, Object> options);
/*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room
@ -106,10 +107,10 @@ public interface NcApi {
@FormUrlEncoded
@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);
/*
QueryMap items are as follows:
- "newParticipant" : "user"
@ -117,76 +118,91 @@ public interface NcApi {
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /room/roomToken/participants
*/
@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);
// also used for removing a guest from a conversation
@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
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
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
*/
@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
*/
@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
*/
@DELETE
Observable<GenericOverall> makeRoomPrivate(@Header("Authorization") String authorization, @Url String url);
Observable<GenericOverall> makeRoomPrivate(@Header("Authorization") String authorization,
@Url String url);
@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
*/
@GET
Observable<ParticipantsOverall> getPeersForCall(@Header("Authorization") String authorization, @Url String url);
Observable<ParticipantsOverall> getPeersForCall(@Header("Authorization") String authorization,
@Url String url);
@FormUrlEncoded
@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
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
*/
@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
*/
@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
*/
@POST
Observable<GenericOverall> pingCall(@Nullable @Header("Authorization") String authorization, @Url String url);
Observable<GenericOverall> pingCall(@Nullable @Header("Authorization") String authorization,
@Url String url);
@GET
Observable<SignalingSettingsOverall> getSignalingSettings(@Nullable @Header("Authorization") String authorization,
Observable<SignalingSettingsOverall> getSignalingSettings(
@Nullable @Header("Authorization") String authorization,
@Url String url);
/*
@ -197,14 +213,16 @@ public interface NcApi {
*/
@FormUrlEncoded
@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);
/*
Server URL is: baseUrl + ocsApiVersion + spreedApiVersion + /signaling
*/
@GET
Observable<SignalingOverall> pullSignalingMessages(@Nullable @Header("Authorization") String authorization, @Url
Observable<SignalingOverall> pullSignalingMessages(
@Nullable @Header("Authorization") String authorization, @Url
String
url);
@ -216,7 +234,8 @@ public interface NcApi {
*/
@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
@ -236,7 +255,8 @@ public interface NcApi {
*/
@POST
Observable<PushRegistrationOverall> registerDeviceForNotificationsWithNextcloud(@Header("Authorization")
Observable<PushRegistrationOverall> registerDeviceForNotificationsWithNextcloud(
@Header("Authorization")
String authorization,
@Url String url,
@QueryMap Map<String,
@ -252,7 +272,6 @@ public interface NcApi {
Observable<Void> registerDeviceForNotificationsWithProxy(@Url String url,
@FieldMap Map<String, String> fields);
/*
QueryMap items are as follows:
- "deviceIdentifier": "{{deviceIdentifier}}",
@ -265,11 +284,13 @@ public interface NcApi {
@FormUrlEncoded
@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);
@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:
@ -279,7 +300,8 @@ public interface NcApi {
- "lastKnownMessageId", int, use one from X-Chat-Last-Given
*/
@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);
/*
@ -290,23 +312,27 @@ public interface NcApi {
@FormUrlEncoded
@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("actorDisplayName") String actorDisplayName);
@GET
Observable<MentionOverall> getMentionAutocompleteSuggestions(@Header("Authorization") String authorization,
Observable<MentionOverall> getMentionAutocompleteSuggestions(
@Header("Authorization") String authorization,
@Url String url, @Query("search") String query,
@Nullable @Query("limit") Integer limit);
// Url is: /api/{apiVersion}/room/{token}/pin
@POST
Observable<GenericOverall> addConversationToFavorites(@Header("Authorization") String authorization,
Observable<GenericOverall> addConversationToFavorites(
@Header("Authorization") String authorization,
@Url String url);
// Url is: /api/{apiVersion}/room/{token}/favorites
@DELETE
Observable<GenericOverall> removeConversationFromFavorites(@Header("Authorization") String authorization,
Observable<GenericOverall> removeConversationFromFavorites(
@Header("Authorization") String authorization,
@Url String url);
@GET
@ -315,16 +341,18 @@ public interface NcApi {
@FormUrlEncoded
@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
@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
@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("shareWith") String roomToken,
@Field("shareType") String shareType);
@ -334,5 +362,4 @@ public interface NcApi {
Observable<GenericOverall> setLobbyForConversation(@Header("Authorization") String authorization,
@Url String url, @Field("viewState") Integer state,
@Field("timer") Long timer);
}

View File

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

View File

@ -25,9 +25,9 @@ import android.text.Editable;
import android.text.Spanned;
import android.widget.EditText;
import com.facebook.widget.text.span.BetterImageSpan;
import com.nextcloud.talk.models.json.mention.Mention;
import com.nextcloud.talk.R;
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.MagicCharPolicy;
import com.nextcloud.talk.utils.text.Spans;

View File

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

View File

@ -103,7 +103,9 @@ public class BrowserController extends BaseController implements ListingInterfac
public BrowserController(Bundle args) {
super();
setHasOptionsMenu(true);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
browserType = Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_BROWSER_TYPE()));
activeUser = Parcels.unwrap(args.getParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY()));
roomToken = args.getString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN());
@ -225,7 +227,8 @@ public class BrowserController extends BaseController implements ListingInterfac
listingAbstractClass.cancelAllJobs();
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
@ -252,7 +255,6 @@ public class BrowserController extends BaseController implements ListingInterfac
getActivity().runOnUiThread(() -> {
adapter.notifyDataSetChanged();
changeEnabledStatusForBarItems(true);
});
}
}
@ -314,7 +316,8 @@ public class BrowserController extends BaseController implements ListingInterfac
fastScroller.setBubbleTextCreator(position -> {
IFlexible abstractFlexibleItem = adapter.getItem(position);
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 {
return "";
}

View File

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

View File

@ -34,7 +34,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
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
@Setter

View File

@ -34,7 +34,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
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
@Setter

View File

@ -34,7 +34,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
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
@Setter

View File

@ -34,7 +34,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
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
@Setter

View File

@ -34,7 +34,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
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
@Setter

View File

@ -35,7 +35,8 @@ public abstract class ListingAbstractClass {
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() {
handler.removeCallbacksAndMessages(null);

View File

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

View File

@ -42,11 +42,14 @@ public class ReadFilesystemOperation {
private final int depth;
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();
okHttpClientBuilder.followRedirects(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.basePath = currentUser.getBaseUrl() + DavUtils.DAV_PATH + currentUser.getUserId();
this.url = basePath + path;
@ -84,7 +87,6 @@ public class ReadFilesystemOperation {
e.printStackTrace();
}
remoteFiles.add(BrowserFile.getModelFromResponse(rootElement[0],
rootElement[0].getHref().toString().substring(basePath.length())));
for (Response memberElement : memberElements) {
@ -95,5 +97,4 @@ public class ReadFilesystemOperation {
davResponse.setData(remoteFiles);
return davResponse;
}
}

View File

@ -36,9 +36,6 @@ import autodagger.AutoInjector;
import butterknife.BindView;
import com.bluelinelabs.conductor.RouterTransaction;
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.api.NcApi;
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.SignalingSettingsWorker;
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.utils.ApiUtils;
import com.nextcloud.talk.utils.ClosedInterfaceImpl;
@ -67,7 +67,6 @@ import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
@AutoInjector(NextcloudTalkApplication.class)
public class AccountVerificationController extends BaseController {
@ -134,7 +133,9 @@ public class AccountVerificationController extends BaseController {
@Override
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
if (getActivity() != null) {
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
@ -144,7 +145,8 @@ public class AccountVerificationController extends BaseController {
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))) {
determineBaseUrlProtocol(true);
} else {
@ -190,7 +192,8 @@ public class AccountVerificationController extends BaseController {
}
if (isAccountImport) {
getRouter().replaceTopController(RouterTransaction.with(new WebViewLoginController(baseUrl,
getRouter().replaceTopController(
RouterTransaction.with(new WebViewLoginController(baseUrl,
false, username, ""))
.pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new HorizontalChangeHandler()));
@ -232,8 +235,10 @@ public class AccountVerificationController extends BaseController {
@Override
public void onError(Throwable e) {
if (getActivity() != null && getResources() != null) {
getActivity().runOnUiThread(() -> progressText.setText(String.format(getResources().getString(
R.string.nc_nextcloud_talk_app_not_installed), getResources().getString(R.string.nc_app_name))));
getActivity().runOnUiThread(
() -> progressText.setText(String.format(getResources().getString(
R.string.nc_nextcloud_talk_app_not_installed),
getResources().getString(R.string.nc_app_name))));
}
ApplicationWideMessageHolder.getInstance().setMessageType(
@ -268,7 +273,8 @@ public class AccountVerificationController extends BaseController {
if (new ClosedInterfaceImpl().isGooglePlayServicesAvailable()) {
registerForPush();
} else {
getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
getActivity().runOnUiThread(
() -> progressText.setText(progressText.getText().toString() + "\n" +
getResources().getString(R.string.nc_push_disabled)));
fetchAndStoreCapabilities();
}
@ -281,7 +287,6 @@ public class AccountVerificationController extends BaseController {
getResources().getString(
R.string.nc_display_name_not_stored));
abortVerification();
}
@Override
@ -318,7 +323,8 @@ public class AccountVerificationController extends BaseController {
storeProfile(displayName, userProfileOverall.getOcs().getData().getUserId());
} else {
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)));
}
abortVerification();
@ -328,11 +334,11 @@ public class AccountVerificationController extends BaseController {
@Override
public void onError(Throwable e) {
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)));
}
abortVerification();
}
@Override
@ -343,22 +349,27 @@ public class AccountVerificationController extends BaseController {
}
private void registerForPush() {
OneTimeWorkRequest pushRegistrationWork = new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
OneTimeWorkRequest pushRegistrationWork =
new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
WorkManager.getInstance().enqueue(pushRegistrationWork);
}
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(EventStatus eventStatus) {
if (eventStatus.getEventType().equals(EventStatus.EventType.PUSH_REGISTRATION)) {
if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood() && getActivity() != null) {
getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
if (internalAccountId == eventStatus.getUserId()
&& !eventStatus.isAllGood()
&& getActivity() != null) {
getActivity().runOnUiThread(
() -> progressText.setText(progressText.getText().toString() + "\n" +
getResources().getString(R.string.nc_push_disabled)));
}
fetchAndStoreCapabilities();
} else if (eventStatus.getEventType().equals(EventStatus.EventType.CAPABILITIES_FETCH)) {
if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood()) {
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)));
}
abortVerification();
@ -368,14 +379,14 @@ public class AccountVerificationController extends BaseController {
} else if (eventStatus.getEventType().equals(EventStatus.EventType.SIGNALING_SETTINGS)) {
if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood()) {
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)));
}
}
proceedWithLogin();
}
}
private void fetchAndStoreCapabilities() {
@ -383,7 +394,8 @@ public class AccountVerificationController extends BaseController {
.putLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), internalAccountId)
.build();
OneTimeWorkRequest pushNotificationWork = new OneTimeWorkRequest.Builder(CapabilitiesWorker.class)
OneTimeWorkRequest pushNotificationWork =
new OneTimeWorkRequest.Builder(CapabilitiesWorker.class)
.setInputData(userData)
.build();
WorkManager.getInstance().enqueue(pushNotificationWork);
@ -394,7 +406,8 @@ public class AccountVerificationController extends BaseController {
.putLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), internalAccountId)
.build();
OneTimeWorkRequest signalingSettings = new OneTimeWorkRequest.Builder(SignalingSettingsWorker.class)
OneTimeWorkRequest signalingSettings =
new OneTimeWorkRequest.Builder(SignalingSettingsWorker.class)
.setInputData(userData)
.build();
WorkManager.getInstance().enqueue(signalingSettings);
@ -422,7 +435,6 @@ public class AccountVerificationController extends BaseController {
}
}
@Override
protected void onDestroyView(@NonNull View view) {
super.onDestroyView(view);
@ -471,8 +483,6 @@ public class AccountVerificationController extends BaseController {
if (getActivity() != null) {
getRouter().popToRoot();
}
} else {
if (userUtils.anyUserExists()) {
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.interfaces.DraweeController;
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.api.NcApi;
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.SessionDescriptionSendEvent;
import com.nextcloud.talk.events.WebSocketCommunicationEvent;
import com.nextcloud.talk.models.ExternalSignalingServer;
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.DisplayUtils;
import com.nextcloud.talk.utils.NotificationUtils;
@ -258,14 +265,11 @@ public class CallController extends BaseController {
private MediaPlayer mediaPlayer;
@Parcel
public enum CallStatus {
CALLING, CALLING_TIMEOUT, ESTABLISHED, IN_CONVERSATION, RECONNECTING, OFFLINE, LEAVING, PUBLISHER_FAILED
}
public CallController(Bundle args) {
super();
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
roomId = args.getString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), "");
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(), "");
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(), "");
@ -302,7 +307,8 @@ public class CallController extends BaseController {
if (camera2EnumeratorIsSupported) {
cameraEnumerator = new Camera2Enumerator(getActivity());
} else {
cameraEnumerator = new Camera1Enumerator(MagicWebRTCUtils.shouldEnableVideoHardwareAcceleration());
cameraEnumerator =
new Camera1Enumerator(MagicWebRTCUtils.shouldEnableVideoHardwareAcceleration());
}
}
}
@ -371,15 +377,21 @@ public class CallController extends BaseController {
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(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
sdpConstraintsForMCU.mandatory.add(
new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "false"));
sdpConstraintsForMCU.mandatory.add(
new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
sdpConstraintsForMCU.optional.add(new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true"));
sdpConstraintsForMCU.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
sdpConstraintsForMCU.optional.add(
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"));
if (!isVoiceOnlyCall) {
@ -443,7 +455,6 @@ public class CallController extends BaseController {
}
}
private void checkPermissions() {
if (isVoiceOnlyCall) {
onMicrophoneClick();
@ -454,11 +465,11 @@ public class CallController extends BaseController {
onRequestPermissionsResult(100, PERMISSIONS_CALL, new int[] { 1, 1 });
}
}
}
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)
@ -485,11 +496,11 @@ public class CallController extends BaseController {
if (!isConnectionEstablished()) {
fetchSignalingSettings();
}
} else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(),
} else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(
getActivity(),
PERMISSIONS_CALL)) {
checkIfSomeAreApproved();
}
}
private void checkIfSomeAreApproved() {
@ -502,12 +513,14 @@ public class CallController extends BaseController {
cameraSwitchButton.setVisibility(View.VISIBLE);
}
if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA)) {
if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(),
PERMISSIONS_CAMERA)) {
if (!videoOn) {
onCameraClick();
}
} 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);
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))) {
checkIfSomeAreApproved();
} else if (!isConnectionEstablished()) {
@ -545,22 +559,24 @@ public class CallController extends BaseController {
}
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 + ", "
+ "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.BLUETOOTH));
if (shouldDisableProximityLock) {
powerManagerUtils.updatePhoneState(PowerManagerUtils.PhoneState.WITHOUT_PROXIMITY_SENSOR_LOCK);
powerManagerUtils.updatePhoneState(
PowerManagerUtils.PhoneState.WITHOUT_PROXIMITY_SENSOR_LOCK);
} else {
powerManagerUtils.updatePhoneState(PowerManagerUtils.PhoneState.WITH_PROXIMITY_SENSOR_LOCK);
}
}
private void cameraInitialization() {
videoCapturer = createCameraCapturer(cameraEnumerator);
@ -572,7 +588,6 @@ public class CallController extends BaseController {
localVideoTrack.setEnabled(false);
localVideoTrack.addSink(pipVideoView);
}
}
private void microphoneInitialization() {
@ -599,7 +614,6 @@ public class CallController extends BaseController {
}
}
// Front facing camera not found, try something else
Logging.d(TAG, "Looking for other cameras.");
for (String deviceName : deviceNames) {
@ -638,16 +652,19 @@ public class CallController extends BaseController {
if (audioManager != null) {
audioManager.toggleUseSpeakerphone();
if (audioManager.isSpeakerphoneAutoOn()) {
callControlEnableSpeaker.getHierarchy().setPlaceholderImage(R.drawable.ic_volume_up_white_24dp);
callControlEnableSpeaker.getHierarchy()
.setPlaceholderImage(R.drawable.ic_volume_up_white_24dp);
} 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)
public void onMicrophoneClick() {
if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_MICROPHONE)) {
if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(),
PERMISSIONS_MICROPHONE)) {
if (getActivity() != null && !appPreferences.getPushToTalkIntroShown()) {
spotlightView = new SpotlightView.Builder(getActivity())
@ -679,7 +696,8 @@ public class CallController extends BaseController {
if (audioOn) {
microphoneControlButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_white_24px);
} else {
microphoneControlButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_off_white_24px);
microphoneControlButton.getHierarchy()
.setPlaceholderImage(R.drawable.ic_mic_off_white_24px);
}
toggleMedia(audioOn, false);
@ -692,8 +710,8 @@ public class CallController extends BaseController {
if (isVoiceOnlyCall && !isConnectionEstablished()) {
fetchSignalingSettings();
}
} else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(),
} else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(
getActivity(),
PERMISSIONS_MICROPHONE)) {
// Microphone permission is permanently denied so we cannot request it normally.
@ -717,7 +735,8 @@ public class CallController extends BaseController {
@OnClick(R.id.call_control_camera)
public void onCameraClick() {
if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA)) {
if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(),
PERMISSIONS_CAMERA)) {
videoOn = !videoOn;
if (videoOn) {
@ -726,12 +745,14 @@ public class CallController extends BaseController {
cameraSwitchButton.setVisibility(View.VISIBLE);
}
} 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);
}
toggleMedia(videoOn, true);
} else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(),
} else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(
getActivity(),
PERMISSIONS_CAMERA)) {
// Camera permission is permanently denied so we cannot request it normally.
OpenAppDetailsDialogFragment.show(
@ -745,7 +766,6 @@ public class CallController extends BaseController {
onRequestPermissionsResult(100, PERMISSIONS_CAMERA, new int[] { 1 });
}
}
}
@OnClick({ R.id.call_control_switch_camera, R.id.pip_video_view })
@ -814,17 +834,17 @@ public class CallController extends BaseController {
}
} else {
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));
break;
}
}
}
}
}
private void animateCallControls(boolean show, long startDelay) {
if (isVoiceOnlyCall) {
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();
if (!TextUtils.isEmpty(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer()) &&
!TextUtils.isEmpty(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket())) {
if (!TextUtils.isEmpty(
signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer()) &&
!TextUtils.isEmpty(signalingSettingsOverall.getOcs()
.getSettings()
.getExternalSignalingTicket())) {
externalSignalingServer = new ExternalSignalingServer();
externalSignalingServer.setExternalSignalingServer(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer());
externalSignalingServer.setExternalSignalingTicket(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket());
externalSignalingServer.setExternalSignalingServer(
signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer());
externalSignalingServer.setExternalSignalingTicket(
signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket());
hasExternalSignalingServer = true;
} else {
hasExternalSignalingServer = false;
@ -954,7 +978,8 @@ public class CallController extends BaseController {
if (!conversationUser.getUserId().equals("?")) {
try {
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())
.subscribe();
} catch (IOException exception) {
@ -963,9 +988,11 @@ public class CallController extends BaseController {
}
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++) {
iceServer = signalingSettingsOverall.getOcs().getSettings().getStunServers().get(i);
iceServer =
signalingSettingsOverall.getOcs().getSettings().getStunServers().get(i);
if (TextUtils.isEmpty(iceServer.getUsername()) || TextUtils.isEmpty(iceServer
.getCredential())) {
iceServers.add(new PeerConnection.IceServer(iceServer.getUrl()));
@ -977,9 +1004,11 @@ public class CallController extends BaseController {
}
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++) {
iceServer = signalingSettingsOverall.getOcs().getSettings().getTurnServers().get(i);
iceServer =
signalingSettingsOverall.getOcs().getSettings().getTurnServers().get(i);
for (int j = 0; j < iceServer.getUrls().size(); j++) {
if (TextUtils.isEmpty(iceServer.getUsername()) || TextUtils.isEmpty(iceServer
.getCredential())) {
@ -1154,14 +1183,18 @@ public class CallController extends BaseController {
urlToken = roomToken;
}
if (!conversationUser.hasSpreedFeatureCapability("no-ping") && !TextUtils.isEmpty(roomId)) {
NotificationUtils.INSTANCE.cancelExistingNotificationsForRoom(getApplicationContext(), conversationUser, roomId);
if (!conversationUser.hasSpreedFeatureCapability("no-ping") && !TextUtils.isEmpty(
roomId)) {
NotificationUtils.INSTANCE.cancelExistingNotificationsForRoom(
getApplicationContext(), conversationUser, roomId);
} else if (!TextUtils.isEmpty(roomToken)) {
NotificationUtils.INSTANCE.cancelExistingNotificationsForRoom(getApplicationContext(), conversationUser, roomToken);
NotificationUtils.INSTANCE.cancelExistingNotificationsForRoom(
getApplicationContext(), conversationUser, roomToken);
}
if (!hasExternalSignalingServer) {
ncApi.pullSignalingMessages(credentials, ApiUtils.getUrlForSignaling(baseUrl, urlToken))
ncApi.pullSignalingMessages(credentials,
ApiUtils.getUrlForSignaling(baseUrl, urlToken))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.repeatWhen(observable -> observable)
@ -1176,9 +1209,11 @@ public class CallController extends BaseController {
@Override
public void onNext(SignalingOverall signalingOverall) {
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 {
receivedSignalingMessage(signalingOverall.getOcs().getSignalings().get(i));
receivedSignalingMessage(
signalingOverall.getOcs().getSignalings().get(i));
} catch (IOException e) {
Log.e(TAG, "Failed to process received signaling" +
" message");
@ -1197,8 +1232,6 @@ public class CallController extends BaseController {
dispose(signalingDisposable);
}
});
}
}
}
@ -1275,14 +1308,17 @@ public class CallController extends BaseController {
break;
case "participantsUpdate":
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;
case "signalingMessage":
processMessage((NCSignalingMessage) webSocketClient.getJobWithId(Integer.valueOf(webSocketCommunicationEvent.getHashMap().get("jobId"))));
processMessage((NCSignalingMessage) webSocketClient.getJobWithId(
Integer.valueOf(webSocketCommunicationEvent.getHashMap().get("jobId"))));
break;
case "peerReadyForRequestingOffer":
webSocketClient.requestOfferForSessionIdWithType(webSocketCommunicationEvent.getHashMap().get("sessionId"), "video");
webSocketClient.requestOfferForSessionIdWithType(
webSocketCommunicationEvent.getHashMap().get("sessionId"), "video");
break;
}
}
@ -1319,7 +1355,8 @@ public class CallController extends BaseController {
if ("usersInRoom".equals(messageType)) {
processUsersInRoom((List<HashMap<String, Object>>) signaling.getMessageWrapper());
} else if ("message".equals(messageType)) {
NCSignalingMessage ncSignalingMessage = LoganSquare.parse(signaling.getMessageWrapper().toString(),
NCSignalingMessage ncSignalingMessage =
LoganSquare.parse(signaling.getMessageWrapper().toString(),
NCSignalingMessage.class);
processMessage(ncSignalingMessage);
} else {
@ -1328,13 +1365,15 @@ public class CallController extends BaseController {
}
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 =
getPeerConnectionWrapperForSessionIdAndType(ncSignalingMessage.getFrom(),
ncSignalingMessage.getRoomType(), false);
String type = null;
if (ncSignalingMessage.getPayload() != null && ncSignalingMessage.getPayload().getType() != null) {
if (ncSignalingMessage.getPayload() != null
&& ncSignalingMessage.getPayload().getType() != null) {
type = ncSignalingMessage.getPayload().getType();
} else if (ncSignalingMessage.getType() != null) {
type = ncSignalingMessage.getType();
@ -1359,7 +1398,8 @@ public class CallController extends BaseController {
sessionDescriptionStringWithPreferredCodec);
if (magicPeerConnectionWrapper.getPeerConnection() != null) {
magicPeerConnectionWrapper.getPeerConnection().setRemoteDescription(magicPeerConnectionWrapper
magicPeerConnectionWrapper.getPeerConnection()
.setRemoteDescription(magicPeerConnectionWrapper
.getMagicSdpObserver(), sessionDescriptionWithPreferredCodec);
}
break;
@ -1423,7 +1463,6 @@ public class CallController extends BaseController {
localAudioTrack = null;
localVideoTrack = null;
if (TextUtils.isEmpty(credentials) && hasExternalSignalingServer) {
WebSocketConnectionHelper.deleteExternalSignalingInstanceForUserEntity(-1);
}
@ -1455,7 +1494,8 @@ public class CallController extends BaseController {
if (isMultiSession) {
if (shutDownView && getActivity() != null) {
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();
}
} else {
@ -1476,7 +1516,8 @@ public class CallController extends BaseController {
}
private void leaveRoom(boolean shutDownView) {
ncApi.leaveRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken))
ncApi.leaveRoom(credentials,
ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<GenericOverall>() {
@ -1555,7 +1596,8 @@ public class CallController extends BaseController {
hasMCU = hasExternalSignalingServer && webSocketClient != null && webSocketClient.hasMCU();
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)) {
@ -1582,7 +1624,8 @@ public class CallController extends BaseController {
for (Participant participant : participantsOverall.getOcs().getData()) {
participantMap.put(participant.getSessionId(), participant);
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);
}
private MagicPeerConnectionWrapper getPeerConnectionWrapperForSessionId(String sessionId, String type) {
private MagicPeerConnectionWrapper getPeerConnectionWrapperForSessionId(String sessionId,
String type) {
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);
}
}
@ -1614,22 +1659,25 @@ public class CallController extends BaseController {
return null;
}
private MagicPeerConnectionWrapper getPeerConnectionWrapperForSessionIdAndType(String sessionId, String type, boolean publisher) {
private MagicPeerConnectionWrapper getPeerConnectionWrapperForSessionIdAndType(String sessionId,
String type, boolean publisher) {
MagicPeerConnectionWrapper magicPeerConnectionWrapper;
if ((magicPeerConnectionWrapper = getPeerConnectionWrapperForSessionId(sessionId, type)) != null) {
if ((magicPeerConnectionWrapper = getPeerConnectionWrapperForSessionId(sessionId, type))
!= null) {
return magicPeerConnectionWrapper;
} else {
if (hasMCU && publisher) {
magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory,
iceServers, sdpConstraintsForMCU, sessionId, callSession, localMediaStream, true, true, type);
iceServers, sdpConstraintsForMCU, sessionId, callSession, localMediaStream, true, true,
type);
} else if (hasMCU) {
magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory,
iceServers, sdpConstraints, sessionId, callSession, null, false, true, type);
} else {
if (!"screen".equals(type)) {
magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory,
iceServers, sdpConstraints, sessionId, callSession, localMediaStream, false, false, type);
iceServers, sdpConstraints, sessionId, callSession, localMediaStream, false, false,
type);
} else {
magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory,
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<>();
for (MagicPeerConnectionWrapper magicPeerConnectionWrapper : magicPeerConnectionWrapperList) {
if (magicPeerConnectionWrapper.getSessionId().equals(sessionId)) {
@ -1660,7 +1709,8 @@ public class CallController extends BaseController {
private void endPeerConnection(String sessionId, boolean justScreen) {
List<MagicPeerConnectionWrapper> magicPeerConnectionWrappers;
MagicPeerConnectionWrapper magicPeerConnectionWrapper;
if (!(magicPeerConnectionWrappers = getPeerConnectionWrapperListForSessionId(sessionId)).isEmpty()
if (!(magicPeerConnectionWrappers =
getPeerConnectionWrapperListForSessionId(sessionId)).isEmpty()
&& getActivity() != null) {
for (int i = 0; i < magicPeerConnectionWrappers.size(); i++) {
magicPeerConnectionWrapper = magicPeerConnectionWrappers.get(i);
@ -1694,12 +1744,13 @@ public class CallController extends BaseController {
@Subscribe(threadMode = ThreadMode.MAIN)
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) {
remoteRenderersLayout.setOrientation(LinearLayout.HORIZONTAL);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
} else if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_PORTRAIT) {
remoteRenderersLayout.setOrientation(LinearLayout.VERTICAL);
}
@ -1707,14 +1758,16 @@ public class CallController extends BaseController {
}
private void setPipVideoViewDimensions() {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) pipVideoView.getLayoutParams();
FrameLayout.LayoutParams layoutParams =
(FrameLayout.LayoutParams) pipVideoView.getLayoutParams();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
remoteRenderersLayout.setOrientation(LinearLayout.HORIZONTAL);
layoutParams.height = (int) getResources().getDimension(R.dimen.large_preview_dimension);
layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT;
pipVideoView.setLayoutParams(layoutParams);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
} else if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_PORTRAIT) {
remoteRenderersLayout.setOrientation(LinearLayout.VERTICAL);
layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams.width = (int) getResources().getDimension(R.dimen.large_preview_dimension);
@ -1724,18 +1777,22 @@ public class CallController extends BaseController {
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(PeerConnectionEvent peerConnectionEvent) {
if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent.PeerConnectionEventType
if (peerConnectionEvent.getPeerConnectionEventType()
.equals(PeerConnectionEvent.PeerConnectionEventType
.PEER_CLOSED)) {
endPeerConnection(peerConnectionEvent.getSessionId(), peerConnectionEvent.getVideoStreamType().equals("screen"));
endPeerConnection(peerConnectionEvent.getSessionId(),
peerConnectionEvent.getVideoStreamType().equals("screen"));
} else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.PeerConnectionEventType.SENSOR_FAR) ||
peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.PeerConnectionEventType.SENSOR_NEAR)) {
if (!isVoiceOnlyCall) {
boolean enableVideo = peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
boolean enableVideo =
peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.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
&& enableVideo != localVideoTrack.enabled()) {
toggleMedia(enableVideo, true);
@ -1743,16 +1800,20 @@ public class CallController extends BaseController {
}
} else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.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
.PeerConnectionEventType.VIDEO_CHANGE) && !isVoiceOnlyCall) {
gotAudioOrVideoChange(true, peerConnectionEvent.getSessionId() + "+" + peerConnectionEvent.getVideoStreamType(),
gotAudioOrVideoChange(true,
peerConnectionEvent.getSessionId() + "+" + peerConnectionEvent.getVideoStreamType(),
peerConnectionEvent.getChangeValue());
} else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
.PeerConnectionEventType.AUDIO_CHANGE)) {
gotAudioOrVideoChange(false, peerConnectionEvent.getSessionId() + "+" + peerConnectionEvent.getVideoStreamType(),
gotAudioOrVideoChange(false,
peerConnectionEvent.getSessionId() + "+" + peerConnectionEvent.getVideoStreamType(),
peerConnectionEvent.getChangeValue());
} else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent.PeerConnectionEventType.PUBLISHER_FAILED)) {
} else if (peerConnectionEvent.getPeerConnectionEventType()
.equals(PeerConnectionEvent.PeerConnectionEventType.PUBLISHER_FAILED)) {
currentCallStatus = CallStatus.PUBLISHER_FAILED;
webSocketClient.clearResumeId();
hangup(false);
@ -1797,7 +1858,6 @@ public class CallController extends BaseController {
});
break;
}
}
}
@ -1806,14 +1866,17 @@ public class CallController extends BaseController {
if (mediaStreamEvent.getMediaStream() != null) {
setupVideoStreamForLayout(mediaStreamEvent.getMediaStream(), mediaStreamEvent.getSession(),
mediaStreamEvent.getMediaStream().videoTracks != null
&& mediaStreamEvent.getMediaStream().videoTracks.size() > 0, mediaStreamEvent.getVideoStreamType());
&& mediaStreamEvent.getMediaStream().videoTracks.size() > 0,
mediaStreamEvent.getVideoStreamType());
} else {
setupVideoStreamForLayout(null, mediaStreamEvent.getSession(), false, mediaStreamEvent.getVideoStreamType());
setupVideoStreamForLayout(null, mediaStreamEvent.getSession(), false,
mediaStreamEvent.getVideoStreamType());
}
}
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(SessionDescriptionSendEvent sessionDescriptionSend) throws IOException {
public void onMessageEvent(SessionDescriptionSendEvent sessionDescriptionSend)
throws IOException {
NCMessageWrapper ncMessageWrapper = new NCMessageWrapper();
ncMessageWrapper.setEv("message");
ncMessageWrapper.setSessionId(callSession);
@ -1831,17 +1894,16 @@ public class CallController extends BaseController {
ncMessagePayload.setIceCandidate(sessionDescriptionSend.getNcIceCandidate());
}
// Set all we need
ncSignalingMessage.setPayload(ncMessagePayload);
ncMessageWrapper.setSignalingMessage(ncSignalingMessage);
if (!hasExternalSignalingServer) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{")
.append("\"fn\":\"")
.append(StringEscapeUtils.escapeJson(LoganSquare.serialize(ncMessageWrapper.getSignalingMessage()))).append("\"")
.append(StringEscapeUtils.escapeJson(
LoganSquare.serialize(ncMessageWrapper.getSignalingMessage()))).append("\"")
.append(",")
.append("\"sessionId\":")
.append("\"").append(StringEscapeUtils.escapeJson(callSession)).append("\"")
@ -1925,7 +1987,8 @@ public class CallController extends BaseController {
DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(avatarImageView.getController())
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(baseUrl,
.setImageRequest(
DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(baseUrl,
userId,
R.dimen.avatar_size_big), null))
.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;
if (remoteRenderersLayout.findViewWithTag(session) == null) {
setupNewPeerLayout(session, videoStreamType);
isInitialLayoutSetupForPeer = true;
}
RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(session + "+" + videoStreamType);
RelativeLayout relativeLayout =
remoteRenderersLayout.findViewWithTag(session + "+" + videoStreamType);
SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id.surface_view);
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.addSink(surfaceViewRenderer);
@ -1996,7 +2064,8 @@ public class CallController extends BaseController {
}
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(() -> {
RelativeLayout relativeLayout = (RelativeLayout)
getActivity().getLayoutInflater().inflate(R.layout.call_item, remoteRenderersLayout,
@ -2016,7 +2085,9 @@ public class CallController extends BaseController {
if (hasExternalSignalingServer) {
gotNick(session, webSocketClient.getDisplayNameForSession(session), false, type);
} else {
gotNick(session, getPeerConnectionWrapperForSessionIdAndType(session, type, false).getNick(), false, type);
gotNick(session,
getPeerConnectionWrapperForSessionIdAndType(session, type, false).getNick(), false,
type);
}
if ("video".equals(type)) {
@ -2200,7 +2271,6 @@ public class CallController extends BaseController {
}
}
if (conversationView != null) {
if (conversationView.getVisibility() != View.INVISIBLE) {
conversationView.setVisibility(View.INVISIBLE);
@ -2240,20 +2310,24 @@ public class CallController extends BaseController {
private void playCallingSound() {
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) {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(Objects.requireNonNull(getActivity()), ringtoneUri);
mediaPlayer.setLooping(true);
AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(AudioAttributes
.CONTENT_TYPE_SONIFICATION).setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION).build();
AudioAttributes audioAttributes =
new AudioAttributes.Builder().setContentType(AudioAttributes
.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.build();
mediaPlayer.setAudioAttributes(audioAttributes);
mediaPlayer.setOnPreparedListener(mp -> mediaPlayer.start());
mediaPlayer.prepareAsync();
} catch (IOException e) {
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 {
@SuppressLint("ClickableViewAccessibility")
@ -2279,7 +2384,8 @@ public class CallController extends BaseController {
v.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP && isPTTActive) {
isPTTActive = false;
microphoneControlButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_off_white_24px);
microphoneControlButton.getHierarchy()
.setPlaceholderImage(R.drawable.ic_mic_off_white_24px);
pulseAnimation.stop();
toggleMedia(false, false);
animateCallControls(false, 5000);
@ -2295,28 +2401,4 @@ public class CallController extends BaseController {
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.postprocessors.BlurPostProcessor;
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.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.controllers.base.BaseController;
import com.nextcloud.talk.events.ConfigurationChangeEvent;
import com.nextcloud.talk.models.RingtoneSettings;
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.DisplayUtils;
import com.nextcloud.talk.utils.DoNotDisturbUtils;
@ -145,14 +145,18 @@ public class CallNotificationController extends BaseController {
public CallNotificationController(Bundle args) {
super();
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
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.originalBundle = args;
credentials = ApiUtils.getCredentials(userBeingCalled.getUsername(), userBeingCalled.getToken());
credentials =
ApiUtils.getCredentials(userBeingCalled.getUsername(), userBeingCalled.getToken());
}
@Override
@ -199,7 +203,8 @@ public class CallNotificationController extends BaseController {
}
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))
.popChangeHandler(new HorizontalChangeHandler())
@ -253,7 +258,6 @@ public class CallNotificationController extends BaseController {
}
}
});
}
private void handleFromNotification() {
@ -276,7 +280,6 @@ public class CallNotificationController extends BaseController {
break;
}
}
}
@Override
@ -334,7 +337,8 @@ public class CallNotificationController extends BaseController {
"/raw/librem_by_feandesign_call");
} else {
try {
RingtoneSettings ringtoneSettings = LoganSquare.parse(callRingtonePreferenceString, RingtoneSettings.class);
RingtoneSettings ringtoneSettings =
LoganSquare.parse(callRingtonePreferenceString, RingtoneSettings.class);
ringtoneUri = ringtoneSettings.getRingtoneUri();
} catch (IOException e) {
Log.e(TAG, "Failed to parse ringtone settings");
@ -349,8 +353,11 @@ public class CallNotificationController extends BaseController {
mediaPlayer.setDataSource(getActivity(), ringtoneUri);
mediaPlayer.setLooping(true);
AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(AudioAttributes
.CONTENT_TYPE_SONIFICATION).setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build();
AudioAttributes audioAttributes =
new AudioAttributes.Builder().setContentType(AudioAttributes
.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
mediaPlayer.setAudioAttributes(audioAttributes);
mediaPlayer.setOnPreparedListener(mp -> mediaPlayer.start());
@ -391,10 +398,10 @@ public class CallNotificationController extends BaseController {
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
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);
layoutParams.width = dimen;
@ -408,11 +415,13 @@ public class CallNotificationController extends BaseController {
avatarImageView.setVisibility(View.VISIBLE);
ImageRequest imageRequest =
DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(userBeingCalled.getBaseUrl(),
DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(userBeingCalled.getBaseUrl(),
currentConversation.getName(), R.dimen.avatar_size_very_big), null);
ImagePipeline imagePipeline = Fresco.getImagePipeline();
DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, null);
DataSource<CloseableReference<CloseableImage>> dataSource =
imagePipeline.fetchDecodedImage(imageRequest, null);
dataSource.subscribe(new BaseBitmapDataSubscriber() {
@Override
@ -426,7 +435,8 @@ public class CallNotificationController extends BaseController {
.incoming_gradient));
}
if ((AvatarStatusCodeHolder.getInstance().getStatusCode() == 200 || AvatarStatusCodeHolder.getInstance().getStatusCode() == 0) &&
if ((AvatarStatusCodeHolder.getInstance().getStatusCode() == 200
|| AvatarStatusCodeHolder.getInstance().getStatusCode() == 0) &&
userBeingCalled.hasSpreedFeatureCapability("no-ping")) {
if (getActivity() != null) {
Bitmap backgroundBitmap = bitmap.copy(bitmap.getConfig(), true);
@ -454,10 +464,14 @@ public class CallNotificationController extends BaseController {
break;
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);
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);
break;
default:

View File

@ -56,14 +56,6 @@ import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.VerticalChangeHandler;
import com.bluelinelabs.logansquare.LoganSquare;
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.activities.MagicCallActivity;
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.events.BottomSheetLockEvent;
import com.nextcloud.talk.jobs.AddParticipantsToConversation;
import com.nextcloud.talk.models.RetrofitBucket;
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.ConductorRemapping;
import com.nextcloud.talk.utils.KeyboardUtils;
@ -110,7 +110,8 @@ import org.parceler.Parcels;
@AutoInjector(NextcloudTalkApplication.class)
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";
@ -197,7 +198,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
existingParticipants = new ArrayList<>();
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);
conversationPrivacyToogleLayout.setVisibility(View.GONE);
}
}
@Override
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
currentUser = userUtils.getCurrentUser();
@ -283,7 +286,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
userId = selectedUserIds.iterator().next();
}
RetrofitBucket retrofitBucket = ApiUtils.getRetrofitBucketForCreateRoom(currentUser.getBaseUrl(), roomType,
RetrofitBucket retrofitBucket =
ApiUtils.getRetrofitBucketForCreateRoom(currentUser.getBaseUrl(), roomType,
userId, null);
ncApi.createRoom(credentials,
retrofitBucket.getUrl(), retrofitBucket.getQueryMap())
@ -301,8 +305,10 @@ public class ContactsController extends BaseController implements SearchView.OnQ
Intent conversationIntent = new Intent(getActivity(), MagicCallActivity.class);
Bundle bundle = new Bundle();
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_ID(), roomOverall.getOcs().getData().getRoomId());
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(),
roomOverall.getOcs().getData().getToken());
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(),
roomOverall.getOcs().getData().getRoomId());
if (currentUser.hasSpreedFeatureCapability("chat-v2")) {
ncApi.getRoom(credentials,
@ -323,7 +329,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(),
Parcels.wrap(roomOverall.getOcs().getData()));
ConductorRemapping.INSTANCE.remapChatController(getRouter(), currentUser.getId(),
ConductorRemapping.INSTANCE.remapChatController(getRouter(),
currentUser.getId(),
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> groupIdsArray = new ArrayList<>(selectedGroupIds);
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_CONVERSATION_TYPE(), Parcels.wrap(roomType));
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_CONVERSATION_TYPE(),
Parcels.wrap(roomType));
bundle.putStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_PARTICIPANTS(), userIdsArray);
bundle.putStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_GROUP(), groupIdsArray);
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);
OneTimeWorkRequest addParticipantsToConversationWorker =
new OneTimeWorkRequest.Builder(AddParticipantsToConversation.class).setInputData(data.build()).build();
new OneTimeWorkRequest.Builder(AddParticipantsToConversation.class).setInputData(
data.build()).build();
WorkManager.getInstance().enqueue(addParticipantsToConversationWorker);
getRouter().popCurrentController();
@ -400,19 +408,22 @@ public class ContactsController extends BaseController implements SearchView.OnQ
private void initSearchView() {
if (getActivity() != null) {
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER);
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;
}
searchView.setImeOptions(imeOptions);
searchView.setQueryHint(getResources().getString(R.string.nc_search));
if (searchManager != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
}
searchView.setOnQueryTextListener(this);
}
@ -466,7 +477,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
boolean serverIs14OrUp = false;
if (currentUser.hasSpreedFeatureCapability("last-room-activity")) {
// 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;
} else {
retrofitBucket = ApiUtils.getRetrofitBucketForContactsSearch(currentUser.getBaseUrl(), query);
@ -496,7 +508,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
// mails
//shareTypesList.add("4");
modifiedQueryMap.put("shareTypes[]", shareTypesList);
}
@ -522,7 +533,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
try {
if (!finalServerIs14OrUp) {
ShareesOverall shareesOverall = LoganSquare.parse(responseBody.string(), ShareesOverall.class);
ShareesOverall shareesOverall =
LoganSquare.parse(responseBody.string(), ShareesOverall.class);
if (shareesOverall.getOcs().getData().getUsers() != null) {
shareeHashSet.addAll(shareesOverall.getOcs().getData().getUsers());
@ -535,7 +547,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
}
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.setDisplayName(sharee.getLabel());
String headerTitle;
@ -556,17 +569,16 @@ public class ContactsController extends BaseController implements SearchView.OnQ
if (!contactItems.contains(newContactItem)) {
newUserItemList.add(newContactItem);
}
}
}
} else {
AutocompleteOverall autocompleteOverall = LoganSquare.parse(responseBody.string(), AutocompleteOverall.class);
AutocompleteOverall autocompleteOverall =
LoganSquare.parse(responseBody.string(), AutocompleteOverall.class);
autocompleteUsersHashSet.addAll(autocompleteOverall.getOcs().getData());
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.setUserId(autocompleteUser.getId());
participant.setDisplayName(autocompleteUser.getLabel());
@ -586,14 +598,12 @@ public class ContactsController extends BaseController implements SearchView.OnQ
userHeaderItems.put(headerTitle, genericTextHeaderItem);
}
UserItem newContactItem = new UserItem(participant, currentUser,
userHeaderItems.get(headerTitle), getActivity());
if (!contactItems.contains(newContactItem)) {
newUserItemList.add(newContactItem);
}
}
}
}
@ -602,10 +612,12 @@ public class ContactsController extends BaseController implements SearchView.OnQ
}
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");
} else {
canFetchSearchFurther = !shareeHashSet.isEmpty() || (finalServerIs14OrUp && autocompleteUsersHashSet.size() == 100);
canFetchSearchFurther = !shareeHashSet.isEmpty() || (finalServerIs14OrUp
&& autocompleteUsersHashSet.size() == 100);
currentSearchPage = (int) modifiedQueryMap.get("page");
}
@ -616,7 +628,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
String firstName;
String secondName;
if (o1 instanceof UserItem) {
firstName = ((UserItem) o1).getModel().getDisplayName();
} else {
@ -630,7 +641,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
}
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);
} else if ("groups".equals(((UserItem) o1).getModel().getSource())) {
return -1;
@ -646,7 +658,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
String firstName;
String secondName;
if (o1 instanceof UserItem) {
firstName = ((UserItem) o1).getModel().getDisplayName();
} else {
@ -660,7 +671,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
}
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);
} else if ("groups".equals(((UserItem) o1).getModel().getSource())) {
return -1;
@ -672,7 +684,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
return firstName.compareToIgnoreCase(secondName);
});
if (newUserItemList.size() > 0) {
adapter.updateDataSet(newUserItemList);
} else {
@ -683,7 +694,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
swipeRefreshLayout.setRefreshing(false);
}
}
}
@Override
@ -691,7 +701,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setRefreshing(false);
}
}
@Override
@ -704,7 +713,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
disengageProgressBar();
}
});
}
private void prepareViews() {
@ -806,7 +814,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
swipeRefreshLayout.setEnabled(!scrolling);
}
private void prepareAndShowBottomSheetWithBundle(Bundle bundle, boolean showEntrySheet) {
if (view == null) {
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();
}
@ -854,7 +862,6 @@ public class ContactsController extends BaseController implements SearchView.OnQ
new Handler().postDelayed(() -> {
bottomSheet.setOnCancelListener(null);
bottomSheet.cancel();
}, bottomSheetLockEvent.getDelay());
}
}
@ -872,7 +879,9 @@ public class ContactsController extends BaseController implements SearchView.OnQ
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,
retrofitBucket.getUrl(), retrofitBucket.getQueryMap())
@ -891,15 +900,18 @@ public class ContactsController extends BaseController implements SearchView.OnQ
Intent conversationIntent = new Intent(getActivity(), MagicCallActivity.class);
Bundle bundle = new Bundle();
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_ID(), roomOverall.getOcs().getData().getRoomId());
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(),
roomOverall.getOcs().getData().getToken());
bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(),
roomOverall.getOcs().getData().getRoomId());
conversationIntent.putExtras(bundle);
if (currentUser.hasSpreedFeatureCapability("chat-v2")) {
bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(),
Parcels.wrap(roomOverall.getOcs().getData()));
ConductorRemapping.INSTANCE.remapChatController(getRouter(), currentUser.getId(),
ConductorRemapping.INSTANCE.remapChatController(getRouter(),
currentUser.getId(),
roomOverall.getOcs().getData().getToken(), bundle, true);
} else {
startActivity(conversationIntent);
@ -945,13 +957,14 @@ public class ContactsController extends BaseController implements SearchView.OnQ
Participant internalParticipant;
for (int i = 0; i < currentItems.size(); i++) {
internalParticipant = currentItems.get(i).getModel();
if (internalParticipant.getUserId().equals(participant.getUserId()) &&
"groups".equals(internalParticipant.getSource()) && internalParticipant.isSelected()) {
if (internalParticipant.getUserId().equals(participant.getUserId())
&&
"groups".equals(internalParticipant.getSource())
&& internalParticipant.isSelected()) {
internalParticipant.setSelected(false);
selectedGroupIds.remove(internalParticipant.getUserId());
}
}
}
adapter.notifyDataSetChanged();
@ -988,7 +1001,8 @@ public class ContactsController extends BaseController implements SearchView.OnQ
for (int i = 0; i < currentItems.size(); i++) {
if (currentItems.get(i) instanceof UserItem) {
internalParticipant = ((UserItem) currentItems.get(i)).getModel();
if ("groups".equals(internalParticipant.getSource()) && internalParticipant.isSelected()) {
if ("groups".equals(internalParticipant.getSource())
&& internalParticipant.isSelected()) {
internalParticipant.setSelected(false);
selectedGroupIds.remove(internalParticipant.getUserId());
}

View File

@ -20,7 +20,6 @@
package com.nextcloud.talk.controllers
import android.content.res.Configuration
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.os.Bundle
@ -48,12 +47,6 @@ import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler
import com.facebook.drawee.backends.pipeline.Fresco
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.adapters.items.UserItem
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.LeaveConversationWorker
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.DateUtils
import com.nextcloud.talk.utils.DisplayUtils
@ -92,7 +91,8 @@ import java.util.Calendar
import javax.inject.Inject
@AutoInjector(NextcloudTalkApplication::class)
class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapter.OnItemClickListener {
class ConversationInfoController(args: Bundle) : BaseController(),
FlexibleAdapter.OnItemClickListener {
@BindView(R.id.notification_settings)
lateinit var notificationsPreferenceScreen: MaterialPreferenceScreen
@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)
}
@ -209,10 +212,14 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
private fun setupWebinaryView() {
if (conversationUser!!.hasSpreedFeatureCapability("webinary-lobby") && (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
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)
.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()
submitLobbyChanges()
}
@ -244,7 +253,8 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
}
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) {
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
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 {
startTimeView.setSummary(R.string.nc_manual)
}
@ -269,11 +281,18 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
}
fun submitLobbyChanges() {
val state = if ((conversationInfoLobby.findViewById<View>(R.id
.mp_checkable) as SwitchCompat).isChecked) 1 else 0
ncApi.setLobbyForConversation(ApiUtils.getCredentials(conversationUser!!.username,
conversationUser.token), ApiUtils.getUrlForLobbyForConversation
(conversationUser.baseUrl, conversation!!.token), state, conversation!!.lobbyTimer)
val state = if ((conversationInfoLobby.findViewById<View>(
R.id
.mp_checkable
) as SwitchCompat).isChecked
) 1 else 0
ncApi.setLobbyForConversation(
ApiUtils.getCredentials(
conversationUser!!.username,
conversationUser.token
), ApiUtils.getUrlForLobbyForConversation
(conversationUser.baseUrl, conversation!!.token), state, conversation!!.lobbyTimer
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.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) {
ID_DELETE_CONVERSATION_DIALOG -> showDeleteConversationDialog(savedInstanceState)
else -> {
@ -309,9 +331,12 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
if (activity != null) {
LovelyStandardDialog(activity, LovelyStandardDialog.ButtonLayout.HORIZONTAL)
.setTopColorRes(R.color.nc_darkRed)
.setIcon(DisplayUtils.getTintedDrawable(
.setIcon(
DisplayUtils.getTintedDrawable(
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))
.setTitle(R.string.nc_delete_call)
.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)
super.onSaveViewState(view, outState)
}
override fun onRestoreViewState(view: View, savedViewState: Bundle) {
override fun onRestoreViewState(
view: View,
savedViewState: Bundle
) {
super.onRestoreViewState(view, savedViewState)
if (LovelySaveStateHandler.wasDialogOnScreen(savedViewState)) {
//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.putString(BundleKeys.KEY_TOKEN, conversation!!.token)
router.pushController((RouterTransaction.with(ContactsController(bundle))
router.pushController(
(RouterTransaction.with(ContactsController(bundle))
.pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler())))
.popChangeHandler(HorizontalChangeHandler()))
)
}
}
@ -381,7 +414,10 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
participant = participants[i]
userItem = UserItem(participant, conversationUser, null, activity)
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.model.sessionId = "-1"
ownUserItem.isOnline = true
@ -406,7 +442,9 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
}
private fun getListOfParticipants() {
ncApi.getPeersForCall(credentials, ApiUtils.getUrlForParticipants(conversationUser!!.baseUrl, conversationToken))
ncApi.getPeersForCall(
credentials, ApiUtils.getUrlForParticipants(conversationUser!!.baseUrl, conversationToken)
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<ParticipantsOverall> {
@ -432,9 +470,13 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
@OnClick(R.id.leaveConversationAction)
internal fun leaveConversation() {
workerData?.let {
WorkManager.getInstance().enqueue(OneTimeWorkRequest.Builder
(LeaveConversationWorker::class
.java).setInputData(it).build()
WorkManager.getInstance()
.enqueue(
OneTimeWorkRequest.Builder
(
LeaveConversationWorker::class
.java
).setInputData(it).build()
)
popTwoLastControllers()
}
@ -442,8 +484,11 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
private fun deleteConversation() {
workerData?.let {
WorkManager.getInstance().enqueue(OneTimeWorkRequest.Builder
(DeleteConversationWorker::class.java).setInputData(it).build())
WorkManager.getInstance()
.enqueue(
OneTimeWorkRequest.Builder
(DeleteConversationWorker::class.java).setInputData(it).build()
)
popTwoLastControllers()
}
}
@ -528,12 +573,16 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
private fun adjustNotificationLevelUI() {
if (conversation != null) {
if (conversationUser != null && conversationUser.hasSpreedFeatureCapability("notification-levels")) {
if (conversationUser != null && conversationUser.hasSpreedFeatureCapability(
"notification-levels"
)
) {
messageNotificationLevel.isEnabled = true
messageNotificationLevel.alpha = 1.0f
if (conversation!!.notificationLevel != Conversation.NotificationLevel.DEFAULT) {
val stringValue: String = when (EnumNotificationLevelConverter().convertToInt(conversation!!.notificationLevel)) {
val stringValue: String =
when (EnumNotificationLevelConverter().convertToInt(conversation!!.notificationLevel)) {
1 -> "always"
2 -> "mention"
3 -> "never"
@ -568,27 +617,44 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
private fun loadConversationAvatar() {
when (conversation!!.type) {
Conversation.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL -> if (!TextUtils.isEmpty
(conversation!!.name)) {
(conversation!!.name)
) {
val draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(conversationAvatarImageView.controller)
.setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(conversationUser!!.baseUrl,
conversation!!.name, R.dimen.avatar_size_big), null))
.setImageRequest(
DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(
conversationUser!!.baseUrl,
conversation!!.name, R.dimen.avatar_size_big
), null
)
)
.build()
conversationAvatarImageView.controller = draweeController
}
Conversation.ConversationType.ROOM_GROUP_CALL -> conversationAvatarImageView.hierarchy.setPlaceholderImage(DisplayUtils
.getRoundedBitmapDrawableFromVectorDrawableResource(resources,
R.drawable.ic_people_group_white_24px))
Conversation.ConversationType.ROOM_PUBLIC_CALL -> conversationAvatarImageView.hierarchy.setPlaceholderImage(DisplayUtils
.getRoundedBitmapDrawableFromVectorDrawableResource(resources,
R.drawable.ic_link_white_24px))
Conversation.ConversationType.ROOM_GROUP_CALL -> conversationAvatarImageView.hierarchy.setPlaceholderImage(
DisplayUtils
.getRoundedBitmapDrawableFromVectorDrawableResource(
resources,
R.drawable.ic_people_group_white_24px
)
)
Conversation.ConversationType.ROOM_PUBLIC_CALL -> conversationAvatarImageView.hierarchy.setPlaceholderImage(
DisplayUtils
.getRoundedBitmapDrawableFromVectorDrawableResource(
resources,
R.drawable.ic_link_white_24px
)
)
Conversation.ConversationType.ROOM_SYSTEM -> {
val layers = arrayOfNulls<Drawable>(2)
layers[0] = context.getDrawable(R.drawable.ic_launcher_background)
layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground)
val layerDrawable = LayerDrawable(layers)
conversationAvatarImageView.hierarchy.setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable))
conversationAvatarImageView.hierarchy.setPlaceholderImage(
DisplayUtils.getRoundedDrawable(layerDrawable)
)
}
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 participant = userItem.model
if (participant.userId != conversationUser!!.userId) {
var items = mutableListOf(
BasicListItemWithImage(R.drawable.ic_pencil_grey600_24dp, context.getString(R.string.nc_promote)),
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))
BasicListItemWithImage(
R.drawable.ic_pencil_grey600_24dp, context.getString(R.string.nc_promote)
),
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)) {
@ -629,14 +704,22 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
if (index == 0) {
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())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
getListOfParticipants()
}
} 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())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
@ -645,8 +728,13 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
}
} else if (index == 1) {
if (participant.type == Participant.ParticipantType.GUEST ||
participant.type == Participant.ParticipantType.USER_FOLLOWING_LINK) {
ncApi.removeParticipantFromConversation(credentials, ApiUtils.getUrlForRemovingParticipantFromConversation(conversationUser.baseUrl, conversation!!.token, true), participant.sessionId)
participant.type == Participant.ParticipantType.USER_FOLLOWING_LINK
) {
ncApi.removeParticipantFromConversation(
credentials, ApiUtils.getUrlForRemovingParticipantFromConversation(
conversationUser.baseUrl, conversation!!.token, true
), participant.sessionId
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
@ -654,7 +742,11 @@ class ConversationInfoController(args: Bundle) : BaseController(), FlexibleAdapt
}
} 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())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {

View File

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

View File

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

View File

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

View File

@ -108,7 +108,9 @@ public class ServerSelectionController extends BaseController {
@Override
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
if (getActivity() != null) {
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
@ -118,14 +120,16 @@ public class ServerSelectionController extends BaseController {
getActionBar().hide();
}
textFieldBoxes.getEndIconImageButton().setBackgroundDrawable(getResources().getDrawable(R.drawable
textFieldBoxes.getEndIconImageButton()
.setBackgroundDrawable(getResources().getDrawable(R.drawable
.ic_arrow_forward_white_24px));
textFieldBoxes.getEndIconImageButton().setAlpha(0.5f);
textFieldBoxes.getEndIconImageButton().setEnabled(false);
textFieldBoxes.getEndIconImageButton().setVisibility(View.VISIBLE);
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)))) {
providersTextView.setVisibility(View.INVISIBLE);
} else {
@ -145,16 +149,19 @@ public class ServerSelectionController extends BaseController {
.getString(R.string.nc_import_accounts_from)))) {
if (AccountUtils.INSTANCE.findAccounts(userUtils.getUsers()).size() > 1) {
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))));
} else {
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))));
}
} else {
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 {
providersTextView.setText(getResources().getString(R.string
.nc_server_import_account_plain));
@ -281,7 +288,6 @@ public class ServerSelectionController extends BaseController {
, productName), true);
toggleProceedButton(false);
}
}, throwable -> {
if (checkForcedHttps) {
checkServer(queryUrl.replace("https://", "http://"), false);
@ -319,7 +325,8 @@ public class ServerSelectionController extends BaseController {
if (ApplicationWideMessageHolder.getInstance().getMessageType() != null) {
if (ApplicationWideMessageHolder.getInstance().getMessageType()
.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);
ApplicationWideMessageHolder.getInstance().setMessageType(null);
} else if (ApplicationWideMessageHolder.getInstance().getMessageType()
@ -328,7 +335,8 @@ public class ServerSelectionController extends BaseController {
false);
} else if (ApplicationWideMessageHolder.getInstance().getMessageType()
.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);
}
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.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nextcloud.talk.models.RingtoneSettings;
import com.nextcloud.talk.BuildConfig;
import com.nextcloud.talk.R;
import com.nextcloud.talk.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.controllers.base.BaseController;
import com.nextcloud.talk.jobs.AccountRemovalWorker;
import com.nextcloud.talk.models.RingtoneSettings;
import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.utils.ApiUtils;
import com.nextcloud.talk.utils.DisplayUtils;
@ -182,7 +182,9 @@ public class SettingsController extends BaseController {
setHasOptionsMenu(true);
ViewCompat.setTransitionName(avatarImageView, "userAvatar.transitionTag");
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
getCurrentUser();
@ -190,11 +192,15 @@ public class SettingsController extends BaseController {
saveStateHandler = new LovelySaveStateHandler();
}
appPreferences.registerProxyTypeListener(proxyTypeChangeListener = new ProxyTypeChangeListener());
appPreferences.registerProxyCredentialsListener(proxyCredentialsChangeListener = new ProxyCredentialsChangeListener());
appPreferences.registerScreenSecurityListener(screenSecurityChangeListener = new ScreenSecurityChangeListener());
appPreferences.registerProxyTypeListener(
proxyTypeChangeListener = new ProxyTypeChangeListener());
appPreferences.registerProxyCredentialsListener(
proxyCredentialsChangeListener = new ProxyCredentialsChangeListener());
appPreferences.registerScreenSecurityListener(
screenSecurityChangeListener = new ScreenSecurityChangeListener());
appPreferences.registerScreenLockListener(screenLockChangeListener = new ScreenLockListener());
appPreferences.registerScreenLockTimeoutListener(screenLockTimeoutChangeListener = new ScreenLockTimeoutListener());
appPreferences.registerScreenLockTimeoutListener(
screenLockTimeoutChangeListener = new ScreenLockTimeoutListener());
appPreferences.registerThemeChangeListener(themeChangeListener = new ThemeChangeListener());
List<String> listWithIntFields = new ArrayList<>();
@ -232,7 +238,6 @@ public class SettingsController extends BaseController {
getResources().getString(R.string.nc_app_name)));
}
if (!TextUtils.isEmpty(getResources().getString(R.string.nc_privacy_url))) {
privacyButton.addPreferenceClickListener(view12 -> {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().
@ -297,7 +302,8 @@ public class SettingsController extends BaseController {
String finalHost = host;
int finalPort = port;
certificateSetup.addPreferenceClickListener(v -> KeyChain.choosePrivateKeyAlias(Objects.requireNonNull(getActivity()), alias -> {
certificateSetup.addPreferenceClickListener(
v -> KeyChain.choosePrivateKeyAlias(Objects.requireNonNull(getActivity()), alias -> {
String finalAlias = alias;
getActivity().runOnUiThread(() -> {
if (finalAlias != null) {
@ -311,10 +317,11 @@ public class SettingsController extends BaseController {
alias = "";
}
userUtils.createOrUpdateUser(null, null, null, null, null, null, null, currentUser.getId(),
userUtils.createOrUpdateUser(null, null, null, null, null, null, null,
currentUser.getId(),
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() {
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);
if (otherUserExists && getView() != null) {
@ -407,27 +415,34 @@ public class SettingsController extends BaseController {
}
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) {
((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) {
((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) {
KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager keyguardManager =
(KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (keyguardManager.isKeyguardSecure()) {
screenLockSwitchPreference.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());
@ -453,7 +468,8 @@ public class SettingsController extends BaseController {
RingtoneSettings ringtoneSettings;
if (!TextUtils.isEmpty(appPreferences.getCallRingtoneUri())) {
try {
ringtoneSettings = LoganSquare.parse(appPreferences.getCallRingtoneUri(), RingtoneSettings.class);
ringtoneSettings =
LoganSquare.parse(appPreferences.getCallRingtoneUri(), RingtoneSettings.class);
ringtoneName = ringtoneSettings.getRingtoneName();
} catch (IOException e) {
Log.e(TAG, "Failed to parse ringtone name");
@ -467,7 +483,8 @@ public class SettingsController extends BaseController {
if (!TextUtils.isEmpty(appPreferences.getMessageRingtoneUri())) {
try {
ringtoneSettings = LoganSquare.parse(appPreferences.getMessageRingtoneUri(), RingtoneSettings.class);
ringtoneSettings =
LoganSquare.parse(appPreferences.getMessageRingtoneUri(), RingtoneSettings.class);
ringtoneName = ringtoneSettings.getRingtoneName();
} catch (IOException e) {
Log.e(TAG, "Failed to parse ringtone name");
@ -524,8 +541,8 @@ public class SettingsController extends BaseController {
.getDisplayNameAlt();
}
if ((!TextUtils.isEmpty(displayName) && !displayName.equals(currentUser.getDisplayName()))) {
if ((!TextUtils.isEmpty(displayName) && !displayName.equals(
currentUser.getDisplayName()))) {
userUtils.createOrUpdateUser(null,
null,
@ -539,18 +556,15 @@ public class SettingsController extends BaseController {
},
throwable -> {
}, () -> Log.d(TAG, ""));
}
}, throwable -> {
}, () -> Log.d(TAG, ""));
removeAccountButton.addPreferenceClickListener(view1 -> {
showLovelyDialog(ID_REMOVE_ACCOUNT_WARNING_DIALOG, null);
});
}
if (userUtils.getUsers().size() <= 1) {
switchAccountButton.setVisibility(View.GONE);
}
@ -573,7 +587,8 @@ public class SettingsController extends BaseController {
break;
case FAILED_TO_IMPORT_ACCOUNT:
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);
break;
default:
@ -596,7 +611,6 @@ public class SettingsController extends BaseController {
}
}
});
} else {
if (messageView != null) {
messageView.setVisibility(View.GONE);
@ -615,7 +629,8 @@ public class SettingsController extends BaseController {
DraweeController draweeController = Fresco.newDraweeControllerBuilder()
.setOldController(avatarImageView.getController())
.setAutoPlayAnimations(true)
.setImageRequest(DisplayUtils.getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(currentUser.getBaseUrl(),
.setImageRequest(DisplayUtils.getImageRequestForUrl(
ApiUtils.getUrlForAvatarWithName(currentUser.getBaseUrl(),
avatarId, R.dimen.avatar_size_big), null))
.build();
avatarImageView.setController(draweeController);
@ -634,7 +649,6 @@ public class SettingsController extends BaseController {
super.onDestroy();
}
private void hideProxySettings() {
appPreferences.removeProxyHost();
appPreferences.removeProxyPort();
@ -711,7 +725,8 @@ public class SettingsController extends BaseController {
}
}
private class ProxyCredentialsChangeListener implements OnPreferenceValueChangedListener<Boolean> {
private class ProxyCredentialsChangeListener
implements OnPreferenceValueChangedListener<Boolean> {
@Override
public void onChanged(Boolean newValue) {

View File

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

View File

@ -50,12 +50,12 @@ import autodagger.AutoInjector;
import butterknife.BindView;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.nextcloud.talk.models.LoginData;
import com.nextcloud.talk.R;
import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.controllers.base.BaseController;
import com.nextcloud.talk.events.CertificateEvent;
import com.nextcloud.talk.jobs.PushRegistrationWorker;
import com.nextcloud.talk.models.LoginData;
import com.nextcloud.talk.models.database.UserEntity;
import com.nextcloud.talk.utils.bundle.BundleKeys;
import com.nextcloud.talk.utils.database.user.UserUtils;
@ -102,7 +102,6 @@ public class WebViewLoginController extends BaseController {
@Inject
CookieManager cookieManager;
@BindView(R.id.webview)
WebView webView;
@ -129,7 +128,8 @@ public class WebViewLoginController extends BaseController {
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.isPasswordUpdate = isPasswordUpdate;
this.username = username;
@ -151,7 +151,9 @@ public class WebViewLoginController extends BaseController {
@Override
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
if (getActivity() != null) {
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
@ -161,7 +163,8 @@ public class WebViewLoginController extends BaseController {
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().setAllowFileAccessFromFileURLs(false);
@ -177,7 +180,8 @@ public class WebViewLoginController extends BaseController {
webView.clearHistory();
WebView.clearClientCertPreferences(null);
webViewFidoBridge = WebViewFidoBridge.createInstanceForWebView((AppCompatActivity) getActivity(), webView);
webViewFidoBridge =
WebViewFidoBridge.createInstanceForWebView((AppCompatActivity) getActivity(), webView);
CookieSyncManager.createInstance(getActivity());
android.webkit.CookieManager.getInstance().removeAllCookies(null);
@ -230,7 +234,9 @@ public class WebViewLoginController extends BaseController {
} else if (!automatedLoginAttempted) {
automatedLoginAttempted = true;
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 {
webView.loadUrl("javascript: {" +
"document.getElementById('user').value = '" + username + "';" +
@ -261,7 +267,8 @@ public class WebViewLoginController extends BaseController {
new Thread(() -> {
try {
PrivateKey privateKey = KeyChain.getPrivateKey(getActivity(), finalAlias);
X509Certificate[] certificates = KeyChain.getCertificateChain(getActivity(), finalAlias);
X509Certificate[] certificates =
KeyChain.getCertificateChain(getActivity(), finalAlias);
if (privateKey != null && certificates != null) {
request.proceed(privateKey, certificates);
} else {
@ -279,7 +286,8 @@ public class WebViewLoginController extends BaseController {
PrivateKey privateKey = null;
try {
privateKey = KeyChain.getPrivateKey(getActivity(), chosenAlias);
X509Certificate[] certificates = KeyChain.getCertificateChain(getActivity(), chosenAlias);
X509Certificate[] certificates =
KeyChain.getCertificateChain(getActivity(), chosenAlias);
if (privateKey != null && certificates != null) {
request.proceed(privateKey, certificates);
} else {
@ -320,7 +328,8 @@ public class WebViewLoginController extends BaseController {
}
@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);
}
});
@ -346,7 +355,8 @@ public class WebViewLoginController extends BaseController {
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;
}
@ -398,7 +408,8 @@ public class WebViewLoginController extends BaseController {
ApplicationWideMessageHolder.getInstance().setMessageType(finalMessageType);
}
OneTimeWorkRequest pushRegistrationWork = new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
OneTimeWorkRequest pushRegistrationWork =
new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
WorkManager.getInstance().enqueue(pushRegistrationWork);
getRouter().popCurrentController();
@ -410,7 +421,6 @@ public class WebViewLoginController extends BaseController {
ApplicationWideMessageHolder.getInstance().setMessageType(finalMessageType);
}
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())) {
return loginData;
} else {

View File

@ -37,9 +37,15 @@ abstract class ButterKnifeController : Controller {
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)
unbinder = ButterKnife.bind(this, view)
onViewBound(view)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -89,7 +89,8 @@ public class RestModule {
@Singleton
@Provides
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())) {
GetProxyRunnable getProxyRunnable = new GetProxyRunnable(appPreferences);
Thread getProxyThread = new Thread(getProxyRunnable);
@ -131,7 +132,8 @@ public class RestModule {
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyManagerFactory kmf =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, null);
X509KeyManager origKm = (X509KeyManager) kmf.getKeyManagers()[0];
return new MagicKeyManager(origKm, userUtils, appPreferences);
@ -169,7 +171,8 @@ public class RestModule {
@Provides
Cache provideCache() {
int cacheSize = 128 * 1024 * 1024; // 128 MB
return new Cache(NextcloudTalkApplication.Companion.getSharedApplication().getCacheDir(), cacheSize);
return new Cache(NextcloudTalkApplication.Companion.getSharedApplication().getCacheDir(),
cacheSize);
}
@Singleton

View File

@ -30,7 +30,8 @@ public class BottomSheetLockEvent {
private final boolean cancel;
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.delay = delay;
this.shouldRefreshData = shouldRefreshData;
@ -38,7 +39,8 @@ public class BottomSheetLockEvent {
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) {
this.cancelable = cancelable;
this.delay = delay;
@ -46,5 +48,4 @@ public class BottomSheetLockEvent {
this.cancel = cancel;
this.dismissView = dismissView;
}
}

View File

@ -37,5 +37,4 @@ public class EventStatus {
public enum EventType {
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 videoStreamType;
public MediaStreamEvent(@Nullable MediaStream mediaStream, String session, String videoStreamType) {
public MediaStreamEvent(@Nullable MediaStream mediaStream, String session,
String videoStreamType) {
this.mediaStream = mediaStream;
this.session = session;
this.videoStreamType = videoStreamType;

View File

@ -24,13 +24,13 @@ import lombok.Data;
@Data
public class NetworkEvent {
public enum NetworkConnectionEvent {
NETWORK_CONNECTED, NETWORK_DISCONNECTED
}
private final NetworkConnectionEvent networkConnectionEvent;
public NetworkEvent(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 String videoStreamType;
public PeerConnectionEvent(PeerConnectionEventType peerConnectionEventType, @Nullable String sessionId,
public PeerConnectionEvent(PeerConnectionEventType peerConnectionEventType,
@Nullable String sessionId,
@Nullable String nick, Boolean changeValue, @Nullable String videoStreamType) {
this.peerConnectionEventType = peerConnectionEventType;
this.nick = nick;

View File

@ -35,7 +35,8 @@ public class SessionDescriptionSendEvent {
private final NCIceCandidate ncIceCandidate;
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) {
this.sessionDescription = sessionDescription;
this.peerId = peerId;

View File

@ -23,5 +23,8 @@ package com.nextcloud.talk.interfaces
import android.os.Bundle
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 autodagger.AutoInjector;
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.api.NcApi;
import com.nextcloud.talk.application.NextcloudTalkApplication;
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.database.arbitrarystorage.ArbitraryStorageUtils;
import com.nextcloud.talk.utils.database.user.UserUtils;
@ -77,7 +77,9 @@ public class AccountRemovalWorker extends Worker {
@NonNull
@Override
public Result doWork() {
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
PushConfigurationState pushConfigurationState;
String credentials;
@ -95,7 +97,8 @@ public class AccountRemovalWorker extends Worker {
JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class);
String finalCredentials = credentials;
ncApi.unregisterDeviceForNotificationsWithNextcloud(credentials, ApiUtils.getUrlNextcloudPush(userEntity
ncApi.unregisterDeviceForNotificationsWithNextcloud(credentials,
ApiUtils.getUrlNextcloudPush(userEntity
.getBaseUrl()))
.blockingSubscribe(new Observer<GenericOverall>() {
@Override
@ -108,7 +111,8 @@ public class AccountRemovalWorker extends Worker {
if (genericOverall.getOcs().getMeta().getStatusCode() == 200
|| genericOverall.getOcs().getMeta().getStatusCode() == 202) {
HashMap<String, String> queryMap = new HashMap<>();
queryMap.put("deviceIdentifier", finalPushConfigurationState.getDeviceIdentifier());
queryMap.put("deviceIdentifier",
finalPushConfigurationState.getDeviceIdentifier());
queryMap.put("userPublicKey", finalPushConfigurationState.getUserPublicKey());
queryMap.put("deviceIdentifierSignature",
finalPushConfigurationState.getDeviceIdentifierSignature());
@ -125,9 +129,11 @@ public class AccountRemovalWorker extends Worker {
public void onNext(Void aVoid) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String groupName = String.format(getApplicationContext().getResources()
String groupName =
String.format(getApplicationContext().getResources()
.getString(R.string
.nc_notification_channel), userEntity.getUserId(), userEntity.getBaseUrl());
.nc_notification_channel), userEntity.getUserId(),
userEntity.getBaseUrl());
CRC32 crc32 = new CRC32();
crc32.update(groupName.getBytes());
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
public void onSubscribe(Disposable d) {
@ -150,7 +158,8 @@ public class AccountRemovalWorker extends Worker {
@Override
public void onNext(Object o) {
userUtils.deleteUser(userEntity.getId()).subscribe(new CompletableObserver() {
userUtils.deleteUser(userEntity.getId())
.subscribe(new CompletableObserver() {
@Override
public void onSubscribe(Disposable d) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -30,12 +30,12 @@ import androidx.work.Worker;
import androidx.work.WorkerParameters;
import autodagger.AutoInjector;
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.application.NextcloudTalkApplication;
import com.nextcloud.talk.events.EventStatus;
import com.nextcloud.talk.models.ExternalSignalingServer;
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.bundle.BundleKeys;
import com.nextcloud.talk.utils.database.user.UserUtils;
@ -67,7 +67,9 @@ public class SignalingSettingsWorker extends Worker {
@NonNull
@Override
public Result doWork() {
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
NextcloudTalkApplication.Companion.getSharedApplication()
.getComponentApplication()
.inject(this);
Data data = getInputData();
@ -75,7 +77,8 @@ public class SignalingSettingsWorker extends Worker {
List<UserEntity> userEntityList = new ArrayList<>();
UserEntity userEntity;
if (internalUserId == -1 || (userEntity = userUtils.getUserWithInternalId(internalUserId)) == null) {
if (internalUserId == -1
|| (userEntity = userUtils.getUserWithInternalId(internalUserId)) == null) {
userEntityList = userUtils.getUsers();
} else {
userEntityList.add(userEntity);
@ -84,7 +87,8 @@ public class SignalingSettingsWorker extends Worker {
for (int i = 0; i < userEntityList.size(); i++) {
userEntity = userEntityList.get(i);
UserEntity finalUserEntity = userEntity;
ncApi.getSignalingSettings(ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()),
ncApi.getSignalingSettings(
ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()),
ApiUtils.getUrlForSignalingSettings(userEntity.getBaseUrl()))
.blockingSubscribe(new Observer<SignalingSettingsOverall>() {
@Override
@ -96,12 +100,15 @@ public class SignalingSettingsWorker extends Worker {
public void onNext(SignalingSettingsOverall signalingSettingsOverall) {
ExternalSignalingServer externalSignalingServer;
externalSignalingServer = new ExternalSignalingServer();
externalSignalingServer.setExternalSignalingServer(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer());
externalSignalingServer.setExternalSignalingTicket(signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket());
externalSignalingServer.setExternalSignalingServer(
signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer());
externalSignalingServer.setExternalSignalingTicket(
signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket());
try {
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>() {
@Override
public void onSubscribe(Disposable d) {
@ -110,12 +117,14 @@ public class SignalingSettingsWorker extends Worker {
@Override
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
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
@ -130,7 +139,9 @@ public class SignalingSettingsWorker extends Worker {
@Override
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
@ -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);
return Result.success();

View File

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

View File

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

View File

@ -65,7 +65,8 @@ public interface User extends Parcelable, Persistable, Serializable {
if (getCapabilities() != null) {
try {
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);
}
} catch (IOException e) {
@ -79,7 +80,8 @@ public interface User extends Parcelable, Persistable, Serializable {
if (getCapabilities() != null) {
try {
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");
}
} catch (IOException e) {
@ -109,9 +111,12 @@ public interface User extends Parcelable, Persistable, Serializable {
Capabilities capabilities = null;
try {
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")) {
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")) {
int chatSize = Integer.parseInt(chatConfigHashMap.get("max-length"));
if (chatSize > 0) {

View File

@ -55,9 +55,6 @@ public class ChatMessage implements IMessage, MessageContentType, MessageContent
public Map<String, String> selectedIndividualHashMap;
@JsonIgnore
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")
public int jsonMessageId;
@JsonField(name = "token")
@ -79,6 +76,9 @@ public class ChatMessage implements IMessage, MessageContentType, MessageContent
public HashMap<String, HashMap<String, String>> messageParameters;
@JsonField(name = "systemMessage", typeConverter = EnumSystemMessageTypeConverter.class)
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() {
if (messageParameters != null && messageParameters.size() > 0) {
@ -102,7 +102,9 @@ public class ChatMessage implements IMessage, MessageContentType, MessageContent
if (individualHashMap.get("type").equals("file")) {
selectedIndividualHashMap = individualHashMap;
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() {
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();
} else {
if (getMessageType().equals(MessageType.SINGLE_LINK_GIPHY_MESSAGE)
|| getMessageType().equals(MessageType.SINGLE_LINK_TENOR_MESSAGE)
|| getMessageType().equals(MessageType.SINGLE_LINK_GIF_MESSAGE)) {
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 {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_a_gif),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest)));
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
.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)) {
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 {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_an_attachment),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest)));
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
.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)) {
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 {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_a_link),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest)));
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
.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)) {
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 {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_an_audio),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest)));
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
.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)) {
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 {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_a_video),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest)));
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
.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)) {
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 {
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication().getResources().getString(R.string.nc_sent_an_image),
!TextUtils.isEmpty(getActorDisplayName()) ? getActorDisplayName() : NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest)));
return (String.format(NextcloudTalkApplication.Companion.getSharedApplication()
.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
public String getAvatar() {
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")) {
String apiId =
NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_guest);
NextcloudTalkApplication.Companion.getSharedApplication()
.getString(R.string.nc_guest);
if (!TextUtils.isEmpty(getActorDisplayName())) {
apiId = getActorDisplayName();
}
return ApiUtils.getUrlForAvatarWithNameForGuests(getActiveUser().getBaseUrl(), apiId, R.dimen.avatar_size);
return ApiUtils.getUrlForAvatarWithNameForGuests(getActiveUser().getBaseUrl(), apiId,
R.dimen.avatar_size);
} else {
return null;
}

View File

@ -24,11 +24,13 @@ import java.util.HashMap;
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) {
for (String key : messageParameters.keySet()) {
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 + "\\}", "@" +
messageParameters.get(key).get("name"));
} else if (individualHashMap.get("type").equals("file")) {
@ -37,7 +39,6 @@ public class ChatUtils {
}
}
return message;
}
}

View File

@ -100,30 +100,35 @@ public class Conversation {
Participant.ParticipantType.USER_FOLLOWING_LINK.equals(participantType));
}
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) {
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) {
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) {
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) {
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) {
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() {
@ -163,5 +168,4 @@ public class Conversation {
ROOM_PUBLIC_CALL,
ROOM_SYSTEM
}
}

View File

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

View File

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

View File

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

View File

@ -43,7 +43,8 @@ public class LoganSquareJodaTimeConverter implements TypeConverter<DateTime> {
}
@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) {
jsonGenerator.writeStringField(fieldName, object != null ? object.toString() : null);
} else {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -22,10 +22,10 @@ package com.nextcloud.talk.utils;
import android.net.Uri;
import android.text.TextUtils;
import androidx.annotation.DimenRes;
import com.nextcloud.talk.models.RetrofitBucket;
import com.nextcloud.talk.BuildConfig;
import com.nextcloud.talk.R;
import com.nextcloud.talk.application.NextcloudTalkApplication;
import com.nextcloud.talk.models.RetrofitBucket;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
@ -45,7 +45,8 @@ public class ApiUtils {
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);
if (isGuest) {
@ -55,7 +56,8 @@ public class ApiUtils {
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.setUrl(baseUrl + ocsApiVersion + "/apps/files_sharing/api/v1/sharees");
@ -73,7 +75,8 @@ public class ApiUtils {
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="
+ Uri.encode(remotePath, "UTF-8")
+ "&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";
}
public static RetrofitBucket getRetrofitBucketForContactsSearchFor14(String baseUrl, @Nullable String searchQuery) {
public static RetrofitBucket getRetrofitBucketForContactsSearchFor14(String baseUrl,
@Nullable String searchQuery) {
RetrofitBucket retrofitBucket = getRetrofitBucketForContactsSearch(baseUrl, searchQuery);
retrofitBucket.setUrl(baseUrl + ocsApiVersion + "/core/autocomplete/get");
@ -98,7 +102,6 @@ public class ApiUtils {
return retrofitBucket;
}
public static String getUrlForSettingNotificationlevel(String baseUrl, String token) {
return getRoom(baseUrl, token) + "/notify";
}
@ -107,7 +110,6 @@ public class ApiUtils {
return getRoom(baseUrl, token) + "/participants/active";
}
public static String getUrlForParticipants(String baseUrl, String token) {
return getRoom(baseUrl, token) + "/participants";
}
@ -145,9 +147,11 @@ public class ApiUtils {
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.setUrl(baseUrl + ocsApiVersion + spreedApiVersion + "/room/" + token + "/participants");
retrofitBucket.setUrl(
baseUrl + ocsApiVersion + spreedApiVersion + "/room/" + token + "/participants");
Map<String, String> queryMap = new HashMap<>();
@ -156,16 +160,17 @@ public class ApiUtils {
retrofitBucket.setQueryMap(queryMap);
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.getQueryMap().put("source", "groups");
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.getQueryMap().put("source", "emails");
return retrofitBucket;
@ -181,7 +186,6 @@ public class ApiUtils {
public static String getUrlForCall(String baseUrl, String token) {
return baseUrl + ocsApiVersion + spreedApiVersion + "/call/" + token;
}
public static String getUrlForCallPing(String baseUrl, String token) {
@ -217,7 +221,6 @@ public class ApiUtils {
return getUrlForSignaling(baseUrl, null) + "/settings";
}
public static String getUrlForUserProfile(String baseUrl) {
return baseUrl + ocsApiVersion + "/cloud/user";
}
@ -226,11 +229,13 @@ public class ApiUtils {
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;
}
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
.Companion.getSharedApplication().getResources().getDimension(avatarSize));

View File

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

View File

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

View File

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

View File

@ -31,13 +31,15 @@ object DoNotDisturbUtils {
fun isDnDActive(): Boolean {
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 (notificationManager.currentInterruptionFilter == NotificationManager
.INTERRUPTION_FILTER_NONE || notificationManager
.currentInterruptionFilter == NotificationManager
.INTERRUPTION_FILTER_ALARMS || notificationManager
.currentInterruptionFilter == NotificationManager.INTERRUPTION_FILTER_PRIORITY) {
.currentInterruptionFilter == NotificationManager.INTERRUPTION_FILTER_PRIORITY
) {
return true
}
}
@ -49,7 +51,8 @@ object DoNotDisturbUtils {
fun isInDoNotDisturbWithPriority(): Boolean {
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 (notificationManager.currentInterruptionFilter == NotificationManager.INTERRUPTION_FILTER_PRIORITY) {
return true
@ -62,7 +65,8 @@ object DoNotDisturbUtils {
fun shouldPlaySound(): Boolean {
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
var shouldPlaySound = true

View File

@ -26,7 +26,6 @@ import java.util.HashMap
object DrawableUtils {
fun getDrawableResourceIdForMimeType(mimetype: String): Int {
var localMimetype = mimetype
val drawableMap = HashMap<String, Int>()
@ -48,44 +47,72 @@ object DrawableUtils {
drawableMap["application/octet-stream"] = R.drawable.ic_mimetype_file
drawableMap["application/postscript"] = R.drawable.ic_mimetype_image
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.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.kmz"] = R.drawable.ic_mimetype_location
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.sheet.binary.macroEnabled.12"] = 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-excel.addin.macroEnabled.12"] =
R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.ms-excel.sheet.binary.macroEnabled.12"] =
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-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.presentation.macroEnabled.12"] = 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.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-powerpoint.addin.macroEnabled.12"] =
R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.ms-powerpoint.presentation.macroEnabled.12"] =
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.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.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.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-word.template.macroEnabled.12"] = R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.oasis.opendocument.presentation"] = R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.oasis.opendocument.presentation-template"] = R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.oasis.opendocument.spreadsheet"] = R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.oasis.opendocument.spreadsheet-template"] = R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.oasis.opendocument.text"] = R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.oasis.opendocument.text-master"] = R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.oasis.opendocument.text-template"] = 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.ms-word.template.macroEnabled.12"] =
R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.oasis.opendocument.presentation"] =
R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.oasis.opendocument.presentation-template"] =
R.drawable.ic_mimetype_x_office_presentation
drawableMap["application/vnd.oasis.opendocument.spreadsheet"] =
R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.oasis.opendocument.spreadsheet-template"] =
R.drawable.ic_mimetype_x_office_spreadsheet
drawableMap["application/vnd.oasis.opendocument.text"] =
R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.oasis.opendocument.text-master"] =
R.drawable.ic_mimetype_x_office_document
drawableMap["application/vnd.oasis.opendocument.text-template"] =
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.wordperfect"] = R.drawable.ic_mimetype_x_office_document
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-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-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-mobipocket-ebook"] = R.drawable.ic_mimetype_text
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) {
// Ensure we react to vertical scrolling
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
|| super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
|| super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
nestedScrollAxes);
}
@Override
public void onNestedScroll(final CoordinatorLayout coordinatorLayout, final View child,
final View target, final int dxConsumed, final int dyConsumed,
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) {
// User scrolled down -> hide the FAB
List<View> dependencies = coordinatorLayout.getDependencies(child);

View File

@ -33,7 +33,8 @@ public class KeyboardUtils {
private View contentView;
private boolean isUsedInBottomSheet;
//a small helper to allow showing the editText focus
ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener =
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
@ -72,12 +73,11 @@ public class KeyboardUtils {
/**
* Helper to hide the keyboard
*
* @param act
*/
public static void hideKeyboard(Activity act) {
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);
}
}

View File

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

View File

@ -41,17 +41,27 @@ object NotificationUtils {
val NOTIFICATION_CHANNEL_CALLS_V3 = "NOTIFICATION_CHANNEL_CALLS_V3"
@TargetApi(Build.VERSION_CODES.O)
fun createNotificationChannel(context: Context,
channelId: String, channelName: String,
channelDescription: String, enableLights: Boolean,
importance: Int) {
fun createNotificationChannel(
context: Context,
channelId: String,
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,
importance)
val channel = NotificationChannel(
channelId, channelName,
importance
)
channel.description = channelDescription
channel.enableLights(enableLights)
@ -63,10 +73,14 @@ object NotificationUtils {
}
@TargetApi(Build.VERSION_CODES.O)
fun createNotificationChannelGroup(context: Context,
groupId: String, groupName: CharSequence) {
fun createNotificationChannelGroup(
context: Context,
groupId: String,
groupName: CharSequence
) {
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)
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) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val statusBarNotifications = notificationManager.activeNotifications
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 &&
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
var notification: Notification?
@ -107,7 +131,10 @@ object NotificationUtils {
notification = statusBarNotification.notification
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)
}
}
@ -115,13 +142,17 @@ object NotificationUtils {
}
}
fun findNotificationForRoom(context: Context?,
fun findNotificationForRoom(
context: Context?,
conversationUser: UserEntity,
roomTokenOrId: String): StatusBarNotification? {
roomTokenOrId: String
): StatusBarNotification? {
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
var notification: Notification?
@ -129,7 +160,12 @@ object NotificationUtils {
notification = statusBarNotification.notification
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
}
}
@ -139,12 +175,17 @@ object NotificationUtils {
return null
}
fun cancelExistingNotificationsForRoom(context: Context?, conversationUser: UserEntity,
roomTokenOrId: String) {
fun cancelExistingNotificationsForRoom(
context: Context?,
conversationUser: UserEntity,
roomTokenOrId: String
) {
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
var notification: Notification?
@ -152,7 +193,12 @@ object NotificationUtils {
notification = statusBarNotification.notification
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)
}
}

View File

@ -34,7 +34,8 @@ public class OkHttpNetworkFetcherWithCache extends OkHttpNetworkFetcher {
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);
}
}

View File

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

View File

@ -63,7 +63,11 @@ public class SecurityUtils {
keyStore.load(null);
SecretKey secretKey = (SecretKey) keyStore.getKey(CREDENTIALS_KEY, null);
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
// the last AUTHENTICATION_DURATION_SECONDS seconds.
@ -123,7 +127,8 @@ public class SecurityUtils {
private static int getIntegerFromStringTimeout(String validity) {
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 indexOfValidity = entryValues.indexOf(validity);
return entryIntValues[indexOfValidity];

View File

@ -41,7 +41,8 @@ import java.util.Set;
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) {
UserEntity userEntity = userUtils.getCurrentUser();
@ -51,7 +52,8 @@ public class ShareUtils {
userEntity.getBaseUrl(), conversation.getToken());
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 null;
}
}

View File

@ -65,7 +65,8 @@ public final class TextMatchers {
MimeUtil.registerMimeDetector(ExtensionMimeDetector.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.equalsIgnoreCase("image/gif")) {
return ChatMessage.MessageType.SINGLE_LINK_GIF_MESSAGE;

View File

@ -53,7 +53,9 @@ public class PulseAnimation {
if (view == null) throw new NullPointerException("View cant be null!");
scaleDown = ObjectAnimator.ofPropertyValuesHolder(view, PropertyValuesHolder.ofFloat("scaleX", 1.2f), PropertyValuesHolder.ofFloat("scaleY", 1.2f));
scaleDown =
ObjectAnimator.ofPropertyValuesHolder(view, PropertyValuesHolder.ofFloat("scaleX", 1.2f),
PropertyValuesHolder.ofFloat("scaleY", 1.2f));
scaleDown.setDuration(duration);
scaleDown.setRepeatMode(repeatMode);
scaleDown.setRepeatCount(repeatCount);

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