Commit 0685f5fa authored by karthyks's avatar karthyks

handle nullable on arguments extra

format code to match kotlin guidelines
remove redundant underscores on function destructuring
handle deprecated calls on lower android versions
parent 99f75dd6
...@@ -58,10 +58,8 @@ class LoginFragment : Fragment(), LoginView { ...@@ -58,10 +58,8 @@ class LoginFragment : Fragment(), LoginView {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
arguments?.run {
val bundle = arguments serverName = getString(SERVER_NAME)
if (bundle != null) {
serverName = bundle.getString(SERVER_NAME)
} }
} }
...@@ -150,7 +148,7 @@ class LoginFragment : Fragment(), LoginView { ...@@ -150,7 +148,7 @@ class LoginFragment : Fragment(), LoginView {
override fun showGenericErrorMessage() = showMessage(R.string.msg_generic_error) override fun showGenericErrorMessage() = showMessage(R.string.msg_generic_error)
private fun setupOnClickListener() = private fun setupOnClickListener() =
ui { _ -> ui {
button_log_in.setOnClickListener { button_log_in.setOnClickListener {
presenter.authenticateWithUserAndPassword( presenter.authenticateWithUserAndPassword(
text_username_or_email.textContent, text_username_or_email.textContent,
...@@ -160,7 +158,7 @@ class LoginFragment : Fragment(), LoginView { ...@@ -160,7 +158,7 @@ class LoginFragment : Fragment(), LoginView {
} }
override fun showForgotPasswordView() { override fun showForgotPasswordView() {
ui { _ -> ui {
button_forgot_your_password.isVisible = true button_forgot_your_password.isVisible = true
button_forgot_your_password.setOnClickListener { presenter.forgotPassword() } button_forgot_your_password.setOnClickListener { presenter.forgotPassword() }
......
...@@ -157,34 +157,33 @@ class LoginOptionsFragment : Fragment(), LoginOptionsView { ...@@ -157,34 +157,33 @@ class LoginOptionsFragment : Fragment(), LoginOptionsView {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
val bundle = arguments arguments?.run {
if (bundle != null) { serverName = getString(SERVER_NAME)
serverName = bundle.getString(SERVER_NAME) state = getString(STATE)
state = bundle.getString(STATE) facebookOauthUrl = getString(FACEBOOK_OAUTH_URL)
facebookOauthUrl = bundle.getString(FACEBOOK_OAUTH_URL) githubOauthUrl = getString(GITHUB_OAUTH_URL)
githubOauthUrl = bundle.getString(GITHUB_OAUTH_URL) googleOauthUrl = getString(GOOGLE_OAUTH_URL)
googleOauthUrl = bundle.getString(GOOGLE_OAUTH_URL) linkedinOauthUrl = getString(LINKEDIN_OAUTH_URL)
linkedinOauthUrl = bundle.getString(LINKEDIN_OAUTH_URL) gitlabOauthUrl = getString(GITLAB_OAUTH_URL)
gitlabOauthUrl = bundle.getString(GITLAB_OAUTH_URL) wordpressOauthUrl = getString(WORDPRESS_OAUTH_URL)
wordpressOauthUrl = bundle.getString(WORDPRESS_OAUTH_URL) casLoginUrl = getString(CAS_LOGIN_URL)
casLoginUrl = bundle.getString(CAS_LOGIN_URL) casToken = getString(CAS_TOKEN)
casToken = bundle.getString(CAS_TOKEN) casServiceName = getString(CAS_SERVICE_NAME)
casServiceName = bundle.getString(CAS_SERVICE_NAME) casServiceNameTextColor = getInt(CAS_SERVICE_NAME_TEXT_COLOR)
casServiceNameTextColor = bundle.getInt(CAS_SERVICE_NAME_TEXT_COLOR) casServiceButtonColor = getInt(CAS_SERVICE_BUTTON_COLOR)
casServiceButtonColor = bundle.getInt(CAS_SERVICE_BUTTON_COLOR) customOauthUrl = getString(CUSTOM_OAUTH_URL)
customOauthUrl = bundle.getString(CUSTOM_OAUTH_URL) customOauthServiceName = getString(CUSTOM_OAUTH_SERVICE_NAME)
customOauthServiceName = bundle.getString(CUSTOM_OAUTH_SERVICE_NAME) customOauthServiceTextColor = getInt(CUSTOM_OAUTH_SERVICE_NAME_TEXT_COLOR)
customOauthServiceTextColor = bundle.getInt(CUSTOM_OAUTH_SERVICE_NAME_TEXT_COLOR) customOauthServiceButtonColor = getInt(CUSTOM_OAUTH_SERVICE_BUTTON_COLOR)
customOauthServiceButtonColor = bundle.getInt(CUSTOM_OAUTH_SERVICE_BUTTON_COLOR) samlUrl = getString(SAML_URL)
samlUrl = bundle.getString(SAML_URL) samlToken = getString(SAML_TOKEN)
samlToken = bundle.getString(SAML_TOKEN) samlServiceName = getString(SAML_SERVICE_NAME)
samlServiceName = bundle.getString(SAML_SERVICE_NAME) samlServiceTextColor = getInt(SAML_SERVICE_NAME_TEXT_COLOR)
samlServiceTextColor = bundle.getInt(SAML_SERVICE_NAME_TEXT_COLOR) samlServiceButtonColor = getInt(SAML_SERVICE_BUTTON_COLOR)
samlServiceButtonColor = bundle.getInt(SAML_SERVICE_BUTTON_COLOR) totalSocialAccountsEnabled = getInt(TOTAL_SOCIAL_ACCOUNTS)
totalSocialAccountsEnabled = bundle.getInt(TOTAL_SOCIAL_ACCOUNTS) isLoginFormEnabled = getBoolean(IS_LOGIN_FORM_ENABLED)
isLoginFormEnabled = bundle.getBoolean(IS_LOGIN_FORM_ENABLED) isNewAccountCreationEnabled = getBoolean(IS_NEW_ACCOUNT_CREATION_ENABLED)
isNewAccountCreationEnabled = bundle.getBoolean(IS_NEW_ACCOUNT_CREATION_ENABLED) deepLinkInfo = getParcelable(DEEP_LINK_INFO)
deepLinkInfo = bundle.getParcelable(DEEP_LINK_INFO)
} }
} }
...@@ -388,7 +387,7 @@ class LoginOptionsFragment : Fragment(), LoginOptionsView { ...@@ -388,7 +387,7 @@ class LoginOptionsFragment : Fragment(), LoginOptionsView {
} }
override fun setupExpandAccountsView() { override fun setupExpandAccountsView() {
ui { _ -> ui {
expand_more_accounts_container.isVisible = true expand_more_accounts_container.isVisible = true
var isAccountsCollapsed = true var isAccountsCollapsed = true
button_expand_collapse_accounts.setOnClickListener { button_expand_collapse_accounts.setOnClickListener {
...@@ -406,14 +405,14 @@ class LoginOptionsFragment : Fragment(), LoginOptionsView { ...@@ -406,14 +405,14 @@ class LoginOptionsFragment : Fragment(), LoginOptionsView {
} }
override fun showLoginWithEmailButton() { override fun showLoginWithEmailButton() {
ui { _ -> ui {
button_login_with_email.setOnClickListener { presenter.toLoginWithEmail() } button_login_with_email.setOnClickListener { presenter.toLoginWithEmail() }
button_login_with_email.isVisible = true button_login_with_email.isVisible = true
} }
} }
override fun showCreateNewAccountButton() { override fun showCreateNewAccountButton() {
ui { _ -> ui {
button_create_an_account.setOnClickListener { presenter.toCreateAccount() } button_create_an_account.setOnClickListener { presenter.toCreateAccount() }
button_create_an_account.isVisible = true button_create_an_account.isVisible = true
} }
......
...@@ -52,14 +52,10 @@ class RegisterUsernameFragment : Fragment(), RegisterUsernameView { ...@@ -52,14 +52,10 @@ class RegisterUsernameFragment : Fragment(), RegisterUsernameView {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
arguments?.run {
val bundle = arguments userId = getString(BUNDLE_USER_ID, "")
if (bundle != null) { authToken = getString(BUNDLE_AUTH_TOKEN, "")
userId = bundle.getString(BUNDLE_USER_ID) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
authToken = bundle.getString(BUNDLE_AUTH_TOKEN)
} else {
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
......
...@@ -75,7 +75,7 @@ class SignupFragment : Fragment(), SignupView { ...@@ -75,7 +75,7 @@ class SignupFragment : Fragment(), SignupView {
} }
private fun setupOnClickListener() = private fun setupOnClickListener() =
ui { _ -> ui {
button_register.setOnClickListener { button_register.setOnClickListener {
presenter.signup( presenter.signup(
text_username.textContent, text_username.textContent,
......
...@@ -49,14 +49,10 @@ class TwoFAFragment : Fragment(), TwoFAView { ...@@ -49,14 +49,10 @@ class TwoFAFragment : Fragment(), TwoFAView {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
arguments?.run {
val bundle = arguments username = getString(BUNDLE_USERNAME, "")
if (bundle != null) { password = getString(BUNDLE_PASSWORD, "")
username = bundle.getString(BUNDLE_USERNAME) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
password = bundle.getString(BUNDLE_PASSWORD)
} else {
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
......
...@@ -66,15 +66,12 @@ class ChatDetailsFragment : Fragment(), ChatDetailsView { ...@@ -66,15 +66,12 @@ class ChatDetailsFragment : Fragment(), ChatDetailsView {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
val bundle = arguments arguments?.run {
if (bundle != null) { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID)
chatRoomId = bundle.getString(BUNDLE_CHAT_ROOM_ID) chatRoomType = getString(BUNDLE_CHAT_ROOM_TYPE)
chatRoomType = bundle.getString(BUNDLE_CHAT_ROOM_TYPE) isSubscribed = getBoolean(BUNDLE_IS_SUBSCRIBED)
isSubscribed = bundle.getBoolean(BUNDLE_IS_SUBSCRIBED) disableMenu = getBoolean(BUNDLE_DISABLE_MENU)
disableMenu = bundle.getBoolean(BUNDLE_DISABLE_MENU) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
} else {
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
......
...@@ -46,12 +46,9 @@ class MessageInfoFragment : Fragment(), MessageInfoView { ...@@ -46,12 +46,9 @@ class MessageInfoFragment : Fragment(), MessageInfoView {
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
setHasOptionsMenu(true) setHasOptionsMenu(true)
val bundle = arguments arguments?.run {
if (bundle != null) { messageId = getString(BUNDLE_MESSAGE_ID, "")
messageId = bundle.getString(BUNDLE_MESSAGE_ID) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
} else {
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
......
...@@ -12,7 +12,10 @@ import com.facebook.drawee.backends.pipeline.Fresco ...@@ -12,7 +12,10 @@ import com.facebook.drawee.backends.pipeline.Fresco
import kotlinx.android.synthetic.main.item_action_button.view.* import kotlinx.android.synthetic.main.item_action_button.view.*
import timber.log.Timber import timber.log.Timber
class ActionsListAdapter(actions: List<Action>, var actionAttachmentOnClickListener: ActionAttachmentOnClickListener) : RecyclerView.Adapter<ActionsListAdapter.ViewHolder>() { class ActionsListAdapter(
actions: List<Action>,
var actionAttachmentOnClickListener: ActionAttachmentOnClickListener
) : RecyclerView.Adapter<ActionsListAdapter.ViewHolder>() {
var actions: List<Action> = actions var actions: List<Action> = actions
......
...@@ -174,12 +174,12 @@ class ChatRoomAdapter( ...@@ -174,12 +174,12 @@ class ChatRoomAdapter(
Timber.d("index: $index") Timber.d("index: $index")
if (index > -1) { if (index > -1) {
dataSet[index] = message dataSet[index] = message
dataSet.forEachIndexed { index, viewModel -> dataSet.forEachIndexed { ind, viewModel ->
if (viewModel.messageId == message.messageId) { if (viewModel.messageId == message.messageId) {
if (viewModel.nextDownStreamMessage == null) { if (viewModel.nextDownStreamMessage == null) {
viewModel.reactions = message.reactions viewModel.reactions = message.reactions
} }
notifyItemChanged(index) notifyItemChanged(ind)
} }
} }
// Delete message only if current is a system message update, i.e.: Message Removed // Delete message only if current is a system message update, i.e.: Message Removed
......
...@@ -24,8 +24,8 @@ class RoomSuggestionsAdapter : SuggestionsAdapter<RoomSuggestionsViewHolder>("#" ...@@ -24,8 +24,8 @@ class RoomSuggestionsAdapter : SuggestionsAdapter<RoomSuggestionsViewHolder>("#"
override fun bind(item: SuggestionModel, itemClickListener: SuggestionsAdapter.ItemClickListener?) { override fun bind(item: SuggestionModel, itemClickListener: SuggestionsAdapter.ItemClickListener?) {
item as ChatRoomSuggestionUiModel item as ChatRoomSuggestionUiModel
with(itemView) { with(itemView) {
val fullname = itemView.findViewById<TextView>(R.id.text_fullname) val fullname = findViewById<TextView>(R.id.text_fullname)
val name = itemView.findViewById<TextView>(R.id.text_name) val name = findViewById<TextView>(R.id.text_name)
name.text = item.name name.text = item.name
fullname.text = item.fullName fullname.text = item.fullName
setOnClickListener { setOnClickListener {
......
...@@ -8,10 +8,11 @@ import chat.rocket.android.util.extensions.content ...@@ -8,10 +8,11 @@ import chat.rocket.android.util.extensions.content
import chat.rocket.android.util.extensions.openTabbedUrl import chat.rocket.android.util.extensions.openTabbedUrl
import kotlinx.android.synthetic.main.message_url_preview.view.* import kotlinx.android.synthetic.main.message_url_preview.view.*
class UrlPreviewViewHolder(itemView: View, class UrlPreviewViewHolder(
listener: ActionsListener, itemView: View,
reactionListener: EmojiReactionListener? = null) listener: ActionsListener,
: BaseViewHolder<UrlPreviewUiModel>(itemView, listener, reactionListener) { reactionListener: EmojiReactionListener? = null
) : BaseViewHolder<UrlPreviewUiModel>(itemView, listener, reactionListener) {
init { init {
with(itemView) { with(itemView) {
......
...@@ -1072,7 +1072,7 @@ class ChatRoomPresenter @Inject constructor( ...@@ -1072,7 +1072,7 @@ class ChatRoomPresenter @Inject constructor(
launchUI(strategy) { launchUI(strategy) {
try { try {
messagesRepository.getById(messageId)?.let { message -> messagesRepository.getById(messageId)?.let { message ->
getChatRoomAsync(message.roomId)?.let { chatRoom -> getChatRoomAsync(message.roomId)?.let {
val models = mapper.map(message) val models = mapper.map(message)
models.firstOrNull()?.permalink?.let { models.firstOrNull()?.permalink?.let {
view.copyToClipboard(it) view.copyToClipboard(it)
......
...@@ -81,44 +81,46 @@ class ChatRoomActivity : AppCompatActivity(), HasSupportFragmentInjector { ...@@ -81,44 +81,46 @@ class ChatRoomActivity : AppCompatActivity(), HasSupportFragmentInjector {
return return
} }
val chatRoomId = intent.getStringExtra(INTENT_CHAT_ROOM_ID) with(intent) {
requireNotNull(chatRoomId) { "no chat_room_id provided in Intent extras" } val chatRoomId = getStringExtra(INTENT_CHAT_ROOM_ID)
requireNotNull(chatRoomId) { "no chat_room_id provided in Intent extras" }
val chatRoomName = intent.getStringExtra(INTENT_CHAT_ROOM_NAME) val chatRoomName = getStringExtra(INTENT_CHAT_ROOM_NAME)
requireNotNull(chatRoomName) { "no chat_room_name provided in Intent extras" } requireNotNull(chatRoomName) { "no chat_room_name provided in Intent extras" }
val chatRoomType = intent.getStringExtra(INTENT_CHAT_ROOM_TYPE) val chatRoomType = getStringExtra(INTENT_CHAT_ROOM_TYPE)
requireNotNull(chatRoomType) { "no chat_room_type provided in Intent extras" } requireNotNull(chatRoomType) { "no chat_room_type provided in Intent extras" }
val isReadOnly = intent.getBooleanExtra(INTENT_CHAT_ROOM_IS_READ_ONLY, true) val isReadOnly = getBooleanExtra(INTENT_CHAT_ROOM_IS_READ_ONLY, true)
val isCreator = intent.getBooleanExtra(INTENT_CHAT_ROOM_IS_CREATOR, false) val isCreator = getBooleanExtra(INTENT_CHAT_ROOM_IS_CREATOR, false)
val isFavorite = intent.getBooleanExtra(INTENT_CHAT_ROOM_IS_FAVORITE, false) val isFavorite = getBooleanExtra(INTENT_CHAT_ROOM_IS_FAVORITE, false)
val chatRoomLastSeen = intent.getLongExtra(INTENT_CHAT_ROOM_LAST_SEEN, -1) val chatRoomLastSeen = getLongExtra(INTENT_CHAT_ROOM_LAST_SEEN, -1)
val isSubscribed = intent.getBooleanExtra(INTENT_CHAT_IS_SUBSCRIBED, true) val isSubscribed = getBooleanExtra(INTENT_CHAT_IS_SUBSCRIBED, true)
val chatRoomMessage = intent.getStringExtra(INTENT_CHAT_ROOM_MESSAGE) val chatRoomMessage = getStringExtra(INTENT_CHAT_ROOM_MESSAGE)
setupToolbar() if (supportFragmentManager.findFragmentByTag(TAG_CHAT_ROOM_FRAGMENT) == null) {
addFragment(TAG_CHAT_ROOM_FRAGMENT, R.id.fragment_container) {
if (supportFragmentManager.findFragmentByTag(TAG_CHAT_ROOM_FRAGMENT) == null) { newInstance(
addFragment(TAG_CHAT_ROOM_FRAGMENT, R.id.fragment_container) { chatRoomId,
newInstance( chatRoomName,
chatRoomId, chatRoomType,
chatRoomName, isReadOnly,
chatRoomType, chatRoomLastSeen,
isReadOnly, isSubscribed,
chatRoomLastSeen, isCreator,
isSubscribed, isFavorite,
isCreator, chatRoomMessage
isFavorite, )
chatRoomMessage }
)
} }
} }
setupToolbar()
} }
override fun onBackPressed() { override fun onBackPressed() {
......
...@@ -273,20 +273,18 @@ class ChatRoomFragment : Fragment(), ChatRoomView, EmojiKeyboardListener, EmojiR ...@@ -273,20 +273,18 @@ class ChatRoomFragment : Fragment(), ChatRoomView, EmojiKeyboardListener, EmojiR
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
setHasOptionsMenu(true) setHasOptionsMenu(true)
val bundle = arguments
if (bundle != null) { arguments?.run {
chatRoomId = bundle.getString(BUNDLE_CHAT_ROOM_ID) chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "")
chatRoomName = bundle.getString(BUNDLE_CHAT_ROOM_NAME) chatRoomName = getString(BUNDLE_CHAT_ROOM_NAME, "")
chatRoomType = bundle.getString(BUNDLE_CHAT_ROOM_TYPE) chatRoomType = getString(BUNDLE_CHAT_ROOM_TYPE, "")
isReadOnly = bundle.getBoolean(BUNDLE_IS_CHAT_ROOM_READ_ONLY) isReadOnly = getBoolean(BUNDLE_IS_CHAT_ROOM_READ_ONLY)
isSubscribed = bundle.getBoolean(BUNDLE_CHAT_ROOM_IS_SUBSCRIBED) isSubscribed = getBoolean(BUNDLE_CHAT_ROOM_IS_SUBSCRIBED)
chatRoomLastSeen = bundle.getLong(BUNDLE_CHAT_ROOM_LAST_SEEN) chatRoomLastSeen = getLong(BUNDLE_CHAT_ROOM_LAST_SEEN)
isCreator = bundle.getBoolean(BUNDLE_CHAT_ROOM_IS_CREATOR) isCreator = getBoolean(BUNDLE_CHAT_ROOM_IS_CREATOR)
isFavorite = bundle.getBoolean(BUNDLE_CHAT_ROOM_IS_FAVORITE) isFavorite = getBoolean(BUNDLE_CHAT_ROOM_IS_FAVORITE)
chatRoomMessage = bundle.getString(BUNDLE_CHAT_ROOM_MESSAGE) chatRoomMessage = getString(BUNDLE_CHAT_ROOM_MESSAGE)
} else { } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
adapter = ChatRoomAdapter(chatRoomId, chatRoomType, chatRoomName, this, reactionListener = this, navigator = navigator) adapter = ChatRoomAdapter(chatRoomId, chatRoomType, chatRoomName, this, reactionListener = this, navigator = navigator)
} }
......
...@@ -8,8 +8,7 @@ import chat.rocket.android.emoji.internal.GlideApp ...@@ -8,8 +8,7 @@ import chat.rocket.android.emoji.internal.GlideApp
import chat.rocket.android.util.extensions.getFileName import chat.rocket.android.util.extensions.getFileName
import chat.rocket.android.util.extensions.getMimeType import chat.rocket.android.util.extensions.getMimeType
import chat.rocket.common.util.ifNull import chat.rocket.common.util.ifNull
import com.bumptech.glide.request.target.SimpleTarget import com.bumptech.glide.request.target.ImageViewTarget
import com.bumptech.glide.request.transition.Transition
fun ChatRoomFragment.showFileAttachmentDialog(uri: Uri) { fun ChatRoomFragment.showFileAttachmentDialog(uri: Uri) {
imagePreview.isVisible = false imagePreview.isVisible = false
...@@ -25,27 +24,22 @@ fun ChatRoomFragment.showFileAttachmentDialog(uri: Uri) { ...@@ -25,27 +24,22 @@ fun ChatRoomFragment.showFileAttachmentDialog(uri: Uri) {
when { when {
mimeType.startsWith("image") -> { mimeType.startsWith("image") -> {
if (mimeType.contains("gif")) { if (mimeType.contains("gif")) {
GlideApp GlideApp.with(context)
.with(context) .asGif()
.asGif() .load(uri)
.load(uri) .fitCenter()
.fitCenter() .into(imagePreview)
.into(imagePreview)
} else { } else {
GlideApp GlideApp.with(context)
.with(context) .asBitmap()
.asBitmap() .load(uri)
.load(uri) .fitCenter()
.fitCenter() .into(object : ImageViewTarget<Bitmap>(imagePreview) {
.into(object : SimpleTarget<Bitmap>() { override fun setResource(resource: Bitmap?) {
override fun onResourceReady( bitmap = resource
resource: Bitmap, imagePreview.setImageBitmap(resource)
transition: Transition<in Bitmap>? }
) { })
bitmap = resource
imagePreview.setImageBitmap(resource)
}
})
} }
imagePreview.isVisible = true imagePreview.isVisible = true
} }
......
...@@ -416,21 +416,18 @@ class UiModelMapper @Inject constructor( ...@@ -416,21 +416,18 @@ class UiModelMapper @Inject constructor(
return fullUrl return fullUrl
} }
private fun attachmentText(text: String?, attachment: Attachment?, context: Context): String? { private fun attachmentText(text: String?, attachment: Attachment?, context: Context): String? = attachment?.run {
return if (attachment != null) { with(context) {
when { when {
attachment.imageUrl.isNotNullNorEmpty() -> context.getString(R.string.msg_preview_photo) imageUrl.isNotNullNorEmpty() -> getString(R.string.msg_preview_photo)
attachment.videoUrl.isNotNullNorEmpty() -> context.getString(R.string.msg_preview_video) videoUrl.isNotNullNorEmpty() -> getString(R.string.msg_preview_video)
attachment.audioUrl.isNotNullNorEmpty() -> context.getString(R.string.msg_preview_audio) audioUrl.isNotNullNorEmpty() -> getString(R.string.msg_preview_audio)
attachment.titleLink.isNotNullNorEmpty() && titleLink.isNotNullNorEmpty() &&
attachment.type?.contentEquals("file") == true -> type?.contentEquals("file") == true -> getString(R.string.msg_preview_file)
context.getString(R.string.msg_preview_file) else -> text
else -> text }
} }
} else { } ?: text
text
}
}
private fun attachmentDescription(attachment: Attachment): String? { private fun attachmentDescription(attachment: Attachment): String? {
return attachment.description return attachment.description
......
...@@ -8,20 +8,23 @@ import androidx.core.view.isInvisible ...@@ -8,20 +8,23 @@ import androidx.core.view.isInvisible
import androidx.core.view.isVisible import androidx.core.view.isVisible
import chat.rocket.android.R import chat.rocket.android.R
import chat.rocket.android.chatrooms.adapter.model.RoomUiModel import chat.rocket.android.chatrooms.adapter.model.RoomUiModel
import chat.rocket.android.util.extensions.setTextViewAppearance
import chat.rocket.common.model.RoomType import chat.rocket.common.model.RoomType
import chat.rocket.common.model.UserStatus import chat.rocket.common.model.UserStatus
import kotlinx.android.synthetic.main.item_chat.view.* import kotlinx.android.synthetic.main.item_chat.view.*
import kotlinx.android.synthetic.main.unread_messages_badge.view.* import kotlinx.android.synthetic.main.unread_messages_badge.view.*
class RoomViewHolder(itemView: View, private val listener: (RoomUiModel) -> Unit) : class RoomViewHolder(
ViewHolder<RoomItemHolder>(itemView) { itemView: View,
private val listener: (RoomUiModel) -> Unit
) : ViewHolder<RoomItemHolder>(itemView) {
private val resources: Resources = itemView.resources private val resources: Resources = itemView.resources
private val channelIcon: Drawable = resources.getDrawable(R.drawable.ic_hashtag_12dp) private val channelIcon: Drawable = resources.getDrawable(R.drawable.ic_hashtag_12dp, null)
private val groupIcon: Drawable = resources.getDrawable(R.drawable.ic_lock_12_dp) private val groupIcon: Drawable = resources.getDrawable(R.drawable.ic_lock_12_dp, null)
private val onlineIcon: Drawable = resources.getDrawable(R.drawable.ic_status_online_12dp) private val onlineIcon: Drawable = resources.getDrawable(R.drawable.ic_status_online_12dp, null)
private val awayIcon: Drawable = resources.getDrawable(R.drawable.ic_status_away_12dp) private val awayIcon: Drawable = resources.getDrawable(R.drawable.ic_status_away_12dp, null)
private val busyIcon: Drawable = resources.getDrawable(R.drawable.ic_status_busy_12dp) private val busyIcon: Drawable = resources.getDrawable(R.drawable.ic_status_busy_12dp, null)
private val offlineIcon: Drawable = resources.getDrawable(R.drawable.ic_status_invisible_12dp) private val offlineIcon: Drawable = resources.getDrawable(R.drawable.ic_status_invisible_12dp, null)
override fun bindViews(data: RoomItemHolder) { override fun bindViews(data: RoomItemHolder) {
val room = data.data val room = data.data
...@@ -53,14 +56,14 @@ class RoomViewHolder(itemView: View, private val listener: (RoomUiModel) -> Unit ...@@ -53,14 +56,14 @@ class RoomViewHolder(itemView: View, private val listener: (RoomUiModel) -> Unit
if (room.unread == null) text_total_unread_messages.text = "!" if (room.unread == null) text_total_unread_messages.text = "!"
if (room.unread != null) text_total_unread_messages.text = room.unread if (room.unread != null) text_total_unread_messages.text = room.unread
if (room.mentions) text_total_unread_messages.text = "@${room.unread}" if (room.mentions) text_total_unread_messages.text = "@${room.unread}"
text_chat_name.setTextAppearance(context, R.style.ChatList_ChatName_Unread_TextView) text_chat_name.setTextViewAppearance(context, R.style.ChatList_ChatName_Unread_TextView)
text_timestamp.setTextAppearance(context, R.style.ChatList_Timestamp_Unread_TextView) text_timestamp.setTextViewAppearance(context, R.style.ChatList_Timestamp_Unread_TextView)
text_last_message.setTextAppearance(context, R.style.ChatList_LastMessage_Unread_TextView) text_last_message.setTextViewAppearance(context, R.style.ChatList_LastMessage_Unread_TextView)
text_total_unread_messages.isVisible = true text_total_unread_messages.isVisible = true
} else { } else {
text_chat_name.setTextAppearance(context, R.style.ChatList_ChatName_TextView) text_chat_name.setTextViewAppearance(context, R.style.ChatList_ChatName_TextView)
text_timestamp.setTextAppearance(context, R.style.ChatList_Timestamp_TextView) text_timestamp.setTextViewAppearance(context, R.style.ChatList_Timestamp_TextView)
text_last_message.setTextAppearance(context, R.style.ChatList_LastMessage_TextView) text_last_message.setTextViewAppearance(context, R.style.ChatList_LastMessage_TextView)
text_total_unread_messages.isInvisible = true text_total_unread_messages.isInvisible = true
} }
......
...@@ -6,8 +6,7 @@ import chat.rocket.android.R ...@@ -6,8 +6,7 @@ import chat.rocket.android.R
import chat.rocket.android.chatrooms.adapter.model.RoomUiModel import chat.rocket.android.chatrooms.adapter.model.RoomUiModel
import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.inflate
class RoomsAdapter(private val listener: (RoomUiModel) -> Unit) : class RoomsAdapter(private val listener: (RoomUiModel) -> Unit) : RecyclerView.Adapter<ViewHolder<*>>() {
RecyclerView.Adapter<ViewHolder<*>>() {
init { init {
setHasStableIds(true) setHasStableIds(true)
......
...@@ -82,9 +82,8 @@ class ChatRoomsFragment : Fragment(), ChatRoomsView { ...@@ -82,9 +82,8 @@ class ChatRoomsFragment : Fragment(), ChatRoomsView {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
setHasOptionsMenu(true) setHasOptionsMenu(true)
val bundle = arguments arguments?.run {
if (bundle != null) { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID)
chatRoomId = bundle.getString(BUNDLE_CHAT_ROOM_ID)
chatRoomId.ifNotNullNotEmpty { roomId -> chatRoomId.ifNotNullNotEmpty { roomId ->
presenter.loadChatRoom(roomId) presenter.loadChatRoom(roomId)
chatRoomId = null chatRoomId = null
...@@ -132,10 +131,10 @@ class ChatRoomsFragment : Fragment(), ChatRoomsView { ...@@ -132,10 +131,10 @@ class ChatRoomsFragment : Fragment(), ChatRoomsView {
recycler_view.adapter = adapter recycler_view.adapter = adapter
viewModel.getChatRooms().observe(viewLifecycleOwner, Observer { rooms -> viewModel.getChatRooms().observe(viewLifecycleOwner, Observer { rooms ->
rooms?.let { rooms?.let { items ->
Timber.d("Got items: $it") Timber.d("Got items: $items")
adapter.values = it adapter.values = items
if (rooms.isNotEmpty()) { if (items.isNotEmpty()) {
text_no_data_to_display.isVisible = false text_no_data_to_display.isVisible = false
} }
} }
......
package chat.rocket.android.createchannel.ui package chat.rocket.android.createchannel.ui
import android.os.Bundle import android.os.Bundle
import android.view.LayoutInflater import android.view.*
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.ActionMode import androidx.appcompat.view.ActionMode
import androidx.core.view.isVisible import androidx.core.view.isVisible
...@@ -294,8 +290,8 @@ class CreateChannelFragment : Fragment(), CreateChannelView, ActionMode.Callback ...@@ -294,8 +290,8 @@ class CreateChannelFragment : Fragment(), CreateChannelView, ActionMode.Callback
private fun addChip(chipText: String) { private fun addChip(chipText: String) {
val chip = Chip(context) val chip = Chip(context)
chip.chipText = chipText chip.text = chipText
chip.isCloseIconEnabled = true chip.isCloseIconVisible = true
chip.setChipBackgroundColorResource(R.color.icon_grey) chip.setChipBackgroundColorResource(R.color.icon_grey)
setupChipOnCloseIconClickListener(chip) setupChipOnCloseIconClickListener(chip)
chip_group_member.addView(chip) chip_group_member.addView(chip)
...@@ -304,7 +300,7 @@ class CreateChannelFragment : Fragment(), CreateChannelView, ActionMode.Callback ...@@ -304,7 +300,7 @@ class CreateChannelFragment : Fragment(), CreateChannelView, ActionMode.Callback
private fun setupChipOnCloseIconClickListener(chip: Chip) { private fun setupChipOnCloseIconClickListener(chip: Chip) {
chip.setOnCloseIconClickListener { chip.setOnCloseIconClickListener {
removeChip(it) removeChip(it)
removeMember((it as Chip).chipText.toString()) removeMember((it as Chip).text.toString())
// whenever we remove a chip we should process the chip group visibility. // whenever we remove a chip we should process the chip group visibility.
processChipGroupVisibility() processChipGroupVisibility()
} }
......
...@@ -223,8 +223,8 @@ class DatabaseManager(val context: Application, val serverUrl: String) { ...@@ -223,8 +223,8 @@ class DatabaseManager(val context: Application, val serverUrl: String) {
val list = mutableListOf<BaseMessageEntity>() val list = mutableListOf<BaseMessageEntity>()
reactions.keys.forEach { reaction -> reactions.keys.forEach { reaction ->
val users = reactions[reaction] val users = reactions[reaction]
users?.let { users -> users?.let {
list.add(ReactionEntity(reaction, message.id, users.size, users.joinToString())) list.add(ReactionEntity(reaction, message.id, it.size, it.joinToString()))
} }
} }
...@@ -375,15 +375,11 @@ class DatabaseManager(val context: Application, val serverUrl: String) { ...@@ -375,15 +375,11 @@ class DatabaseManager(val context: Application, val serverUrl: String) {
} }
} }
private fun mapLastMessageText(message: Message?): String? { private fun mapLastMessageText(message: Message?): String? = message?.run {
return if (message == null) { if (this.message.isEmpty() && attachments?.isNotEmpty() == true) {
null mapAttachmentText(attachments!![0])
} else { } else {
return if (message.message.isEmpty() && message.attachments?.isNotEmpty() == true) { this.message
mapAttachmentText(message.attachments!![0])
} else {
message.message
}
} }
} }
......
package chat.rocket.android.db.model package chat.rocket.android.db.model
import android.content.Context import android.content.Context
import androidx.room.ColumnInfo import androidx.room.*
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import chat.rocket.android.R import chat.rocket.android.R
import chat.rocket.android.util.extension.orFalse import chat.rocket.android.util.extension.orFalse
import chat.rocket.android.util.extensions.isNotNullNorEmpty import chat.rocket.android.util.extensions.isNotNullNorEmpty
...@@ -114,8 +110,7 @@ fun Attachment.asEntity(msgId: String, context: Context): List<BaseMessageEntity ...@@ -114,8 +110,7 @@ fun Attachment.asEntity(msgId: String, context: Context): List<BaseMessageEntity
val list = mutableListOf<BaseMessageEntity>() val list = mutableListOf<BaseMessageEntity>()
val text = mapAttachmentText(text, attachments?.firstOrNull(), context) val text = mapAttachmentText(text, attachments?.firstOrNull(), context)
list.add(AttachmentEntity(
val entity = AttachmentEntity(
_id = attachmentId, _id = attachmentId,
messageId = msgId, messageId = msgId,
title = title, title = title,
...@@ -144,16 +139,14 @@ fun Attachment.asEntity(msgId: String, context: Context): List<BaseMessageEntity ...@@ -144,16 +139,14 @@ fun Attachment.asEntity(msgId: String, context: Context): List<BaseMessageEntity
buttonAlignment = buttonAlignment, buttonAlignment = buttonAlignment,
hasActions = actions?.isNotEmpty() == true, hasActions = actions?.isNotEmpty() == true,
hasFields = fields?.isNotEmpty() == true hasFields = fields?.isNotEmpty() == true
) ))
list.add(entity)
fields?.forEach { field -> fields?.forEach { field ->
val entity = AttachmentFieldEntity( list.add(AttachmentFieldEntity(
attachmentId = attachmentId, attachmentId = attachmentId,
title = field.title, title = field.title,
value = field.value value = field.value
) ))
list.add(entity)
} }
actions?.forEach { action -> actions?.forEach { action ->
...@@ -175,18 +168,16 @@ fun Attachment.asEntity(msgId: String, context: Context): List<BaseMessageEntity ...@@ -175,18 +168,16 @@ fun Attachment.asEntity(msgId: String, context: Context): List<BaseMessageEntity
return list return list
} }
fun mapAttachmentText(text: String?, attachment: Attachment?, context: Context): String? { fun mapAttachmentText(text: String?, attachment: Attachment?, context: Context): String? = attachment?.run {
return if (attachment != null) { with(context) {
when { when {
attachment.imageUrl.isNotNullNorEmpty() -> context.getString(R.string.msg_preview_photo) imageUrl.isNotNullNorEmpty() -> getString(R.string.msg_preview_photo)
attachment.videoUrl.isNotNullNorEmpty() -> context.getString(R.string.msg_preview_video) videoUrl.isNotNullNorEmpty() -> getString(R.string.msg_preview_video)
attachment.audioUrl.isNotNullNorEmpty() -> context.getString(R.string.msg_preview_audio) audioUrl.isNotNullNorEmpty() -> getString(R.string.msg_preview_audio)
attachment.titleLink.isNotNullNorEmpty() && titleLink.isNotNullNorEmpty() &&
attachment.type?.contentEquals("file") == true -> type?.contentEquals("file") == true ->
context.getString(R.string.msg_preview_file) getString(R.string.msg_preview_file)
else -> text else -> text
} }
} else { } ?: text
text
}
} }
...@@ -48,12 +48,9 @@ class FavoriteMessagesFragment : Fragment(), FavoriteMessagesView { ...@@ -48,12 +48,9 @@ class FavoriteMessagesFragment : Fragment(), FavoriteMessagesView {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
val bundle = arguments arguments?.run {
if (bundle != null) { chatRoomId = getString(INTENT_CHAT_ROOM_ID, "")
chatRoomId = bundle.getString(INTENT_CHAT_ROOM_ID) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
} else {
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
......
...@@ -55,12 +55,9 @@ class FilesFragment : Fragment(), FilesView { ...@@ -55,12 +55,9 @@ class FilesFragment : Fragment(), FilesView {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
val bundle = arguments arguments?.run {
if (bundle != null) { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "")
chatRoomId = bundle.getString(BUNDLE_CHAT_ROOM_ID) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
} else {
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
......
...@@ -51,10 +51,10 @@ object ImageHelper { ...@@ -51,10 +51,10 @@ object ImageHelper {
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT ViewGroup.LayoutParams.WRAP_CONTENT
) )
val toolbar = Toolbar(context).also { val toolbar = Toolbar(context).also { toolbar ->
it.inflateMenu(R.menu.image_actions) toolbar.inflateMenu(R.menu.image_actions)
it.setOnMenuItemClickListener { toolbar.setOnMenuItemClickListener { view ->
return@setOnMenuItemClickListener when (it.itemId) { return@setOnMenuItemClickListener when (view.itemId) {
R.id.action_save_image -> saveImage(context) R.id.action_save_image -> saveImage(context)
else -> true else -> true
} }
...@@ -62,14 +62,16 @@ object ImageHelper { ...@@ -62,14 +62,16 @@ object ImageHelper {
val titleSize = context.resources val titleSize = context.resources
.getDimensionPixelSize(R.dimen.viewer_toolbar_title) .getDimensionPixelSize(R.dimen.viewer_toolbar_title)
val titleTextView = TextView(context).also { val titleTextView = TextView(context).also { tv ->
it.text = imageName with(tv) {
it.setTextColor(Color.WHITE) text = imageName
it.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleSize.toFloat()) setTextColor(Color.WHITE)
it.ellipsize = TextUtils.TruncateAt.END setTextSize(TypedValue.COMPLEX_UNIT_PX, titleSize.toFloat())
it.setSingleLine() ellipsize = TextUtils.TruncateAt.END
it.typeface = Typeface.DEFAULT_BOLD setSingleLine()
it.setPadding(pad) typeface = Typeface.DEFAULT_BOLD
setPadding(pad)
}
} }
val backArrowView = ImageView(context).also { val backArrowView = ImageView(context).also {
...@@ -83,8 +85,8 @@ object ImageHelper { ...@@ -83,8 +85,8 @@ object ImageHelper {
AppBarLayout.LayoutParams.WRAP_CONTENT AppBarLayout.LayoutParams.WRAP_CONTENT
) )
it.addView(backArrowView, layoutParams) toolbar.addView(backArrowView, layoutParams)
it.addView(titleTextView, layoutParams) toolbar.addView(titleTextView, layoutParams)
} }
val appBarLayout = AppBarLayout(context).also { val appBarLayout = AppBarLayout(context).also {
......
...@@ -10,8 +10,9 @@ import chat.rocket.android.util.extensions.inflate ...@@ -10,8 +10,9 @@ import chat.rocket.android.util.extensions.inflate
import kotlinx.android.synthetic.main.avatar.view.* import kotlinx.android.synthetic.main.avatar.view.*
import kotlinx.android.synthetic.main.item_member.view.* import kotlinx.android.synthetic.main.item_member.view.*
class MembersAdapter(private val listener: (MemberUiModel) -> Unit) : class MembersAdapter(
RecyclerView.Adapter<MembersAdapter.ViewHolder>() { private val listener: (MemberUiModel) -> Unit
) : RecyclerView.Adapter<MembersAdapter.ViewHolder>() {
private var dataSet: List<MemberUiModel> = ArrayList() private var dataSet: List<MemberUiModel> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MembersAdapter.ViewHolder = override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MembersAdapter.ViewHolder =
...@@ -43,7 +44,8 @@ class MembersAdapter(private val listener: (MemberUiModel) -> Unit) : ...@@ -43,7 +44,8 @@ class MembersAdapter(private val listener: (MemberUiModel) -> Unit) :
fun bind(memberUiModel: MemberUiModel, listener: (MemberUiModel) -> Unit) = with(itemView) { fun bind(memberUiModel: MemberUiModel, listener: (MemberUiModel) -> Unit) = with(itemView) {
image_avatar.setImageURI(memberUiModel.avatarUri) image_avatar.setImageURI(memberUiModel.avatarUri)
text_member.content = memberUiModel.displayName text_member.content = memberUiModel.displayName
text_member.setCompoundDrawablesRelativeWithIntrinsicBounds(DrawableHelper.getUserStatusDrawable(memberUiModel.status, context), null, null, null) text_member.setCompoundDrawablesRelativeWithIntrinsicBounds(
DrawableHelper.getUserStatusDrawable(memberUiModel.status, context), null, null, null)
setOnClickListener { listener(memberUiModel) } setOnClickListener { listener(memberUiModel) }
} }
} }
......
...@@ -52,12 +52,9 @@ class MembersFragment : Fragment(), MembersView { ...@@ -52,12 +52,9 @@ class MembersFragment : Fragment(), MembersView {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
val bundle = arguments arguments?.run {
if (bundle != null) { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "")
chatRoomId = bundle.getString(BUNDLE_CHAT_ROOM_ID) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
} else {
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
...@@ -80,7 +77,7 @@ class MembersFragment : Fragment(), MembersView { ...@@ -80,7 +77,7 @@ class MembersFragment : Fragment(), MembersView {
setupToolbar(total) setupToolbar(total)
if (adapter.itemCount == 0) { if (adapter.itemCount == 0) {
adapter.prependData(dataSet) adapter.prependData(dataSet)
if (dataSet.size >= 59) { // TODO Check why the API retorns the specified count -1 if (dataSet.size >= 59) { // TODO Check why the API returns the specified count -1
recycler_view.addOnScrollListener(object : recycler_view.addOnScrollListener(object :
EndlessRecyclerViewScrollListener(linearLayoutManager) { EndlessRecyclerViewScrollListener(linearLayoutManager) {
override fun onLoadMore( override fun onLoadMore(
......
...@@ -48,12 +48,9 @@ class MentionsFragment : Fragment(), MentionsView { ...@@ -48,12 +48,9 @@ class MentionsFragment : Fragment(), MentionsView {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
val bundle = arguments arguments?.run {
if (bundle != null) { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "")
chatRoomId = bundle.getString(BUNDLE_CHAT_ROOM_ID) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
} else {
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
......
...@@ -48,12 +48,9 @@ class PinnedMessagesFragment : Fragment(), PinnedMessagesView { ...@@ -48,12 +48,9 @@ class PinnedMessagesFragment : Fragment(), PinnedMessagesView {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
val bundle = arguments arguments?.run {
if (bundle != null) { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "")
chatRoomId = bundle.getString(BUNDLE_CHAT_ROOM_ID) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
} else {
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
......
...@@ -96,9 +96,13 @@ class ProfileFragment : Fragment(), ProfileView, ActionMode.Callback { ...@@ -96,9 +96,13 @@ class ProfileFragment : Fragment(), ProfileView, ActionMode.Callback {
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (resultData != null && resultCode == Activity.RESULT_OK) { if (resultData != null && resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CODE_FOR_PERFORM_SAF) { if (requestCode == REQUEST_CODE_FOR_PERFORM_SAF) {
presenter.updateAvatar(resultData.data) resultData.data?.let {
presenter.updateAvatar(it)
}
} else if (requestCode == REQUEST_CODE_FOR_PERFORM_CAMERA) { } else if (requestCode == REQUEST_CODE_FOR_PERFORM_CAMERA) {
presenter.preparePhotoAndUpdateAvatar(resultData.extras["data"] as Bitmap) resultData.extras?.get("data")?.let {
presenter.preparePhotoAndUpdateAvatar(it as Bitmap)
}
} }
} }
} }
......
...@@ -186,7 +186,7 @@ class PushManager @Inject constructor( ...@@ -186,7 +186,7 @@ class PushManager @Inject constructor(
.setGroupSummary(false) .setGroupSummary(false)
if (style == null || "inbox" == style) { if (style == null || "inbox" == style) {
val pushMessageList = groupedPushes.hostToPushMessageList.get(host) val pushMessageList = groupedPushes.hostToPushMessageList[host]
if (pushMessageList != null) { if (pushMessageList != null) {
val userMessages = pushMessageList.filter { val userMessages = pushMessageList.filter {
...@@ -230,7 +230,10 @@ class PushManager @Inject constructor( ...@@ -230,7 +230,10 @@ class PushManager @Inject constructor(
} }
@RequiresApi(Build.VERSION_CODES.O) @RequiresApi(Build.VERSION_CODES.O)
private fun createBaseNotificationBuilder(pushMessage: PushMessage, grouped: Boolean = false): NotificationCompat.Builder { private fun createBaseNotificationBuilder(
pushMessage: PushMessage,
grouped: Boolean = false
): NotificationCompat.Builder {
return with(pushMessage) { return with(pushMessage) {
val id = notificationId.toInt() val id = notificationId.toInt()
val host = info.host val host = info.host
...@@ -295,7 +298,12 @@ class PushManager @Inject constructor( ...@@ -295,7 +298,12 @@ class PushManager @Inject constructor(
return PendingIntent.getBroadcast(context, pushMessage.notificationId.toInt(), deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT) return PendingIntent.getBroadcast(context, pushMessage.notificationId.toInt(), deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT)
} }
private fun getContentIntent(context: Context, notificationId: Int, pushMessage: PushMessage, grouped: Boolean = false): PendingIntent { private fun getContentIntent(
context: Context,
notificationId: Int,
pushMessage: PushMessage,
grouped: Boolean = false
): PendingIntent {
val roomId = if (!grouped) pushMessage.info.roomId else null val roomId = if (!grouped) pushMessage.info.roomId else null
val notificationIntent = context.changeServerIntent(pushMessage.info.host, chatRoomId = roomId) val notificationIntent = context.changeServerIntent(pushMessage.info.host, chatRoomId = roomId)
return PendingIntent.getActivity(context, random.nextInt(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT) return PendingIntent.getActivity(context, random.nextInt(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)
...@@ -303,7 +311,11 @@ class PushManager @Inject constructor( ...@@ -303,7 +311,11 @@ class PushManager @Inject constructor(
// CharSequence extensions // CharSequence extensions
private fun CharSequence.fromHtml(): Spanned { private fun CharSequence.fromHtml(): Spanned {
return Html.fromHtml(this as String) return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(this as String, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(this as String)
}
} }
// NotificationCompat.Builder extensions // NotificationCompat.Builder extensions
...@@ -383,12 +395,12 @@ data class PushMessage( ...@@ -383,12 +395,12 @@ data class PushMessage(
) : Parcelable { ) : Parcelable {
constructor(parcel: Parcel) : this( constructor(parcel: Parcel) : this(
parcel.readString()!!,
parcel.readString()!!,
parcel.readParcelable(PushMessage::class.java.classLoader)!!,
parcel.readString(), parcel.readString(),
parcel.readString(), parcel.readString(),
parcel.readParcelable(PushMessage::class.java.classLoader), parcel.readString()!!,
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(), parcel.readString(),
parcel.readString()) parcel.readString())
...@@ -433,9 +445,9 @@ data class PushInfo @KotshiConstructor constructor( ...@@ -433,9 +445,9 @@ data class PushInfo @KotshiConstructor constructor(
} }
constructor(parcel: Parcel) : this( constructor(parcel: Parcel) : this(
parcel.readString(), parcel.readString()!!,
parcel.readString(), parcel.readString()!!,
roomTypeOf(parcel.readString()), roomTypeOf(parcel.readString()!!),
parcel.readString(), parcel.readString(),
parcel.readParcelable(PushInfo::class.java.classLoader)) parcel.readParcelable(PushInfo::class.java.classLoader))
...@@ -481,7 +493,7 @@ data class PushSender @KotshiConstructor constructor( ...@@ -481,7 +493,7 @@ data class PushSender @KotshiConstructor constructor(
val name: String? val name: String?
) : Parcelable { ) : Parcelable {
constructor(parcel: Parcel) : this( constructor(parcel: Parcel) : this(
parcel.readString(), parcel.readString()!!,
parcel.readString(), parcel.readString(),
parcel.readString()) parcel.readString())
......
...@@ -97,8 +97,8 @@ class ConnectionManager( ...@@ -97,8 +97,8 @@ class ConnectionManager(
resubscribeRooms() resubscribeRooms()
temporaryStatus?.let { status -> temporaryStatus?.let { tempStatus ->
client.setTemporaryStatus(status) client.setTemporaryStatus(tempStatus)
} }
} }
is State.Waiting -> { is State.Waiting -> {
...@@ -231,7 +231,7 @@ class ConnectionManager( ...@@ -231,7 +231,7 @@ class ConnectionManager(
} }
private fun resubscribeRooms() { private fun resubscribeRooms() {
roomMessagesChannels.toList().map { (roomId, channel) -> roomMessagesChannels.toList().map { (roomId, _) ->
client.subscribeRoomMessages(roomId) { _, id -> client.subscribeRoomMessages(roomId) { _, id ->
Timber.d("Subscribed to $roomId: $id") Timber.d("Subscribed to $roomId: $id")
subscriptionIdMap[roomId] = id subscriptionIdMap[roomId] = id
......
...@@ -153,7 +153,7 @@ class DatabaseMessageMapper(private val dbManager: DatabaseManager) { ...@@ -153,7 +153,7 @@ class DatabaseMessageMapper(private val dbManager: DatabaseManager) {
null null
} }
val attachment = Attachment( list.add(Attachment(
title = title, title = title,
type = type, type = type,
description = description, description = description,
...@@ -179,10 +179,10 @@ class DatabaseMessageMapper(private val dbManager: DatabaseManager) { ...@@ -179,10 +179,10 @@ class DatabaseMessageMapper(private val dbManager: DatabaseManager) {
authorLink = authorLink, authorLink = authorLink,
fields = fields, fields = fields,
fallback = fallback, fallback = fallback,
buttonAlignment = if (actions != null && actions.isNotEmpty()) buttonAlignment ?: "vertical" else null, buttonAlignment = if (actions != null && actions.isNotEmpty()) buttonAlignment
?: "vertical" else null,
actions = actions actions = actions
) ))
list.add(attachment)
} }
} }
return list return list
......
...@@ -46,8 +46,8 @@ class DatabaseMessagesRepository( ...@@ -46,8 +46,8 @@ class DatabaseMessagesRepository(
dbManager.processMessagesBatch(listOf(message)).join() dbManager.processMessagesBatch(listOf(message)).join()
} }
override suspend fun saveAll(messages: List<Message>) { override suspend fun saveAll(newMessages: List<Message>) {
dbManager.processMessagesBatch(messages).join() dbManager.processMessagesBatch(newMessages).join()
} }
override suspend fun removeById(id: String) { override suspend fun removeById(id: String) {
...@@ -78,7 +78,7 @@ class DatabaseMessagesRepository( ...@@ -78,7 +78,7 @@ class DatabaseMessagesRepository(
override suspend fun getLastSyncDate(roomId: String): Long? = withContext(CommonPool) { override suspend fun getLastSyncDate(roomId: String): Long? = withContext(CommonPool) {
retryDB("getLastSync($roomId)") { retryDB("getLastSync($roomId)") {
dbManager.messageDao().getLastSync(roomId)?.let { it.timestamp } dbManager.messageDao().getLastSync(roomId)?.timestamp
} }
} }
} }
\ No newline at end of file
...@@ -14,12 +14,12 @@ class SharedPreferencesAccountsRepository( ...@@ -14,12 +14,12 @@ class SharedPreferencesAccountsRepository(
private val moshi: Moshi private val moshi: Moshi
) : AccountsRepository { ) : AccountsRepository {
override fun save(newAccount: Account) { override fun save(account: Account) {
val accounts = load() val accounts = load()
val newList = accounts.filter { account -> newAccount.serverUrl != account.serverUrl } val newList = accounts.filter { account -> account.serverUrl != account.serverUrl }
.toMutableList() .toMutableList()
newList.add(0, newAccount) newList.add(0, account)
save(newList) save(newList)
} }
...@@ -28,7 +28,7 @@ class SharedPreferencesAccountsRepository( ...@@ -28,7 +28,7 @@ class SharedPreferencesAccountsRepository(
val type = Types.newParameterizedType(List::class.java, Account::class.java) val type = Types.newParameterizedType(List::class.java, Account::class.java)
val adapter = moshi.adapter<List<Account>>(type) val adapter = moshi.adapter<List<Account>>(type)
return adapter.fromJson(json) ?: emptyList() return if (json == null) emptyList() else adapter.fromJson(json) ?: emptyList()
} }
override fun remove(serverUrl: String) { override fun remove(serverUrl: String) {
......
...@@ -15,8 +15,7 @@ class SharedPrefsBasicAuthRepository( ...@@ -15,8 +15,7 @@ class SharedPrefsBasicAuthRepository(
) : BasicAuthRepository { ) : BasicAuthRepository {
override fun save(basicAuth: BasicAuth) { override fun save(basicAuth: BasicAuth) {
val newList = load().filter { basicAuth -> basicAuth.host != basicAuth.host } val newList = load().filter { item -> item.host != item.host }.toMutableList()
.toMutableList()
newList.add(0, basicAuth) newList.add(0, basicAuth)
save(newList) save(newList)
} }
...@@ -26,7 +25,7 @@ class SharedPrefsBasicAuthRepository( ...@@ -26,7 +25,7 @@ class SharedPrefsBasicAuthRepository(
val type = Types.newParameterizedType(List::class.java, BasicAuth::class.java) val type = Types.newParameterizedType(List::class.java, BasicAuth::class.java)
val adapter = moshi.adapter<List<BasicAuth>>(type) val adapter = moshi.adapter<List<BasicAuth>>(type)
return adapter.fromJson(json) ?: emptyList() return if (json == null) emptyList() else adapter.fromJson(json) ?: emptyList()
} }
private fun save(basicAuths: List<BasicAuth>) { private fun save(basicAuths: List<BasicAuth>) {
......
...@@ -51,6 +51,7 @@ class ChangeServerPresenter @Inject constructor( ...@@ -51,6 +51,7 @@ class ChangeServerPresenter @Inject constructor(
val settings = settingsRepository.get(serverUrl) val settings = settingsRepository.get(serverUrl)
if (settings == null) { if (settings == null) {
// TODO - reload settings... // TODO - reload settings...
// settingsRepository returns non nullable settings
} }
// Call disconnect on the old url if any... // Call disconnect on the old url if any...
......
...@@ -52,12 +52,9 @@ class UserDetailsFragment : Fragment(), UserDetailsView { ...@@ -52,12 +52,9 @@ class UserDetailsFragment : Fragment(), UserDetailsView {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
val bundle = arguments arguments?.run {
if (bundle != null) { userId = getString(BUNDLE_USER_ID, "")
userId = bundle.getString(BUNDLE_USER_ID) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
} else {
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
......
...@@ -193,7 +193,7 @@ class HttpLoggingInterceptor constructor(private val logger: Logger) : Intercept ...@@ -193,7 +193,7 @@ class HttpLoggingInterceptor constructor(private val logger: Logger) : Intercept
val responseBody = response.body() val responseBody = response.body()
val contentLength = responseBody!!.contentLength() val contentLength = responseBody!!.contentLength()
val bodySize = if (contentLength != -1L) contentLength.toString() + "-byte" else "unknown-length" val bodySize = if (contentLength != -1L) "$contentLength-byte" else "unknown-length"
val responseStr = if (response.message().isEmpty()) "" else " ${response.message()}" val responseStr = if (response.message().isEmpty()) "" else " ${response.message()}"
logger.log("<-- ${response.code()}$responseStr ${response.request().url()}" logger.log("<-- ${response.code()}$responseStr ${response.request().url()}"
+ " (" + tookMs + "ms" + (if (!logHeaders) ", $bodySize body" else "") + ')'.toString()) + " (" + tookMs + "ms" + (if (!logHeaders) ", $bodySize body" else "") + ')'.toString())
......
...@@ -69,11 +69,8 @@ fun String.userId(userId: String?): String? { ...@@ -69,11 +69,8 @@ fun String.userId(userId: String?): String? {
return userId?.let { this.replace(it, "") } return userId?.let { this.replace(it, "") }
} }
fun String.lowercaseUrl(): String? { fun String.lowercaseUrl(): String? = HttpUrl.parse(this)?.run {
val httpUrl = HttpUrl.parse(this) newBuilder().scheme(scheme().toLowerCase()).build().toString()
val newScheme = httpUrl?.scheme()?.toLowerCase()
return httpUrl?.newBuilder()?.scheme(newScheme)?.build()?.toString()
} }
fun String?.isNotNullNorEmpty(): Boolean = this != null && this.isNotEmpty() fun String?.isNotNullNorEmpty(): Boolean = this != null && this.isNotEmpty()
......
package chat.rocket.android.util.extensions
import android.content.Context
import android.os.Build
import android.widget.TextView
fun TextView.setTextViewAppearance(context: Context, style: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setTextAppearance(style)
} else {
setTextAppearance(context, style)
}
}
\ No newline at end of file
...@@ -27,13 +27,11 @@ class AdminPanelWebViewFragment : DaggerFragment() { ...@@ -27,13 +27,11 @@ class AdminPanelWebViewFragment : DaggerFragment() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
val bundle = arguments arguments?.run {
if (bundle != null) { webPageUrl = getString(BUNDLE_WEB_PAGE_URL, "")
webPageUrl = bundle.getString(BUNDLE_WEB_PAGE_URL) userToken = getString(BUNDLE_USER_TOKEN, "")
userToken = bundle.getString(BUNDLE_USER_TOKEN)
} else { } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
requireNotNull(bundle) { "no arguments supplied when the fragment was instantiated" }
}
} }
override fun onCreateView( override fun onCreateView(
...@@ -65,7 +63,7 @@ class AdminPanelWebViewFragment : DaggerFragment() { ...@@ -65,7 +63,7 @@ class AdminPanelWebViewFragment : DaggerFragment() {
web_view.webViewClient = object : WebViewClient() { web_view.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) { override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url) super.onPageFinished(view, url)
ui { _ -> ui {
view_loading.hide() view_loading.hide()
web_view.evaluateJavascript("Meteor.loginWithToken('$userToken', function() { })") {} web_view.evaluateJavascript("Meteor.loginWithToken('$userToken', function() { })") {}
} }
......
...@@ -14,7 +14,7 @@ import androidx.recyclerview.widget.RecyclerView ...@@ -14,7 +14,7 @@ import androidx.recyclerview.widget.RecyclerView
* @see RecyclerView.ItemDecoration * @see RecyclerView.ItemDecoration
*/ */
class DividerItemDecoration() : RecyclerView.ItemDecoration() { class DividerItemDecoration() : RecyclerView.ItemDecoration() {
private lateinit var divider: Drawable private var divider: Drawable? = null
private var boundStart = 0 private var boundStart = 0
private var boundEnd = 0 private var boundEnd = 0
...@@ -59,10 +59,10 @@ class DividerItemDecoration() : RecyclerView.ItemDecoration() { ...@@ -59,10 +59,10 @@ class DividerItemDecoration() : RecyclerView.ItemDecoration() {
val params = child.layoutParams as RecyclerView.LayoutParams val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin val top = child.bottom + params.bottomMargin
val bottom = top + divider.intrinsicHeight val bottom = top + (divider?.intrinsicHeight ?: 0)
divider.setBounds(left, top, right, bottom) divider?.setBounds(left, top, right, bottom)
divider.draw(c) divider?.draw(c)
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment