Unverified Commit 380d3688 authored by Rafael Kellermann Streit's avatar Rafael Kellermann Streit Committed by GitHub

Merge pull request #1204 from RocketChat/fix/reply-with-username

[FIX] Use username when building replies always
parents 6b2bdf3b 7eaa9971
...@@ -104,7 +104,6 @@ dependencies { ...@@ -104,7 +104,6 @@ dependencies {
implementation libraries.frescoImageViewer implementation libraries.frescoImageViewer
implementation libraries.markwon implementation libraries.markwon
implementation libraries.markwonImageLoader
implementation libraries.sheetMenu implementation libraries.sheetMenu
......
...@@ -14,11 +14,11 @@ import timber.log.Timber ...@@ -14,11 +14,11 @@ import timber.log.Timber
import java.security.InvalidParameterException import java.security.InvalidParameterException
class ChatRoomAdapter( class ChatRoomAdapter(
private val roomType: String, private val roomType: String,
private val roomName: String, private val roomName: String,
private val presenter: ChatRoomPresenter?, private val presenter: ChatRoomPresenter?,
private val enableActions: Boolean = true, private val enableActions: Boolean = true,
private val reactionListener: EmojiReactionListener? = null private val reactionListener: EmojiReactionListener? = null
) : RecyclerView.Adapter<BaseViewHolder<*>>() { ) : RecyclerView.Adapter<BaseViewHolder<*>>() {
private val dataSet = ArrayList<BaseViewModel<*>>() private val dataSet = ArrayList<BaseViewModel<*>>()
...@@ -175,15 +175,15 @@ class ChatRoomAdapter( ...@@ -175,15 +175,15 @@ class ChatRoomAdapter(
} }
} }
val actionsListener = object : BaseViewHolder.ActionsListener { private val actionsListener = object : BaseViewHolder.ActionsListener {
override fun isActionsEnabled(): Boolean = enableActions override fun isActionsEnabled(): Boolean = enableActions
override fun onActionSelected(item: MenuItem, message: Message) { override fun onActionSelected(item: MenuItem, message: Message) {
message.apply { message.apply {
when (item.itemId) { when (item.itemId) {
R.id.action_menu_msg_delete -> presenter?.deleteMessage(roomId, id) R.id.action_menu_msg_delete -> presenter?.deleteMessage(roomId, id)
R.id.action_menu_msg_quote -> presenter?.citeMessage(roomType, roomName, id, false) R.id.action_menu_msg_quote -> presenter?.citeMessage(roomType, id, false)
R.id.action_menu_msg_reply -> presenter?.citeMessage(roomType, roomName, id, true) R.id.action_menu_msg_reply -> presenter?.citeMessage(roomType, id, true)
R.id.action_menu_msg_copy -> presenter?.copyMessage(id) R.id.action_menu_msg_copy -> presenter?.copyMessage(id)
R.id.action_menu_msg_edit -> presenter?.editMessage(roomId, id, message.message) R.id.action_menu_msg_edit -> presenter?.editMessage(roomId, id, message.message)
R.id.action_menu_msg_pin_unpin -> { R.id.action_menu_msg_pin_unpin -> {
......
...@@ -31,7 +31,6 @@ import chat.rocket.core.internal.rest.* ...@@ -31,7 +31,6 @@ import chat.rocket.core.internal.rest.*
import chat.rocket.core.model.Command import chat.rocket.core.model.Command
import chat.rocket.core.model.Message import chat.rocket.core.model.Message
import chat.rocket.core.model.Myself import chat.rocket.core.model.Myself
import chat.rocket.core.model.Value
import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.async
...@@ -59,10 +58,11 @@ class ChatRoomPresenter @Inject constructor( ...@@ -59,10 +58,11 @@ class ChatRoomPresenter @Inject constructor(
private val mapper: ViewModelMapper, private val mapper: ViewModelMapper,
private val jobSchedulerInteractor: JobSchedulerInteractor private val jobSchedulerInteractor: JobSchedulerInteractor
) { ) {
private val currentServer = serverInteractor.get()!! private val currentServer = serverInteractor.get()!!
private val manager = factory.create(currentServer) private val manager = factory.create(currentServer)
private val client = manager.client private val client = manager.client
private var settings: Map<String, Value<Any>> = getSettingsInteractor.get(serverInteractor.get()!!) private var settings: PublicSettings = getSettingsInteractor.get(serverInteractor.get()!!)
private val messagesChannel = Channel<Message>() private val messagesChannel = Channel<Message>()
private var chatRoomId: String? = null private var chatRoomId: String? = null
...@@ -194,7 +194,7 @@ class ChatRoomPresenter @Inject constructor( ...@@ -194,7 +194,7 @@ class ChatRoomPresenter @Inject constructor(
} }
} catch (ex: Exception) { } catch (ex: Exception) {
Timber.d(ex, "Error uploading file") Timber.d(ex, "Error uploading file")
when(ex) { when (ex) {
is RocketChatException -> view.showMessage(ex) is RocketChatException -> view.showMessage(ex)
else -> view.showGenericErrorMessage() else -> view.showGenericErrorMessage()
} }
...@@ -279,7 +279,6 @@ class ChatRoomPresenter @Inject constructor( ...@@ -279,7 +279,6 @@ class ChatRoomPresenter @Inject constructor(
// TODO - we need to better treat connection problems here, but no let gaps // TODO - we need to better treat connection problems here, but no let gaps
// on the messages list // on the messages list
Timber.d(ex, "Error fetching channel history") Timber.d(ex, "Error fetching channel history")
ex.printStackTrace()
} }
} }
} }
...@@ -326,43 +325,37 @@ class ChatRoomPresenter @Inject constructor( ...@@ -326,43 +325,37 @@ class ChatRoomPresenter @Inject constructor(
* Quote or reply a message. * Quote or reply a message.
* *
* @param roomType The current room type. * @param roomType The current room type.
* @param roomName The name of the current room.
* @param messageId The id of the message to make citation for. * @param messageId The id of the message to make citation for.
* @param mentionAuthor true means the citation is a reply otherwise it's a quote. * @param mentionAuthor true means the citation is a reply otherwise it's a quote.
*/ */
fun citeMessage(roomType: String, roomName: String, messageId: String, mentionAuthor: Boolean) { fun citeMessage(roomType: String, messageId: String, mentionAuthor: Boolean) {
launchUI(strategy) { launchUI(strategy) {
val message = messagesRepository.getById(messageId) val message = messagesRepository.getById(messageId)
val me: Myself? = try { val me: Myself? = try {
retryIO("me()") { client.me() } //TODO: Cache this and use an interactor retryIO("me()") { client.me() } //TODO: Cache this and use an interactor
} catch (ex: Exception) { } catch (ex: Exception) {
Timber.d(ex, "Error getting myself info.") Timber.e(ex)
ex.printStackTrace()
null null
} }
message?.let { m -> message?.let { msg ->
val id = m.id val id = msg.id
val username = m.sender?.username val username = msg.sender?.username ?: ""
val user = "@" + if (settings.useRealName()) m.sender?.name val mention = if (mentionAuthor && me?.username != username) "@$username" else ""
?: m.sender?.username else m.sender?.username val room = if (roomTypeOf(roomType) is RoomType.DirectMessage) username else roomType
val mention = if (mentionAuthor && me?.username != username) user else ""
val type = roomTypeOf(roomType)
val room = when (type) {
is RoomType.Channel -> "channel"
is RoomType.DirectMessage -> "direct"
is RoomType.PrivateGroup -> "group"
is RoomType.Livechat -> "livechat"
is RoomType.Custom -> "custom" //TODO: put appropriate callback string here.
}
view.showReplyingAction( view.showReplyingAction(
username = user, username = getDisplayName(msg.sender),
replyMarkdown = "[ ]($currentServer/$room/$roomName?msg=$id) $mention ", replyMarkdown = "[ ]($currentServer/$roomType/$room?msg=$id) $mention ",
quotedMessage = mapper.map(message).last().preview?.message ?: "" quotedMessage = mapper.map(message).last().preview?.message ?: ""
) )
} }
} }
} }
private fun getDisplayName(user: SimpleUser?): String {
val username = user?.username ?: ""
return if (settings.useRealName()) user?.name ?: "@$username" else "@$username"
}
/** /**
* Copy message to clipboard. * Copy message to clipboard.
* *
......
...@@ -48,10 +48,8 @@ import okhttp3.Interceptor ...@@ -48,10 +48,8 @@ import okhttp3.Interceptor
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor
import ru.noties.markwon.SpannableConfiguration import ru.noties.markwon.SpannableConfiguration
import ru.noties.markwon.il.AsyncDrawableLoader
import ru.noties.markwon.spans.SpannableTheme import ru.noties.markwon.spans.SpannableTheme
import timber.log.Timber import timber.log.Timber
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.inject.Singleton import javax.inject.Singleton
...@@ -264,11 +262,6 @@ class AppModule { ...@@ -264,11 +262,6 @@ class AppModule {
fun provideConfiguration(context: Application, client: OkHttpClient): SpannableConfiguration { fun provideConfiguration(context: Application, client: OkHttpClient): SpannableConfiguration {
val res = context.resources val res = context.resources
return SpannableConfiguration.builder(context) return SpannableConfiguration.builder(context)
.asyncDrawableLoader(AsyncDrawableLoader.builder()
.client(client)
.executorService(Executors.newCachedThreadPool())
.resources(res)
.build())
.theme(SpannableTheme.builder() .theme(SpannableTheme.builder()
.linkColor(res.getColor(R.color.colorAccent)) .linkColor(res.getColor(R.color.colorAccent))
.build()) .build())
...@@ -277,8 +270,9 @@ class AppModule { ...@@ -277,8 +270,9 @@ class AppModule {
@Provides @Provides
@Singleton @Singleton
fun provideMessageParser(context: Application, configuration: SpannableConfiguration): MessageParser { fun provideMessageParser(context: Application, configuration: SpannableConfiguration, serverInteractor: GetCurrentServerInteractor, settingsInteractor: GetSettingsInteractor): MessageParser {
return MessageParser(context, configuration) val url = serverInteractor.get()!!
return MessageParser(context, configuration, settingsInteractor.get(url))
} }
@Provides @Provides
......
package chat.rocket.android.helper package chat.rocket.android.helper
import android.app.Application import android.app.Application
import android.content.ActivityNotFoundException
import android.content.Context import android.content.Context
import android.content.Intent
import android.graphics.Canvas import android.graphics.Canvas
import android.graphics.Paint import android.graphics.Paint
import android.graphics.RectF import android.graphics.RectF
import android.net.Uri import android.net.Uri
import android.support.customtabs.CustomTabsIntent import android.support.customtabs.CustomTabsIntent
import android.provider.Browser
import android.support.v4.content.res.ResourcesCompat import android.support.v4.content.res.ResourcesCompat
import android.text.Spanned import android.text.Spanned
import android.text.style.ClickableSpan import android.text.style.ClickableSpan
...@@ -17,6 +14,8 @@ import android.text.style.ReplacementSpan ...@@ -17,6 +14,8 @@ import android.text.style.ReplacementSpan
import android.util.Patterns import android.util.Patterns
import android.view.View import android.view.View
import chat.rocket.android.R import chat.rocket.android.R
import chat.rocket.android.server.domain.PublicSettings
import chat.rocket.android.server.domain.useRealName
import chat.rocket.android.widget.emoji.EmojiParser import chat.rocket.android.widget.emoji.EmojiParser
import chat.rocket.android.widget.emoji.EmojiRepository import chat.rocket.android.widget.emoji.EmojiRepository
import chat.rocket.android.widget.emoji.EmojiTypefaceSpan import chat.rocket.android.widget.emoji.EmojiTypefaceSpan
...@@ -29,10 +28,13 @@ import ru.noties.markwon.Markwon ...@@ -29,10 +28,13 @@ import ru.noties.markwon.Markwon
import ru.noties.markwon.SpannableBuilder import ru.noties.markwon.SpannableBuilder
import ru.noties.markwon.SpannableConfiguration import ru.noties.markwon.SpannableConfiguration
import ru.noties.markwon.renderer.SpannableMarkdownVisitor import ru.noties.markwon.renderer.SpannableMarkdownVisitor
import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
class MessageParser @Inject constructor(val context: Application, private val configuration: SpannableConfiguration) { class MessageParser @Inject constructor(
private val context: Application,
private val configuration: SpannableConfiguration,
private val settings: PublicSettings
) {
private val parser = Markwon.createParser() private val parser = Markwon.createParser()
...@@ -53,7 +55,7 @@ class MessageParser @Inject constructor(val context: Application, private val co ...@@ -53,7 +55,7 @@ class MessageParser @Inject constructor(val context: Application, private val co
parentNode.accept(LinkVisitor(builder)) parentNode.accept(LinkVisitor(builder))
parentNode.accept(EmojiVisitor(configuration, builder)) parentNode.accept(EmojiVisitor(configuration, builder))
message.mentions?.let { message.mentions?.let {
parentNode.accept(MentionVisitor(context, builder, it, selfUsername)) parentNode.accept(MentionVisitor(context, builder, it, selfUsername, settings))
} }
return builder.text() return builder.text()
...@@ -62,23 +64,31 @@ class MessageParser @Inject constructor(val context: Application, private val co ...@@ -62,23 +64,31 @@ class MessageParser @Inject constructor(val context: Application, private val co
// Convert to a lenient markdown consistent with Rocket.Chat web markdown instead of the official specs. // Convert to a lenient markdown consistent with Rocket.Chat web markdown instead of the official specs.
private fun toLenientMarkdown(text: String): String { private fun toLenientMarkdown(text: String): String {
return text.trim().replace("\\*(.+)\\*".toRegex()) { "**${it.groupValues[1].trim()}**" } return text.trim().replace("\\*(.+)\\*".toRegex()) { "**${it.groupValues[1].trim()}**" }
.replace("\\~(.+)\\~".toRegex()) { "~~${it.groupValues[1].trim()}~~" } .replace("\\~(.+)\\~".toRegex()) { "~~${it.groupValues[1].trim()}~~" }
.replace("\\_(.+)\\_".toRegex()) { "_${it.groupValues[1].trim()}_" } .replace("\\_(.+)\\_".toRegex()) { "_${it.groupValues[1].trim()}_" }
} }
class MentionVisitor(context: Context, class MentionVisitor(
private val builder: SpannableBuilder, context: Context,
private val mentions: List<SimpleUser>, private val builder: SpannableBuilder,
private val currentUser: String?) : AbstractVisitor() { private val mentions: List<SimpleUser>,
private val currentUser: String?,
private val settings: PublicSettings
) : AbstractVisitor() {
private val othersTextColor = ResourcesCompat.getColor(context.resources, R.color.colorAccent, context.theme) private val othersTextColor = ResourcesCompat.getColor(context.resources, R.color.colorAccent, context.theme)
private val othersBackgroundColor = ResourcesCompat.getColor(context.resources, android.R.color.transparent, context.theme) private val othersBackgroundColor = ResourcesCompat.getColor(context.resources, android.R.color.transparent, context.theme)
private val myselfTextColor = ResourcesCompat.getColor(context.resources, R.color.white, context.theme) private val myselfTextColor = ResourcesCompat.getColor(context.resources, R.color.white, context.theme)
private val myselfBackgroundColor = ResourcesCompat.getColor(context.resources, R.color.colorAccent, context.theme) private val myselfBackgroundColor = ResourcesCompat.getColor(context.resources, R.color.colorAccent, context.theme)
private val mentionPadding = context.resources.getDimensionPixelSize(R.dimen.padding_mention).toFloat() private val mentionPadding = context.resources.getDimensionPixelSize(R.dimen.padding_mention).toFloat()
private val mentionRadius = context.resources.getDimensionPixelSize(R.dimen.radius_mention).toFloat() private val mentionRadius = context.resources.getDimensionPixelSize(R.dimen.radius_mention).toFloat()
override fun visit(t: Text) { override fun visit(t: Text) {
val text = t.literal val text = t.literal
val mentionsList = mentions.map { it.username }.toMutableList() val mentionsList = mentions.map {
if (settings.useRealName()) it.name else it.username ?: ""
}.toMutableList()
mentionsList.add("all") mentionsList.add("all")
mentionsList.add("here") mentionsList.add("here")
...@@ -90,7 +100,7 @@ class MessageParser @Inject constructor(val context: Application, private val co ...@@ -90,7 +100,7 @@ class MessageParser @Inject constructor(val context: Application, private val co
val textColor = if (mentionMe) myselfTextColor else othersTextColor val textColor = if (mentionMe) myselfTextColor else othersTextColor
val backgroundColor = if (mentionMe) myselfBackgroundColor else othersBackgroundColor val backgroundColor = if (mentionMe) myselfBackgroundColor else othersBackgroundColor
val usernameSpan = MentionSpan(backgroundColor, textColor, mentionRadius, mentionPadding, val usernameSpan = MentionSpan(backgroundColor, textColor, mentionRadius, mentionPadding,
mentionMe) mentionMe)
// Add 1 to end offset to include the @. // Add 1 to end offset to include the @.
val end = offset + it.length + 1 val end = offset + it.length + 1
builder.setSpan(usernameSpan, offset, end, 0) builder.setSpan(usernameSpan, offset, end, 0)
...@@ -101,8 +111,11 @@ class MessageParser @Inject constructor(val context: Application, private val co ...@@ -101,8 +111,11 @@ class MessageParser @Inject constructor(val context: Application, private val co
} }
} }
class EmojiVisitor(configuration: SpannableConfiguration, private val builder: SpannableBuilder) class EmojiVisitor(
: SpannableMarkdownVisitor(configuration, builder) { configuration: SpannableConfiguration,
private val builder: SpannableBuilder
) : SpannableMarkdownVisitor(configuration, builder) {
override fun visit(document: Document) { override fun visit(document: Document) {
val spannable = EmojiParser.parse(builder.text()) val spannable = EmojiParser.parse(builder.text())
if (spannable is Spanned) { if (spannable is Spanned) {
...@@ -127,7 +140,7 @@ class MessageParser @Inject constructor(val context: Application, private val co ...@@ -127,7 +140,7 @@ class MessageParser @Inject constructor(val context: Application, private val co
if (!link.startsWith("@") && link !in consumed) { if (!link.startsWith("@") && link !in consumed) {
builder.setSpan(object : ClickableSpan() { builder.setSpan(object : ClickableSpan() {
override fun onClick(view: View) { override fun onClick(view: View) {
with (view) { with(view) {
val tabsbuilder = CustomTabsIntent.Builder() val tabsbuilder = CustomTabsIntent.Builder()
tabsbuilder.setToolbarColor(ResourcesCompat.getColor(context.resources, R.color.colorPrimary, context.theme)) tabsbuilder.setToolbarColor(ResourcesCompat.getColor(context.resources, R.color.colorPrimary, context.theme))
val customTabsIntent = tabsbuilder.build() val customTabsIntent = tabsbuilder.build()
...@@ -150,11 +163,14 @@ class MessageParser @Inject constructor(val context: Application, private val co ...@@ -150,11 +163,14 @@ class MessageParser @Inject constructor(val context: Application, private val co
} }
} }
class MentionSpan(private val backgroundColor: Int, class MentionSpan(
private val textColor: Int, private val backgroundColor: Int,
private val radius: Float, private val textColor: Int,
padding: Float, private val radius: Float,
referSelf: Boolean) : ReplacementSpan() { padding: Float,
referSelf: Boolean
) : ReplacementSpan() {
private val padding: Float = if (referSelf) padding else 0F private val padding: Float = if (referSelf) padding else 0F
override fun getSize(paint: Paint, override fun getSize(paint: Paint,
......
...@@ -91,7 +91,6 @@ ext { ...@@ -91,7 +91,6 @@ ext {
frescoImageViewer : "com.github.luciofm:FrescoImageViewer:${versions.frescoImageViewer}", frescoImageViewer : "com.github.luciofm:FrescoImageViewer:${versions.frescoImageViewer}",
markwon : "ru.noties:markwon:${versions.markwon}", markwon : "ru.noties:markwon:${versions.markwon}",
markwonImageLoader : "ru.noties:markwon-image-loader:${versions.markwon}",
sheetMenu : "com.github.whalemare:sheetmenu:${versions.sheetMenu}", sheetMenu : "com.github.whalemare:sheetmenu:${versions.sheetMenu}",
......
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