Commit 3715659e authored by Lucio Maciel's avatar Lucio Maciel

Merge branch 'develop' into new/generic-file-attachment

parents 7fae0085 380d3688
...@@ -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
......
...@@ -207,6 +207,31 @@ class LoginPresenter @Inject constructor( ...@@ -207,6 +207,31 @@ class LoginPresenter @Inject constructor(
} }
} }
getCustomOauthServices(services).let {
for (service in it) {
val serviceName = getCustomOauthServiceName(service)
val customOauthUrl = OauthHelper.getCustomOauthUrl(
getCustomOauthHost(service),
getCustomOauthAuthorizePath(service),
getCustomOauthClientId(service),
currentServer,
serviceName,
state,
getCustomOauthScope(service)
)
view.addCustomOauthServiceButton(
customOauthUrl,
state,
serviceName,
getCustomOauthServiceNameColor(service),
getCustomOauthButtonColor(service)
)
totalSocialAccountsEnabled++
}
}
if (totalSocialAccountsEnabled > 0) { if (totalSocialAccountsEnabled > 0) {
view.enableOauthView() view.enableOauthView()
if (totalSocialAccountsEnabled > 3) { if (totalSocialAccountsEnabled > 3) {
...@@ -299,6 +324,38 @@ class LoginPresenter @Inject constructor( ...@@ -299,6 +324,38 @@ class LoginPresenter @Inject constructor(
}.toString() }.toString()
} }
private fun getCustomOauthServices(listMap: List<Map<String, Any>>): List<Map<String, Any>> {
return listMap.filter { map -> map["custom"] == true }
}
private fun getCustomOauthHost(service: Map<String, Any>): String {
return service["serverURL"].toString()
}
private fun getCustomOauthAuthorizePath(service: Map<String, Any>): String {
return service["authorizePath"].toString()
}
private fun getCustomOauthClientId(service: Map<String, Any>): String {
return service["clientId"].toString()
}
private fun getCustomOauthServiceName(service: Map<String, Any>): String {
return service["service"].toString()
}
private fun getCustomOauthScope(service: Map<String, Any>): String {
return service["scope"].toString()
}
private fun getCustomOauthButtonColor(service: Map<String, Any>): Int {
return service["buttonColor"].toString().parseColor()
}
private fun getCustomOauthServiceNameColor(service: Map<String, Any>): Int {
return service["buttonLabelColor"].toString().parseColor()
}
private suspend fun saveAccount(username: String) { private suspend fun saveAccount(username: String) {
val icon = settings.favicon()?.let { val icon = settings.favicon()?.let {
currentServer.serverLogoUrl(it) currentServer.serverLogoUrl(it)
......
package chat.rocket.android.authentication.login.presentation package chat.rocket.android.authentication.login.presentation
import chat.rocket.android.authentication.server.presentation.VersionCheckView
import chat.rocket.android.core.behaviours.LoadingView import chat.rocket.android.core.behaviours.LoadingView
import chat.rocket.android.core.behaviours.MessageView import chat.rocket.android.core.behaviours.MessageView
...@@ -75,7 +74,7 @@ interface LoginView : LoadingView, MessageView { ...@@ -75,7 +74,7 @@ interface LoginView : LoadingView, MessageView {
* Enables and shows the oauth view if there is login via social accounts enabled by the server settings. * Enables and shows the oauth view if there is login via social accounts enabled by the server settings.
* *
* REMARK: We must show at maximum *three* social accounts views ([enableLoginByFacebook], [enableLoginByGithub], [enableLoginByGoogle], * REMARK: We must show at maximum *three* social accounts views ([enableLoginByFacebook], [enableLoginByGithub], [enableLoginByGoogle],
* [enableLoginByLinkedin], [enableLoginByMeteor], [enableLoginByTwitter] or [enableLoginByGitlab]) for the oauth view. * [enableLoginByLinkedin], [enableLoginByMeteor], [enableLoginByTwitter], [enableLoginByGitlab] or [addCustomOauthServiceButton]) for the oauth view.
* If the possibility of login via social accounts exceeds 3 different ways we should set up the FAB ([setupFabListener]) to show the remaining view(s). * If the possibility of login via social accounts exceeds 3 different ways we should set up the FAB ([setupFabListener]) to show the remaining view(s).
*/ */
fun enableOauthView() fun enableOauthView()
...@@ -178,6 +177,24 @@ interface LoginView : LoadingView, MessageView { ...@@ -178,6 +177,24 @@ interface LoginView : LoadingView, MessageView {
*/ */
fun setupGitlabButtonListener(gitlabUrl: String, state: String) fun setupGitlabButtonListener(gitlabUrl: String, state: String)
/**
* Adds a custom OAuth button in the oauth view.
*
* @customOauthUrl The custom OAuth url to sets up the button (the listener).
* @state A random string generated by the app, which you'll verify later (to protect against forgery attacks).
* @serviceName The custom OAuth service name.
* @serviceNameColor The custom OAuth service name color (just stylizing).
* @buttonColor The color of the custom OAuth button (just stylizing).
* @see [enableOauthView]
*/
fun addCustomOauthServiceButton(
customOauthUrl: String,
state: String,
serviceName: String,
serviceNameColor: Int,
buttonColor: Int
)
/** /**
* Setups the FloatingActionButton to show more social accounts views (expanding the oauth view interface to show the remaining view(s)). * Setups the FloatingActionButton to show more social accounts views (expanding the oauth view interface to show the remaining view(s)).
*/ */
......
...@@ -180,15 +180,15 @@ class ChatRoomAdapter( ...@@ -180,15 +180,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.
* *
......
...@@ -5,7 +5,6 @@ import android.content.Context ...@@ -5,7 +5,6 @@ import android.content.Context
import android.graphics.Color import android.graphics.Color
import android.graphics.Typeface import android.graphics.Typeface
import android.support.v4.content.ContextCompat import android.support.v4.content.ContextCompat
import android.text.Html
import android.text.SpannableStringBuilder import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan import android.text.style.StyleSpan
...@@ -32,21 +31,21 @@ import okhttp3.HttpUrl ...@@ -32,21 +31,21 @@ import okhttp3.HttpUrl
import java.security.InvalidParameterException import java.security.InvalidParameterException
import javax.inject.Inject import javax.inject.Inject
class ViewModelMapper @Inject constructor(private val context: Context, class ViewModelMapper @Inject constructor(
private val context: Context,
private val parser: MessageParser, private val parser: MessageParser,
private val messagesRepository: MessagesRepository,
private val getAccountInteractor: GetAccountInteractor,
tokenRepository: TokenRepository, tokenRepository: TokenRepository,
serverInteractor: GetCurrentServerInteractor, serverInteractor: GetCurrentServerInteractor,
getSettingsInteractor: GetSettingsInteractor, getSettingsInteractor: GetSettingsInteractor,
localRepository: LocalRepository) { localRepository: LocalRepository
) {
private val currentServer = serverInteractor.get()!! private val currentServer = serverInteractor.get()!!
private val settings: Map<String, Value<Any>> = getSettingsInteractor.get(currentServer) private val settings: Map<String, Value<Any>> = getSettingsInteractor.get(currentServer)
private val baseUrl = settings.baseUrl() private val baseUrl = settings.baseUrl()
private val token = tokenRepository.get(currentServer) private val token = tokenRepository.get(currentServer)
private val currentUsername: String? = localRepository.get(LocalRepository.CURRENT_USERNAME_KEY) private val currentUsername: String? = localRepository.get(LocalRepository.CURRENT_USERNAME_KEY)
private val secundaryTextColor = ContextCompat.getColor(context, R.color.colorSecondaryText) private val secondaryTextColor = ContextCompat.getColor(context, R.color.colorSecondaryText)
suspend fun map(message: Message): List<BaseViewModel<*>> { suspend fun map(message: Message): List<BaseViewModel<*>> {
return translate(message) return translate(message)
...@@ -102,7 +101,7 @@ class ViewModelMapper @Inject constructor(private val context: Context, ...@@ -102,7 +101,7 @@ class ViewModelMapper @Inject constructor(private val context: Context,
getReactions(message), preview = message.copy(message = url.url)) getReactions(message), preview = message.copy(message = url.url))
} }
private suspend fun mapAttachment(message: Message, attachment: Attachment): BaseViewModel<*>? { private fun mapAttachment(message: Message, attachment: Attachment): BaseViewModel<*>? {
return when (attachment) { return when (attachment) {
is FileAttachment -> mapFileAttachment(message, attachment) is FileAttachment -> mapFileAttachment(message, attachment)
is MessageAttachment -> mapMessageAttachment(message, attachment) is MessageAttachment -> mapMessageAttachment(message, attachment)
...@@ -112,7 +111,7 @@ class ViewModelMapper @Inject constructor(private val context: Context, ...@@ -112,7 +111,7 @@ class ViewModelMapper @Inject constructor(private val context: Context,
} }
} }
private suspend fun mapColorAttachment(message: Message, attachment: ColorAttachment): BaseViewModel<*>? { private fun mapColorAttachment(message: Message, attachment: ColorAttachment): BaseViewModel<*>? {
return with(attachment) { return with(attachment) {
val content = stripMessageQuotes(message) val content = stripMessageQuotes(message)
val id = attachmentId(message, attachment) val id = attachmentId(message, attachment)
...@@ -124,7 +123,7 @@ class ViewModelMapper @Inject constructor(private val context: Context, ...@@ -124,7 +123,7 @@ class ViewModelMapper @Inject constructor(private val context: Context,
} }
} }
private suspend fun mapAuthorAttachment(message: Message, attachment: AuthorAttachment): AuthorAttachmentViewModel { private fun mapAuthorAttachment(message: Message, attachment: AuthorAttachment): AuthorAttachmentViewModel {
return with(attachment) { return with(attachment) {
val content = stripMessageQuotes(message) val content = stripMessageQuotes(message)
...@@ -152,7 +151,7 @@ class ViewModelMapper @Inject constructor(private val context: Context, ...@@ -152,7 +151,7 @@ class ViewModelMapper @Inject constructor(private val context: Context,
} }
} }
private suspend fun mapMessageAttachment(message: Message, attachment: MessageAttachment): MessageAttachmentViewModel { private fun mapMessageAttachment(message: Message, attachment: MessageAttachment): MessageAttachmentViewModel {
val attachmentAuthor = attachment.author val attachmentAuthor = attachment.author
val time = attachment.timestamp?.let { getTime(it) } val time = attachment.timestamp?.let { getTime(it) }
val attachmentText = when (attachment.attachments.orEmpty().firstOrNull()) { val attachmentText = when (attachment.attachments.orEmpty().firstOrNull()) {
...@@ -239,7 +238,7 @@ class ViewModelMapper @Inject constructor(private val context: Context, ...@@ -239,7 +238,7 @@ class ViewModelMapper @Inject constructor(private val context: Context,
isFirstUnread = false, preview = preview, isTemporary = isTemp) isFirstUnread = false, preview = preview, isTemporary = isTemp)
} }
private suspend fun mapMessagePreview(message: Message): Message { private fun mapMessagePreview(message: Message): Message {
return when (message.isSystemMessage()) { return when (message.isSystemMessage()) {
false -> stripMessageQuotes(message) false -> stripMessageQuotes(message)
true -> message.copy(message = getSystemMessage(message).toString()) true -> message.copy(message = getSystemMessage(message).toString())
...@@ -265,7 +264,7 @@ class ViewModelMapper @Inject constructor(private val context: Context, ...@@ -265,7 +264,7 @@ class ViewModelMapper @Inject constructor(private val context: Context,
return reactions ?: emptyList() return reactions ?: emptyList()
} }
private suspend fun stripMessageQuotes(message: Message): Message { private fun stripMessageQuotes(message: Message): Message {
val baseUrl = settings.baseUrl() val baseUrl = settings.baseUrl()
return message.copy( return message.copy(
message = message.message.replace("\\[[^\\]]+\\]\\($baseUrl[^)]+\\)".toRegex(), "").trim() message = message.message.replace("\\[[^\\]]+\\]\\($baseUrl[^)]+\\)".toRegex(), "").trim()
...@@ -280,7 +279,7 @@ class ViewModelMapper @Inject constructor(private val context: Context, ...@@ -280,7 +279,7 @@ class ViewModelMapper @Inject constructor(private val context: Context,
username?.let { username?.let {
append(" ") append(" ")
scale(0.8f) { scale(0.8f) {
color(secundaryTextColor) { color(secondaryTextColor) {
append("@$username") append("@$username")
} }
} }
...@@ -306,7 +305,7 @@ class ViewModelMapper @Inject constructor(private val context: Context, ...@@ -306,7 +305,7 @@ class ViewModelMapper @Inject constructor(private val context: Context,
private fun getTime(timestamp: Long) = DateTimeHelper.getTime(DateTimeHelper.getLocalDateTime(timestamp)) private fun getTime(timestamp: Long) = DateTimeHelper.getTime(DateTimeHelper.getLocalDateTime(timestamp))
private suspend fun getContent(message: Message): CharSequence { private fun getContent(message: Message): CharSequence {
return when (message.isSystemMessage()) { return when (message.isSystemMessage()) {
true -> getSystemMessage(message) true -> getSystemMessage(message)
false -> parser.renderMarkdown(message, currentUsername) false -> parser.renderMarkdown(message, currentUsername)
......
...@@ -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
...@@ -265,11 +263,6 @@ class AppModule { ...@@ -265,11 +263,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())
...@@ -278,8 +271,9 @@ class AppModule { ...@@ -278,8 +271,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()
...@@ -66,19 +68,27 @@ class MessageParser @Inject constructor(val context: Application, private val co ...@@ -66,19 +68,27 @@ class MessageParser @Inject constructor(val context: Application, private val co
.replace("\\_(.+)\\_".toRegex()) { "_${it.groupValues[1].trim()}_" } .replace("\\_(.+)\\_".toRegex()) { "_${it.groupValues[1].trim()}_" }
} }
class MentionVisitor(context: Context, class MentionVisitor(
context: Context,
private val builder: SpannableBuilder, private val builder: SpannableBuilder,
private val mentions: List<SimpleUser>, private val mentions: List<SimpleUser>,
private val currentUser: String?) : AbstractVisitor() { 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")
...@@ -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 backgroundColor: Int,
private val textColor: Int, private val textColor: Int,
private val radius: Float, private val radius: Float,
padding: Float, padding: Float,
referSelf: Boolean) : ReplacementSpan() { 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,4 +91,34 @@ object OauthHelper { ...@@ -91,4 +91,34 @@ object OauthHelper {
"&response_type=code" + "&response_type=code" +
"&scope=email" "&scope=email"
} }
/**
* Returns the Custom Oauth URL.
*
* @param host The custom OAuth host.
* @param authorizePath The OAuth authorization path.
* @param clientId The custom OAuth client ID.
* @param serverUrl The server URL.
* @param serviceName The service name.
* @param state An unguessable random string used to protect against forgery attacks.
* @param scope The custom OAuth scope.
* @return The Custom Oauth URL.
*/
fun getCustomOauthUrl(
host: String,
authorizePath: String,
clientId: String,
serverUrl: String,
serviceName: String,
state: String,
scope: String
): String {
return host +
authorizePath +
"?client_id=$clientId" +
"&redirect_uri=${serverUrl.removeTrailingSlash()}/_oauth/$serviceName" +
"&state=$state" +
"&scope=$scope" +
"&response_type=code"
}
} }
package chat.rocket.android.util.extensions package chat.rocket.android.util.extensions
import android.graphics.Color
import android.util.Patterns import android.util.Patterns
import timber.log.Timber
fun String.removeTrailingSlash(): String { fun String.removeTrailingSlash(): String {
return if (isNotEmpty() && this[length - 1] == '/') { return if (isNotEmpty() && this[length - 1] == '/') {
...@@ -33,3 +35,13 @@ fun String.termsOfServiceUrl() = "${removeTrailingSlash()}/terms-of-service" ...@@ -33,3 +35,13 @@ fun String.termsOfServiceUrl() = "${removeTrailingSlash()}/terms-of-service"
fun String.privacyPolicyUrl() = "${removeTrailingSlash()}/privacy-policy" fun String.privacyPolicyUrl() = "${removeTrailingSlash()}/privacy-policy"
fun String.isValidUrl(): Boolean = Patterns.WEB_URL.matcher(this).matches() fun String.isValidUrl(): Boolean = Patterns.WEB_URL.matcher(this).matches()
fun String.parseColor(): Int {
return try {
Color.parseColor(this)
} catch (exception: IllegalArgumentException) {
// Log the exception and get the white color.
Timber.e(exception)
Color.parseColor("white")
}
}
\ No newline at end of file
...@@ -15,6 +15,7 @@ import android.view.inputmethod.InputMethodManager ...@@ -15,6 +15,7 @@ import android.view.inputmethod.InputMethodManager
import android.widget.Toast import android.widget.Toast
import chat.rocket.android.R import chat.rocket.android.R
// TODO: Remove. Use KTX instead.
fun View.setVisible(visible: Boolean) { fun View.setVisible(visible: Boolean) {
visibility = if (visible) { visibility = if (visible) {
View.VISIBLE View.VISIBLE
......
...@@ -78,6 +78,7 @@ class OauthWebViewActivity : AppCompatActivity() { ...@@ -78,6 +78,7 @@ class OauthWebViewActivity : AppCompatActivity() {
private fun setupWebView() { private fun setupWebView() {
with(web_view.settings) { with(web_view.settings) {
javaScriptEnabled = true javaScriptEnabled = true
domStorageEnabled = true
// TODO Remove this workaround that is required to make Google OAuth to work. We should use Custom Tabs instead. See https://github.com/RocketChat/Rocket.Chat.Android/issues/968 // TODO Remove this workaround that is required to make Google OAuth to work. We should use Custom Tabs instead. See https://github.com/RocketChat/Rocket.Chat.Android/issues/968
if (webPageUrl.contains("google")) { if (webPageUrl.contains("google")) {
userAgentString = "Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/43.0.2357.65 Mobile Safari/535.19" userAgentString = "Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/43.0.2357.65 Mobile Safari/535.19"
......
This diff is collapsed.
This diff is collapsed.
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
<!-- Actions --> <!-- Actions -->
<string name="action_connect">Conectar</string> <string name="action_connect">Conectar</string>
<string name="action_use_this_username">Usar este nome de usuário</string> <string name="action_use_this_username">Usar este nome de usuário</string>
<string name="action_login_or_sign_up">Toque este botão para fazer login ou criar uma conta</string> <string name="action_login_or_sign_up">Toque neste botão para fazer login ou criar uma conta</string>
<string name="action_terms_of_service">Termos de Serviço</string> <string name="action_terms_of_service">Termos de Serviço</string>
<string name="action_privacy_policy">Política de Privacidade</string> <string name="action_privacy_policy">Política de Privacidade</string>
<string name="action_search">Pesquisar</string> <string name="action_search">Pesquisar</string>
...@@ -59,7 +59,7 @@ ...@@ -59,7 +59,7 @@
<string name="msg_this_room_is_read_only">Este chat é apenas de leitura</string> <string name="msg_this_room_is_read_only">Este chat é apenas de leitura</string>
<string name="msg_invalid_2fa_code">Código 2FA inválido</string> <string name="msg_invalid_2fa_code">Código 2FA inválido</string>
<string name="msg_invalid_file">Arquivo inválido</string> <string name="msg_invalid_file">Arquivo inválido</string>
<string name="msg_invalid_server_url">URL de servidor inválida</string> <string name="msg_invalid_server_url">URL de servidor inválido</string>
<string name="msg_content_description_log_in_using_facebook">Fazer login através do Facebook</string> <string name="msg_content_description_log_in_using_facebook">Fazer login através do Facebook</string>
<string name="msg_content_description_log_in_using_github">Fazer login através do Github</string> <string name="msg_content_description_log_in_using_github">Fazer login através do Github</string>
<string name="msg_content_description_log_in_using_google">Fazer login através do Google</string> <string name="msg_content_description_log_in_using_google">Fazer login através do Google</string>
...@@ -102,7 +102,7 @@ ...@@ -102,7 +102,7 @@
<string name="message_user_added_by">Usuário %1$s adicionado por %2$s</string> <string name="message_user_added_by">Usuário %1$s adicionado por %2$s</string>
<string name="message_user_removed_by">Usuário %1$s removido por %2$s</string> <string name="message_user_removed_by">Usuário %1$s removido por %2$s</string>
<string name="message_user_left">Saiu da sala.</string> <string name="message_user_left">Saiu da sala.</string>
<string name="message_user_joined_channel">Entrou no sala.</string> <string name="message_user_joined_channel">Entrou na sala.</string>
<string name="message_welcome">Bem-vindo, %s</string> <string name="message_welcome">Bem-vindo, %s</string>
<string name="message_removed">Mensagem removida</string> <string name="message_removed">Mensagem removida</string>
<string name="message_pinned">Pinou uma mensagem:</string> <string name="message_pinned">Pinou uma mensagem:</string>
...@@ -123,7 +123,7 @@ ...@@ -123,7 +123,7 @@
<!-- Permission messages --> <!-- Permission messages -->
<string name="permission_editing_not_allowed">Edição não permitida</string> <string name="permission_editing_not_allowed">Edição não permitida</string>
<string name="permission_deleting_not_allowed">Remoção não permitida</string> <string name="permission_deleting_not_allowed">Remoção não permitida</string>
<string name="permission_pinning_not_allowed">Fixar não permitido</string> <string name="permission_pinning_not_allowed">Pinagem não permitida</string>
<!-- Members List --> <!-- Members List -->
<string name="title_members_list">Lista de Membros</string> <string name="title_members_list">Lista de Membros</string>
...@@ -163,8 +163,8 @@ ...@@ -163,8 +163,8 @@
<string name="Leave_the_current_channel">Sair do canal atual</string> <string name="Leave_the_current_channel">Sair do canal atual</string>
<string name="Displays_action_text">Exibir texto de ação</string> <string name="Displays_action_text">Exibir texto de ação</string>
<string name="Direct_message_someone">Enviar DM para alguém</string> <string name="Direct_message_someone">Enviar DM para alguém</string>
<string name="Mute_someone_in_room">Mutar alguém</string> <string name="Mute_someone_in_room">Silenciar alguém</string>
<string name="Unmute_someone_in_room">Desmutar alguém na sala</string> <string name="Unmute_someone_in_room">De-silenciar alguém na sala</string>
<string name="Invite_user_to_join_channel">Convidar algum usuário para entrar neste canal</string> <string name="Invite_user_to_join_channel">Convidar algum usuário para entrar neste canal</string>
<string name="Unarchive">Desarquivar</string> <string name="Unarchive">Desarquivar</string>
<string name="Join_the_given_channel">Entrar no canal especificado</string> <string name="Join_the_given_channel">Entrar no canal especificado</string>
......
...@@ -10,7 +10,7 @@ buildscript { ...@@ -10,7 +10,7 @@ buildscript {
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:3.1.1' classpath 'com.android.tools.build:gradle:3.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}"
classpath "org.jetbrains.dokka:dokka-gradle-plugin:${versions.dokka}" classpath "org.jetbrains.dokka:dokka-gradle-plugin:${versions.dokka}"
classpath 'com.google.gms:google-services:3.2.0' classpath 'com.google.gms:google-services:3.2.0'
......
...@@ -4,7 +4,7 @@ ext { ...@@ -4,7 +4,7 @@ ext {
compileSdk : 27, compileSdk : 27,
targetSdk : 27, targetSdk : 27,
buildTools : '27.0.3', buildTools : '27.0.3',
kotlin : '1.2.31', kotlin : '1.2.40',
coroutine : '0.22.5', coroutine : '0.22.5',
dokka : '0.9.16', dokka : '0.9.16',
...@@ -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