Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions FlowCrypt/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ dependencies {
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:${rootProject.ext.lifecycleVersion}"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.4.0"
implementation "androidx.lifecycle:lifecycle-process:2.4.0"
implementation "androidx.room:room-runtime:$roomVersion"
implementation "androidx.room:room-ktx:$roomVersion"
implementation "androidx.paging:paging-runtime-ktx:$pagingVersion"
Expand Down
9 changes: 8 additions & 1 deletion FlowCrypt/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,14 @@
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
tools:node="remove" />
android:exported="false"
tools:node="merge">
<!-- If you are using androidx.startup to initialize other components -->
<meta-data
android:name="androidx.work.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>
<!-- Services -->
<service
android:name=".service.PassPhrasesInRAMService"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ class EmailUtil {
TextUtils.isEmpty(email) -> ""
email?.contains("@") == true -> email.substring(email.indexOf('@') + 1)
else -> ""
}
}.lowercase()
}
Comment on lines 150 to 154

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An empty string may not be the best choice. Actually, how come email is already nullable? When would it ever be null?

On browser extension in these situations I throw (cannot parse domain from email).


/**
Expand Down Expand Up @@ -758,32 +758,6 @@ class EmailUtil {
}
}

private fun getBodyPartWithBackupText(context: Context): BodyPart {
val messageBodyPart = MimeBodyPart()
messageBodyPart.setContent(
GeneralUtil.removeAllComments(
IOUtils.toString(
context.assets
.open(HTML_EMAIL_INTRO_TEMPLATE_HTM), StandardCharsets.UTF_8
)
), JavaEmailConstants.MIME_TYPE_TEXT_HTML
)
return messageBodyPart
}

private fun genMsgWithBackupTemplate(
context: Context,
account: AccountEntity,
session: Session
): Message {
val msg = FlowCryptMimeMessage(session)

msg.setFrom(InternetAddress(account.email))
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(account.email))
msg.subject = context.getString(R.string.your_key_backup)
return msg
}

/**
* Get only headers from the raw MIME
*/
Expand Down Expand Up @@ -1084,6 +1058,16 @@ class EmailUtil {
return reply
}

/**
* Get public email domains.
*/
fun getPublicEmailDomains(): Array<String> {
return arrayOf(
JavaEmailConstants.EMAIL_PROVIDER_GMAIL,
JavaEmailConstants.EMAIL_PROVIDER_GOOGLEMAIL
)
Comment on lines +1065 to +1068

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On browser extension we use: ['gmail.com', 'yahoo.com', 'outlook.com', 'live.com', 'googlemail.com']

}

private fun generateNonGmailSearchTerm(localFolder: LocalFolder): SearchTerm {
return OrTerm(
arrayOf(
Expand Down Expand Up @@ -1147,5 +1131,31 @@ class EmailUtil {
info.msg ?: ""
}
}

private fun getBodyPartWithBackupText(context: Context): BodyPart {
val messageBodyPart = MimeBodyPart()
messageBodyPart.setContent(
GeneralUtil.removeAllComments(
IOUtils.toString(
context.assets
.open(HTML_EMAIL_INTRO_TEMPLATE_HTM), StandardCharsets.UTF_8
)
), JavaEmailConstants.MIME_TYPE_TEXT_HTML
)
return messageBodyPart
}

private fun genMsgWithBackupTemplate(
context: Context,
account: AccountEntity,
session: Session
): Message {
val msg = FlowCryptMimeMessage(session)

msg.setFrom(InternetAddress(account.email))
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(account.email))
msg.subject = context.getString(R.string.your_key_backup)
return msg
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import kotlinx.coroutines.withContext
*/
abstract class BaseWorker(context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
abstract val useIndependentConnection: Boolean
protected val roomDatabase = FlowCryptRoomDatabase.getDatabase(applicationContext)

suspend fun rescheduleIfActiveAccountWasChanged(accountEntity: AccountEntity?): Result =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ class ForwardedAttachmentsDownloaderWorker(context: Context, params: WorkerParam
BaseWorker(context, params) {
private val attCacheDir = File(applicationContext.cacheDir, Constants.ATTACHMENTS_CACHE_DIR)
private val fwdAttsCacheDir = File(attCacheDir, Constants.FORWARDED_ATTACHMENTS_CACHE_DIR)
override val useIndependentConnection: Boolean = false

override suspend fun doWork(): Result =
withContext(Dispatchers.IO) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ import javax.net.ssl.SSLException
*/
class MessagesSenderWorker(context: Context, params: WorkerParameters) :
BaseWorker(context, params) {
override val useIndependentConnection: Boolean = false

override suspend fun doWork(): Result =
withContext(Dispatchers.IO) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com
* Contributors: DenBond7
*/

package com.flowcrypt.email.jetpack.workmanager

import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.flowcrypt.email.api.email.EmailUtil
import com.flowcrypt.email.api.retrofit.FlowcryptApiRepository
import com.flowcrypt.email.api.retrofit.request.model.LoginModel
import com.flowcrypt.email.api.retrofit.response.api.ClientConfigurationResponse
import com.flowcrypt.email.api.retrofit.response.api.DomainOrgRulesResponse
import com.flowcrypt.email.api.retrofit.response.base.Result.Status
import com.flowcrypt.email.util.GeneralUtil
import com.flowcrypt.email.util.LogsUtil

/**
* @author Denis Bondarenko
* Date: 11/24/21
* Time: 4:31 PM
* E-mail: DenBond7@gmail.com
*/
class RefreshClientConfigurationWorker(context: Context, params: WorkerParameters) :
BaseWorker(context, params) {

override suspend fun doWork(): Result {
LogsUtil.d(TAG, "doWork")
val repository = FlowcryptApiRepository()
val publicEmailDomains = EmailUtil.getPublicEmailDomains()

for (account in roomDatabase.accountDao().getAccounts()) {
val domain = EmailUtil.getDomain(account.email)
if (domain in publicEmailDomains) {
continue
}

val fesUrl = GeneralUtil.generateFesUrl(domain)
val uuid = account.uuid ?: continue
try {
val result = repository.getDomainOrgRules(
context = applicationContext,
loginModel = LoginModel(account.email, uuid),
fesUrl = fesUrl
)

if (result.status == Status.SUCCESS) {
val fetchedOrgRules = (result.data as? DomainOrgRulesResponse)?.orgRules
?: (result.data as? ClientConfigurationResponse)?.orgRules
fetchedOrgRules?.let { orgRules ->
roomDatabase.accountDao().updateSuspend(account.copy(clientConfiguration = orgRules))
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}

LogsUtil.d(TAG, "work was finished")
return Result.success()
Comment thread
tomholub marked this conversation as resolved.
Resolved
}

companion object {
private val TAG = RefreshClientConfigurationWorker::class.java.simpleName
val NAME = RefreshClientConfigurationWorker::class.java.simpleName

fun enqueue(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()

WorkManager
.getInstance(context.applicationContext)
.enqueueUniqueWork(
NAME,
ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<RefreshClientConfigurationWorker>()
.setConstraints(constraints)
.build()
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ import javax.mail.Store
* E-mail: DenBond7@gmail.com
*/
abstract class BaseSyncWorker(context: Context, params: WorkerParameters) :
BaseWorker(context, params) {
override val useIndependentConnection: Boolean = false
BaseWorker(context, params), SyncInterface {

abstract suspend fun runIMAPAction(accountEntity: AccountEntity, store: Store)
abstract suspend fun runAPIAction(accountEntity: AccountEntity)
Expand All @@ -43,7 +42,7 @@ abstract class BaseSyncWorker(context: Context, params: WorkerParameters) :
try {
val activeAccountEntity = roomDatabase.accountDao().getActiveAccountSuspend()
activeAccountEntity?.let {
if (useIndependentConnection) {
if (useIndependentConnection()) {
AccountViewModel.getAccountEntityWithDecryptedInfoSuspend(it)
?.let { accountWithDecryptedInfo ->
if (accountWithDecryptedInfo.useAPI) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ import java.util.concurrent.TimeUnit
*/
class SyncInboxWorker(context: Context, params: WorkerParameters) :
InboxIdleSyncWorker(context, params) {
override val useIndependentConnection: Boolean = true

override fun useIndependentConnection(): Boolean = true

companion object {
const val GROUP_UNIQUE_TAG = BuildConfig.APPLICATION_ID + ".SYNC_INBOX"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com
* Contributors: DenBond7
*/

package com.flowcrypt.email.jetpack.workmanager.sync

/**
* @author Denis Bondarenko
* Date: 11/24/21
* Time: 4:34 PM
* E-mail: DenBond7@gmail.com
*/
interface SyncInterface {
fun useIndependentConnection(): Boolean = false
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager
import androidx.work.WorkManager
Expand All @@ -50,6 +53,7 @@ import com.flowcrypt.email.jetpack.viewmodel.ActionsViewModel
import com.flowcrypt.email.jetpack.viewmodel.LabelsViewModel
import com.flowcrypt.email.jetpack.viewmodel.MessagesViewModel
import com.flowcrypt.email.jetpack.workmanager.MessagesSenderWorker
import com.flowcrypt.email.jetpack.workmanager.RefreshClientConfigurationWorker
import com.flowcrypt.email.jetpack.workmanager.sync.BaseSyncWorker
import com.flowcrypt.email.model.MessageEncryptionType
import com.flowcrypt.email.service.CheckClipboardToFindKeyService
Expand Down Expand Up @@ -106,6 +110,7 @@ class EmailManagerActivity : BaseEmailListActivity(),
private var currentAccountDetailsItem: View? = null
private var switchView: SwitchMaterial? = null
private var isForceSendingEnabled: Boolean = true
private var isUpdateOrgRulesRequired: Boolean = true

private val idleServiceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {}
Expand All @@ -123,6 +128,7 @@ class EmailManagerActivity : BaseEmailListActivity(),

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
observeMovingToBackground()
updateLabels()
loadContactsIfNeeded()
IdleService.bind(this, idleServiceConnection)
Expand Down Expand Up @@ -164,6 +170,14 @@ class EmailManagerActivity : BaseEmailListActivity(),
MessagesNotificationManager(this).cancelAll(this, nonNullAccount, manager)
}

override fun onStart() {
super.onStart()
if (isUpdateOrgRulesRequired) {
RefreshClientConfigurationWorker.enqueue(applicationContext)
isUpdateOrgRulesRequired = false
}
}

override fun onDestroy() {
super.onDestroy()
unbindService(idleServiceConnection)
Expand Down Expand Up @@ -715,6 +729,17 @@ class EmailManagerActivity : BaseEmailListActivity(),
}
}

private fun observeMovingToBackground() {
ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
/**
* The app moved to background
*/
override fun onStop(owner: LifecycleOwner) {
isUpdateOrgRulesRequired = true
}
})
}

/**
* The custom realization of [ActionBarDrawerToggle]. Will be used to start a labels
* update task when the drawer will be opened.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ abstract class BaseActivity : AppCompatActivity() {
LogsUtil.d(tag, "onResume")
}

override fun onPause() {
super.onPause()
LogsUtil.d(tag, "onPause")
}

public override fun onStop() {
super.onStop()
LogsUtil.d(tag, "onStop")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import com.flowcrypt.email.BuildConfig
import com.flowcrypt.email.Constants
import com.flowcrypt.email.R
import com.flowcrypt.email.api.email.EmailUtil
import com.flowcrypt.email.api.email.JavaEmailConstants
import com.flowcrypt.email.api.retrofit.response.api.ClientConfigurationResponse
import com.flowcrypt.email.api.retrofit.response.api.DomainOrgRulesResponse
import com.flowcrypt.email.api.retrofit.response.base.ApiResponse
Expand Down Expand Up @@ -256,12 +255,8 @@ class MainSignInFragment : BaseSingInFragment() {
val account = googleSignInAccount?.account?.name ?: return
uuid = SecurityUtils.generateRandomUUID()

val publicEmailDomains = arrayOf(
JavaEmailConstants.EMAIL_PROVIDER_GMAIL,
JavaEmailConstants.EMAIL_PROVIDER_GOOGLEMAIL
)

if (EmailUtil.getDomain(account).toLowerCase(Locale.US) in publicEmailDomains) {
val publicEmailDomains = EmailUtil.getPublicEmailDomains()
if (EmailUtil.getDomain(account) in publicEmailDomains) {
onSignSuccess(googleSignInAccount)
} else {
orgRules = null
Expand Down Expand Up @@ -461,7 +456,7 @@ class MainSignInFragment : BaseSingInFragment() {
if ("enterprise-server" == it.data?.service) {
googleSignInAccount?.account?.name?.let { account ->
val domain = EmailUtil.getDomain(account)
fesUrl = "https://fes.$domain/api/v1/client-configuration?domain=$domain"
fesUrl = GeneralUtil.generateFesUrl(domain)
domainOrgRulesViewModel.fetchOrgRules(
account = account,
uuid = uuid,
Expand Down
Loading