Merge remote-tracking branch 'loki/dev' into audio-view-design-update

This commit is contained in:
Anton Chekulaev 2020-10-20 20:46:24 +11:00
commit 001a5a90cb
17 changed files with 335 additions and 198 deletions

View File

@ -182,8 +182,8 @@ dependencies {
testImplementation 'org.robolectric:shadows-multidex:4.2' testImplementation 'org.robolectric:shadows-multidex:4.2'
} }
def canonicalVersionCode = 108 def canonicalVersionCode = 110
def canonicalVersionName = "1.6.0" def canonicalVersionName = "1.6.1"
def postFixSize = 10 def postFixSize = 10
def abiPostFix = ['armeabi-v7a' : 1, def abiPostFix = ['armeabi-v7a' : 1,

View File

@ -5,34 +5,40 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"> android:layout_height="match_parent">
<LinearLayout <ScrollView
android:id="@+id/mainContentContainer"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="wrap_content" >
android:orientation="vertical">
<EditText <LinearLayout
style="@style/SessionEditText" android:id="@+id/mainContentContainer"
android:id="@+id/nameEditText"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/large_spacing" android:orientation="vertical">
android:layout_marginTop="@dimen/medium_spacing"
android:layout_marginRight="@dimen/large_spacing"
android:layout_marginBottom="@dimen/medium_spacing"
android:hint="@string/activity_create_closed_group_edit_text_hint" />
<View <EditText
android:layout_width="match_parent" style="@style/SessionEditText"
android:layout_height="1px" android:id="@+id/nameEditText"
android:background="?android:dividerHorizontal" /> android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/large_spacing"
android:layout_marginTop="@dimen/medium_spacing"
android:layout_marginRight="@dimen/large_spacing"
android:layout_marginBottom="@dimen/medium_spacing"
android:hint="@string/activity_create_closed_group_edit_text_hint" />
<androidx.recyclerview.widget.RecyclerView <View
android:id="@+id/recyclerView" android:layout_width="match_parent"
android:layout_width="match_parent" android:layout_height="1px"
android:layout_height="match_parent" /> android:background="?android:dividerHorizontal" />
</LinearLayout> <androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</ScrollView>
<LinearLayout <LinearLayout
android:id="@+id/emptyStateContainer" android:id="@+id/emptyStateContainer"
@ -51,7 +57,7 @@
<Button <Button
style="@style/Widget.Session.Button.Common.ProminentOutline" style="@style/Widget.Session.Button.Common.ProminentOutline"
android:id="@+id/btnCreateNewPrivateChat" android:id="@+id/createNewPrivateChatButton"
android:layout_width="196dp" android:layout_width="196dp"
android:layout_height="@dimen/medium_button_height" android:layout_height="@dimen/medium_button_height"
android:layout_marginTop="@dimen/medium_spacing" android:layout_marginTop="@dimen/medium_spacing"

View File

@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="org.thoughtcrime.securesms.loki.activities.EditClosedGroupActivity"> tools:context="org.thoughtcrime.securesms.loki.activities.EditClosedGroupActivity">
<LinearLayout <LinearLayout
@ -146,4 +146,22 @@
</LinearLayout> </LinearLayout>
<RelativeLayout
android:id="@+id/loader"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#A4000000"
android:visibility="gone"
android:alpha="0">
<com.github.ybq.android.spinkit.SpinKitView
style="@style/SpinKitView.Large.ThreeBounce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_centerInParent="true"
app:SpinKit_Color="@android:color/white" />
</RelativeLayout>
</RelativeLayout> </RelativeLayout>

View File

@ -123,7 +123,7 @@
<Button <Button
style="@style/Widget.Session.Button.Common.ProminentOutline" style="@style/Widget.Session.Button.Common.ProminentOutline"
android:id="@+id/btnCreateNewPrivateChat" android:id="@+id/createNewPrivateChatButton"
android:layout_width="196dp" android:layout_width="196dp"
android:layout_height="@dimen/medium_button_height" android:layout_height="@dimen/medium_button_height"
android:layout_marginTop="@dimen/medium_spacing" android:layout_marginTop="@dimen/medium_spacing"

View File

@ -26,6 +26,7 @@
android:layout_centerInParent="true"> android:layout_centerInParent="true">
<TextView <TextView
android:id="@+id/emptyStateMessageTextView"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:textSize="@dimen/medium_font_size" android:textSize="@dimen/medium_font_size"

View File

@ -3102,8 +3102,12 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity
} }
private void updateProfilePicture() { private void updateProfilePicture() {
profilePictureView.glide = GlideApp.with(this); try {
profilePictureView.update(recipient, threadId); profilePictureView.glide = GlideApp.with(this);
profilePictureView.update(recipient, threadId);
} catch (Exception exception) {
// Do nothing
}
} }
private void updateSubtitleTextView() { private void updateSubtitleTextView() {

View File

@ -91,8 +91,9 @@ public class SQLCipherOpenHelper extends SQLiteOpenHelper {
private static final int lokiV12 = 33; private static final int lokiV12 = 33;
private static final int lokiV13 = 34; private static final int lokiV13 = 34;
private static final int lokiV14_BACKUP_FILES = 35; private static final int lokiV14_BACKUP_FILES = 35;
private static final int lokiV15 = 36;
private static final int DATABASE_VERSION = lokiV14_BACKUP_FILES; // Loki - onUpgrade(...) must be updated to use Loki version numbers if Signal makes any database changes private static final int DATABASE_VERSION = lokiV15;
private static final String DATABASE_NAME = "signal.db"; private static final String DATABASE_NAME = "signal.db";
private final Context context; private final Context context;
@ -164,7 +165,8 @@ public class SQLCipherOpenHelper extends SQLiteOpenHelper {
db.execSQL(LokiUserDatabase.getCreateDisplayNameTableCommand()); db.execSQL(LokiUserDatabase.getCreateDisplayNameTableCommand());
db.execSQL(LokiUserDatabase.getCreateServerDisplayNameTableCommand()); db.execSQL(LokiUserDatabase.getCreateServerDisplayNameTableCommand());
db.execSQL(LokiBackupFilesDatabase.getCreateTableCommand()); db.execSQL(LokiBackupFilesDatabase.getCreateTableCommand());
db.execSQL(SharedSenderKeysDatabase.getCreateClosedGroupRatchetTableCommand()); db.execSQL(SharedSenderKeysDatabase.getCreateOldClosedGroupRatchetTableCommand());
db.execSQL(SharedSenderKeysDatabase.getCreateCurrentClosedGroupRatchetTableCommand());
db.execSQL(SharedSenderKeysDatabase.getCreateClosedGroupPrivateKeyTableCommand()); db.execSQL(SharedSenderKeysDatabase.getCreateClosedGroupPrivateKeyTableCommand());
executeStatements(db, SmsDatabase.CREATE_INDEXS); executeStatements(db, SmsDatabase.CREATE_INDEXS);
@ -614,7 +616,7 @@ public class SQLCipherOpenHelper extends SQLiteOpenHelper {
if (oldVersion < lokiV12) { if (oldVersion < lokiV12) {
db.execSQL(LokiAPIDatabase.getCreateLastMessageHashValueTable2Command()); db.execSQL(LokiAPIDatabase.getCreateLastMessageHashValueTable2Command());
db.execSQL(SharedSenderKeysDatabase.getCreateClosedGroupRatchetTableCommand()); db.execSQL(SharedSenderKeysDatabase.getCreateCurrentClosedGroupRatchetTableCommand());
db.execSQL(SharedSenderKeysDatabase.getCreateClosedGroupPrivateKeyTableCommand()); db.execSQL(SharedSenderKeysDatabase.getCreateClosedGroupPrivateKeyTableCommand());
} }
@ -626,6 +628,10 @@ public class SQLCipherOpenHelper extends SQLiteOpenHelper {
db.execSQL(LokiBackupFilesDatabase.getCreateTableCommand()); db.execSQL(LokiBackupFilesDatabase.getCreateTableCommand());
} }
if (oldVersion < lokiV15) {
db.execSQL(SharedSenderKeysDatabase.getCreateOldClosedGroupRatchetTableCommand());
}
db.setTransactionSuccessful(); db.setTransactionSuccessful();
} finally { } finally {
db.endTransaction(); db.endTransaction();

View File

@ -32,11 +32,10 @@ import org.whispersystems.libsignal.util.guava.Optional
import java.lang.ref.WeakReference import java.lang.ref.WeakReference
class CreateClosedGroupActivity : PassphraseRequiredActionBarActivity(), LoaderManager.LoaderCallbacks<List<String>> { class CreateClosedGroupActivity : PassphraseRequiredActionBarActivity(), LoaderManager.LoaderCallbacks<List<String>> {
private var isLoading = false
set(newValue) { field = newValue; invalidateOptionsMenu() }
private var members = listOf<String>() private var members = listOf<String>()
set(value) { set(value) { field = value; selectContactsAdapter.members = value }
field = value
selectContactsAdapter.members = value
}
private val selectContactsAdapter by lazy { private val selectContactsAdapter by lazy {
SelectContactsAdapter(this, GlideApp.with(this)) SelectContactsAdapter(this, GlideApp.with(this))
@ -49,21 +48,17 @@ class CreateClosedGroupActivity : PassphraseRequiredActionBarActivity(), LoaderM
// region Lifecycle // region Lifecycle
override fun onCreate(savedInstanceState: Bundle?, isReady: Boolean) { override fun onCreate(savedInstanceState: Bundle?, isReady: Boolean) {
super.onCreate(savedInstanceState, isReady) super.onCreate(savedInstanceState, isReady)
setContentView(R.layout.activity_create_closed_group) setContentView(R.layout.activity_create_closed_group)
supportActionBar!!.title = resources.getString(R.string.activity_create_closed_group_title) supportActionBar!!.title = resources.getString(R.string.activity_create_closed_group_title)
recyclerView.adapter = this.selectContactsAdapter recyclerView.adapter = this.selectContactsAdapter
recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.layoutManager = LinearLayoutManager(this)
createNewPrivateChatButton.setOnClickListener { createNewPrivateChat() }
btnCreateNewPrivateChat.setOnClickListener { createNewPrivateChat() }
LoaderManager.getInstance(this).initLoader(0, null, this) LoaderManager.getInstance(this).initLoader(0, null, this)
} }
override fun onCreateOptionsMenu(menu: Menu?): Boolean { override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_done, menu) menuInflater.inflate(R.menu.menu_done, menu)
return members.isNotEmpty() return members.isNotEmpty() && !isLoading
} }
// endregion // endregion
@ -91,7 +86,7 @@ class CreateClosedGroupActivity : PassphraseRequiredActionBarActivity(), LoaderM
// region Interaction // region Interaction
override fun onOptionsItemSelected(item: MenuItem): Boolean { override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId) { when(item.itemId) {
R.id.doneButton -> createClosedGroup() R.id.doneButton -> if (!isLoading) { createClosedGroup() }
} }
return super.onOptionsItemSelected(item) return super.onOptionsItemSelected(item)
} }
@ -125,9 +120,11 @@ class CreateClosedGroupActivity : PassphraseRequiredActionBarActivity(), LoaderM
return Toast.makeText(this, R.string.activity_create_closed_group_too_many_group_members_error, Toast.LENGTH_LONG).show() return Toast.makeText(this, R.string.activity_create_closed_group_too_many_group_members_error, Toast.LENGTH_LONG).show()
} }
val userPublicKey = TextSecurePreferences.getLocalNumber(this) val userPublicKey = TextSecurePreferences.getLocalNumber(this)
isLoading = true
loader.fadeIn() loader.fadeIn()
ClosedGroupsProtocol.createClosedGroup(this, name.toString(), selectedMembers + setOf( userPublicKey )).successUi { groupID -> ClosedGroupsProtocol.createClosedGroup(this, name.toString(), selectedMembers + setOf( userPublicKey )).successUi { groupID ->
loader.fadeOut() loader.fadeOut()
isLoading = false
val threadID = DatabaseFactory.getThreadDatabase(this).getThreadIdFor(Recipient.from(this, Address.fromSerialized(groupID), false)) val threadID = DatabaseFactory.getThreadDatabase(this).getThreadIdFor(Recipient.from(this, Address.fromSerialized(groupID), false))
if (!isFinishing) { if (!isFinishing) {
openConversationActivity(this, threadID, Recipient.from(this, Address.fromSerialized(groupID), false)) openConversationActivity(this, threadID, Recipient.from(this, Address.fromSerialized(groupID), false))

View File

@ -8,9 +8,7 @@ import android.os.Bundle
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter import androidx.fragment.app.FragmentPagerAdapter
import android.text.InputType import android.text.InputType
import android.view.LayoutInflater import android.view.*
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager import android.view.inputmethod.InputMethodManager
import android.widget.Toast import android.widget.Toast
@ -43,9 +41,21 @@ class CreatePrivateChatActivity : PassphraseRequiredActionBarActivity(), ScanQRC
viewPager.adapter = adapter viewPager.adapter = adapter
tabLayout.setupWithViewPager(viewPager) tabLayout.setupWithViewPager(viewPager)
} }
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_done, menu)
return true
}
// endregion // endregion
// region Interaction // region Interaction
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId) {
R.id.doneButton -> adapter.enterPublicKeyFragment.createPrivateChatIfPossible()
}
return super.onOptionsItemSelected(item)
}
override fun handleQRCodeScanned(hexEncodedPublicKey: String) { override fun handleQRCodeScanned(hexEncodedPublicKey: String) {
createPrivateChatIfPossible(hexEncodedPublicKey) createPrivateChatIfPossible(hexEncodedPublicKey)
} }
@ -71,6 +81,7 @@ class CreatePrivateChatActivity : PassphraseRequiredActionBarActivity(), ScanQRC
// region Adapter // region Adapter
private class CreatePrivateChatActivityAdapter(val activity: CreatePrivateChatActivity) : FragmentPagerAdapter(activity.supportFragmentManager) { private class CreatePrivateChatActivityAdapter(val activity: CreatePrivateChatActivity) : FragmentPagerAdapter(activity.supportFragmentManager) {
val enterPublicKeyFragment = EnterPublicKeyFragment()
override fun getCount(): Int { override fun getCount(): Int {
return 2 return 2
@ -78,7 +89,7 @@ private class CreatePrivateChatActivityAdapter(val activity: CreatePrivateChatAc
override fun getItem(index: Int): Fragment { override fun getItem(index: Int): Fragment {
return when (index) { return when (index) {
0 -> EnterPublicKeyFragment() 0 -> enterPublicKeyFragment
1 -> { 1 -> {
val result = ScanQRCodeWrapperFragment() val result = ScanQRCodeWrapperFragment()
result.delegate = activity result.delegate = activity
@ -104,8 +115,8 @@ class EnterPublicKeyFragment : Fragment() {
private val hexEncodedPublicKey: String private val hexEncodedPublicKey: String
get() { get() {
val masterHexEncodedPublicKey = TextSecurePreferences.getMasterHexEncodedPublicKey(context!!) val masterHexEncodedPublicKey = TextSecurePreferences.getMasterHexEncodedPublicKey(requireContext())
val userHexEncodedPublicKey = TextSecurePreferences.getLocalNumber(context!!) val userHexEncodedPublicKey = TextSecurePreferences.getLocalNumber(requireContext())
return masterHexEncodedPublicKey ?: userHexEncodedPublicKey return masterHexEncodedPublicKey ?: userHexEncodedPublicKey
} }
@ -148,7 +159,7 @@ class EnterPublicKeyFragment : Fragment() {
startActivity(intent) startActivity(intent)
} }
private fun createPrivateChatIfPossible() { fun createPrivateChatIfPossible() {
val hexEncodedPublicKey = publicKeyEditText.text?.trim().toString() ?: "" val hexEncodedPublicKey = publicKeyEditText.text?.trim().toString() ?: ""
(requireActivity() as CreatePrivateChatActivity).createPrivateChatIfPossible(hexEncodedPublicKey) (requireActivity() as CreatePrivateChatActivity).createPrivateChatIfPossible(hexEncodedPublicKey)
} }

View File

@ -13,17 +13,23 @@ import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager import android.view.inputmethod.InputMethodManager
import android.widget.Toast import android.widget.Toast
import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.content.res.AppCompatResources
import kotlinx.android.synthetic.main.activity_create_closed_group.*
import kotlinx.android.synthetic.main.activity_create_closed_group.emptyStateContainer import kotlinx.android.synthetic.main.activity_create_closed_group.emptyStateContainer
import kotlinx.android.synthetic.main.activity_create_closed_group.mainContentContainer import kotlinx.android.synthetic.main.activity_create_closed_group.mainContentContainer
import kotlinx.android.synthetic.main.activity_edit_closed_group.* import kotlinx.android.synthetic.main.activity_edit_closed_group.*
import kotlinx.android.synthetic.main.activity_edit_closed_group.loader
import kotlinx.android.synthetic.main.activity_linked_devices.recyclerView import kotlinx.android.synthetic.main.activity_linked_devices.recyclerView
import network.loki.messenger.R import network.loki.messenger.R
import nl.komponents.kovenant.ui.failUi
import nl.komponents.kovenant.ui.successUi
import org.thoughtcrime.securesms.PassphraseRequiredActionBarActivity import org.thoughtcrime.securesms.PassphraseRequiredActionBarActivity
import org.thoughtcrime.securesms.database.Address import org.thoughtcrime.securesms.database.Address
import org.thoughtcrime.securesms.database.DatabaseFactory import org.thoughtcrime.securesms.database.DatabaseFactory
import org.thoughtcrime.securesms.groups.GroupManager import org.thoughtcrime.securesms.groups.GroupManager
import org.thoughtcrime.securesms.loki.dialogs.ClosedGroupEditingOptionsBottomSheet import org.thoughtcrime.securesms.loki.dialogs.ClosedGroupEditingOptionsBottomSheet
import org.thoughtcrime.securesms.loki.protocol.ClosedGroupsProtocol import org.thoughtcrime.securesms.loki.protocol.ClosedGroupsProtocol
import org.thoughtcrime.securesms.loki.utilities.fadeIn
import org.thoughtcrime.securesms.loki.utilities.fadeOut
import org.thoughtcrime.securesms.mms.GlideApp import org.thoughtcrime.securesms.mms.GlideApp
import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.util.GroupUtil import org.thoughtcrime.securesms.util.GroupUtil
@ -36,6 +42,8 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
private val originalMembers = HashSet<String>() private val originalMembers = HashSet<String>()
private val members = HashSet<String>() private val members = HashSet<String>()
private var hasNameChanged = false private var hasNameChanged = false
private var isLoading = false
set(newValue) { field = newValue; invalidateOptionsMenu() }
private lateinit var groupID: String private lateinit var groupID: String
private lateinit var originalName: String private lateinit var originalName: String
@ -115,7 +123,7 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
override fun onCreateOptionsMenu(menu: Menu): Boolean { override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_edit_closed_group, menu) menuInflater.inflate(R.menu.menu_edit_closed_group, menu)
return members.isNotEmpty() return members.isNotEmpty() && !isLoading
} }
// endregion // endregion
@ -165,8 +173,8 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
// region Interaction // region Interaction
override fun onOptionsItemSelected(item: MenuItem): Boolean { override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId) { when (item.itemId) {
R.id.action_apply -> commitChanges() R.id.action_apply -> if (!isLoading) { commitChanges() }
} }
return super.onOptionsItemSelected(item) return super.onOptionsItemSelected(item)
} }
@ -184,6 +192,7 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
private fun onAddMembersClick() { private fun onAddMembersClick() {
val intent = Intent(this@EditClosedGroupActivity, SelectContactsActivity::class.java) val intent = Intent(this@EditClosedGroupActivity, SelectContactsActivity::class.java)
intent.putExtra(SelectContactsActivity.usersToExcludeKey, members.toTypedArray()) intent.putExtra(SelectContactsActivity.usersToExcludeKey, members.toTypedArray())
intent.putExtra(SelectContactsActivity.emptyStateTextKey, "No contacts to add")
startActivityForResult(intent, addUsersRequestCode) startActivityForResult(intent, addUsersRequestCode)
} }
@ -237,10 +246,19 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
} }
if (isSSKBasedClosedGroup) { if (isSSKBasedClosedGroup) {
ClosedGroupsProtocol.update(this, groupPublicKey!!, members.map { it.address.serialize() }, name) isLoading = true
loader.fadeIn()
ClosedGroupsProtocol.update(this, groupPublicKey!!, members.map { it.address.serialize() }, name).successUi {
loader.fadeOut()
isLoading = false
finish()
}.failUi { exception ->
val message = if (exception is ClosedGroupsProtocol.Error) exception.description else "An error occurred"
Toast.makeText(this@EditClosedGroupActivity, message, Toast.LENGTH_LONG).show()
isLoading = false
}
} else { } else {
GroupManager.updateGroup(this, groupID, members, null, name, admins) GroupManager.updateGroup(this, groupID, members, null, name, admins)
} }
finish()
} }
} }

View File

@ -125,7 +125,7 @@ class HomeActivity : PassphraseRequiredActionBarActivity, ConversationClickListe
recyclerView.adapter = homeAdapter recyclerView.adapter = homeAdapter
recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.layoutManager = LinearLayoutManager(this)
// Set up empty state view // Set up empty state view
btnCreateNewPrivateChat.setOnClickListener { createNewPrivateChat() } createNewPrivateChatButton.setOnClickListener { createNewPrivateChat() }
// This is a workaround for the fact that CursorRecyclerViewAdapter doesn't actually auto-update (even though it says it will) // This is a workaround for the fact that CursorRecyclerViewAdapter doesn't actually auto-update (even though it says it will)
LoaderManager.getInstance(this).restartLoader(0, null, object : LoaderManager.LoaderCallbacks<Cursor> { LoaderManager.getInstance(this).restartLoader(0, null, object : LoaderManager.LoaderCallbacks<Cursor> {

View File

@ -10,7 +10,10 @@ import android.view.Menu
import android.view.MenuItem import android.view.MenuItem
import android.view.View import android.view.View
import kotlinx.android.synthetic.main.activity_create_closed_group.* import kotlinx.android.synthetic.main.activity_create_closed_group.*
import kotlinx.android.synthetic.main.activity_create_closed_group.emptyStateContainer
import kotlinx.android.synthetic.main.activity_create_closed_group.mainContentContainer
import kotlinx.android.synthetic.main.activity_linked_devices.recyclerView import kotlinx.android.synthetic.main.activity_linked_devices.recyclerView
import kotlinx.android.synthetic.main.activity_select_contacts.*
import network.loki.messenger.R import network.loki.messenger.R
import org.thoughtcrime.securesms.PassphraseRequiredActionBarActivity import org.thoughtcrime.securesms.PassphraseRequiredActionBarActivity
import org.thoughtcrime.securesms.mms.GlideApp import org.thoughtcrime.securesms.mms.GlideApp
@ -26,6 +29,7 @@ class SelectContactsActivity : PassphraseRequiredActionBarActivity(), LoaderMana
companion object { companion object {
val usersToExcludeKey = "usersToExcludeKey" val usersToExcludeKey = "usersToExcludeKey"
val emptyStateTextKey = "emptyStateTextKey"
val selectedContactsKey = "selectedContactsKey" val selectedContactsKey = "selectedContactsKey"
} }
@ -37,6 +41,10 @@ class SelectContactsActivity : PassphraseRequiredActionBarActivity(), LoaderMana
supportActionBar!!.title = resources.getString(R.string.activity_select_contacts_title) supportActionBar!!.title = resources.getString(R.string.activity_select_contacts_title)
usersToExclude = intent.getStringArrayExtra(Companion.usersToExcludeKey)?.toSet() ?: setOf() usersToExclude = intent.getStringArrayExtra(Companion.usersToExcludeKey)?.toSet() ?: setOf()
val emptyStateText = intent.getStringExtra(Companion.emptyStateTextKey)
if (emptyStateText != null) {
emptyStateMessageTextView.text = emptyStateText
}
recyclerView.adapter = selectContactsAdapter recyclerView.adapter = selectContactsAdapter
recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.layoutManager = LinearLayoutManager(this)

View File

@ -9,8 +9,10 @@ import org.whispersystems.libsignal.logging.Log
import org.whispersystems.signalservice.internal.util.JsonUtil import org.whispersystems.signalservice.internal.util.JsonUtil
import org.whispersystems.signalservice.loki.api.PushNotificationAPI import org.whispersystems.signalservice.loki.api.PushNotificationAPI
import org.whispersystems.signalservice.loki.api.onionrequests.OnionRequestAPI import org.whispersystems.signalservice.loki.api.onionrequests.OnionRequestAPI
import org.whispersystems.signalservice.loki.utilities.retryIfNeeded
object LokiPushNotificationManager { object LokiPushNotificationManager {
private val maxRetryCount = 4
private val tokenExpirationInterval = 12 * 60 * 60 * 1000 private val tokenExpirationInterval = 12 * 60 * 60 * 1000
private val server by lazy { private val server by lazy {
@ -38,15 +40,17 @@ object LokiPushNotificationManager {
val url = "$server/unregister" val url = "$server/unregister"
val body = RequestBody.create(MediaType.get("application/json"), JsonUtil.toJson(parameters)) val body = RequestBody.create(MediaType.get("application/json"), JsonUtil.toJson(parameters))
val request = Request.Builder().url(url).post(body) val request = Request.Builder().url(url).post(body)
OnionRequestAPI.sendOnionRequest(request.build(), server, pnServerPublicKey).map { json -> retryIfNeeded(maxRetryCount) {
val code = json["code"] as? Int OnionRequestAPI.sendOnionRequest(request.build(), server, pnServerPublicKey).map { json ->
if (code != null && code != 0) { val code = json["code"] as? Int
TextSecurePreferences.setIsUsingFCM(context, false) if (code != null && code != 0) {
} else { TextSecurePreferences.setIsUsingFCM(context, false)
Log.d("Loki", "Couldn't disable FCM due to error: ${json["message"] as? String ?: "null"}.") } else {
Log.d("Loki", "Couldn't disable FCM due to error: ${json["message"] as? String ?: "null"}.")
}
}.fail { exception ->
Log.d("Loki", "Couldn't disable FCM due to error: ${exception}.")
} }
}.fail { exception ->
Log.d("Loki", "Couldn't disable FCM due to error: ${exception}.")
} }
// Unsubscribe from all closed groups // Unsubscribe from all closed groups
val allClosedGroupPublicKeys = DatabaseFactory.getSSKDatabase(context).getAllClosedGroupPublicKeys() val allClosedGroupPublicKeys = DatabaseFactory.getSSKDatabase(context).getAllClosedGroupPublicKeys()
@ -65,17 +69,19 @@ object LokiPushNotificationManager {
val url = "$server/register" val url = "$server/register"
val body = RequestBody.create(MediaType.get("application/json"), JsonUtil.toJson(parameters)) val body = RequestBody.create(MediaType.get("application/json"), JsonUtil.toJson(parameters))
val request = Request.Builder().url(url).post(body) val request = Request.Builder().url(url).post(body)
OnionRequestAPI.sendOnionRequest(request.build(), server, pnServerPublicKey).map { json -> retryIfNeeded(maxRetryCount) {
val code = json["code"] as? Int OnionRequestAPI.sendOnionRequest(request.build(), server, pnServerPublicKey).map { json ->
if (code != null && code != 0) { val code = json["code"] as? Int
TextSecurePreferences.setIsUsingFCM(context, true) if (code != null && code != 0) {
TextSecurePreferences.setFCMToken(context, token) TextSecurePreferences.setIsUsingFCM(context, true)
TextSecurePreferences.setLastFCMUploadTime(context, System.currentTimeMillis()) TextSecurePreferences.setFCMToken(context, token)
} else { TextSecurePreferences.setLastFCMUploadTime(context, System.currentTimeMillis())
Log.d("Loki", "Couldn't register for FCM due to error: ${json["message"] as? String ?: "null"}.") } else {
Log.d("Loki", "Couldn't register for FCM due to error: ${json["message"] as? String ?: "null"}.")
}
}.fail { exception ->
Log.d("Loki", "Couldn't register for FCM due to error: ${exception}.")
} }
}.fail { exception ->
Log.d("Loki", "Couldn't register for FCM due to error: ${exception}.")
} }
// Subscribe to all closed groups // Subscribe to all closed groups
val allClosedGroupPublicKeys = DatabaseFactory.getSSKDatabase(context).getAllClosedGroupPublicKeys() val allClosedGroupPublicKeys = DatabaseFactory.getSSKDatabase(context).getAllClosedGroupPublicKeys()
@ -91,13 +97,15 @@ object LokiPushNotificationManager {
val url = "$server/${operation.rawValue}" val url = "$server/${operation.rawValue}"
val body = RequestBody.create(MediaType.get("application/json"), JsonUtil.toJson(parameters)) val body = RequestBody.create(MediaType.get("application/json"), JsonUtil.toJson(parameters))
val request = Request.Builder().url(url).post(body) val request = Request.Builder().url(url).post(body)
OnionRequestAPI.sendOnionRequest(request.build(), server, pnServerPublicKey).map { json -> retryIfNeeded(maxRetryCount) {
val code = json["code"] as? Int OnionRequestAPI.sendOnionRequest(request.build(), server, pnServerPublicKey).map { json ->
if (code == null || code == 0) { val code = json["code"] as? Int
Log.d("Loki", "Couldn't subscribe/unsubscribe closed group: $closedGroupPublicKey due to error: ${json["message"] as? String ?: "null"}.") if (code == null || code == 0) {
Log.d("Loki", "Couldn't subscribe/unsubscribe closed group: $closedGroupPublicKey due to error: ${json["message"] as? String ?: "null"}.")
}
}.fail { exception ->
Log.d("Loki", "Couldn't subscribe/unsubscribe closed group: $closedGroupPublicKey due to error: ${exception}.")
} }
}.fail { exception ->
Log.d("Loki", "Couldn't subscribe/unsubscribe closed group: $closedGroupPublicKey due to error: ${exception}.")
} }
} }
} }

View File

@ -7,6 +7,7 @@ import org.thoughtcrime.securesms.database.helpers.SQLCipherOpenHelper
import org.thoughtcrime.securesms.loki.utilities.* import org.thoughtcrime.securesms.loki.utilities.*
import org.thoughtcrime.securesms.util.Hex import org.thoughtcrime.securesms.util.Hex
import org.whispersystems.signalservice.loki.protocol.closedgroups.ClosedGroupRatchet import org.whispersystems.signalservice.loki.protocol.closedgroups.ClosedGroupRatchet
import org.whispersystems.signalservice.loki.protocol.closedgroups.ClosedGroupRatchetCollectionType
import org.whispersystems.signalservice.loki.protocol.closedgroups.ClosedGroupSenderKey import org.whispersystems.signalservice.loki.protocol.closedgroups.ClosedGroupSenderKey
import org.whispersystems.signalservice.loki.protocol.closedgroups.SharedSenderKeysDatabaseProtocol import org.whispersystems.signalservice.loki.protocol.closedgroups.SharedSenderKeysDatabaseProtocol
import org.whispersystems.signalservice.loki.utilities.PublicKeyValidation import org.whispersystems.signalservice.loki.utilities.PublicKeyValidation
@ -17,13 +18,18 @@ class SharedSenderKeysDatabase(context: Context, helper: SQLCipherOpenHelper) :
// Shared // Shared
private val closedGroupPublicKey = "closed_group_public_key" private val closedGroupPublicKey = "closed_group_public_key"
// Ratchets // Ratchets
private val closedGroupRatchetTable = "closed_group_ratchet_table" private val oldClosedGroupRatchetTable = "old_closed_group_ratchet_table"
private val currentClosedGroupRatchetTable = "closed_group_ratchet_table"
private val senderPublicKey = "sender_public_key" private val senderPublicKey = "sender_public_key"
private val chainKey = "chain_key" private val chainKey = "chain_key"
private val keyIndex = "key_index" private val keyIndex = "key_index"
private val messageKeys = "message_keys" private val messageKeys = "message_keys"
@JvmStatic val createClosedGroupRatchetTableCommand @JvmStatic val createOldClosedGroupRatchetTableCommand
= "CREATE TABLE $closedGroupRatchetTable ($closedGroupPublicKey STRING, $senderPublicKey STRING, $chainKey STRING, " + = "CREATE TABLE $oldClosedGroupRatchetTable ($closedGroupPublicKey STRING, $senderPublicKey STRING, $chainKey STRING, " +
"$keyIndex INTEGER DEFAULT 0, $messageKeys TEXT, PRIMARY KEY ($closedGroupPublicKey, $senderPublicKey));"
// Private keys
@JvmStatic val createCurrentClosedGroupRatchetTableCommand
= "CREATE TABLE $currentClosedGroupRatchetTable ($closedGroupPublicKey STRING, $senderPublicKey STRING, $chainKey STRING, " +
"$keyIndex INTEGER DEFAULT 0, $messageKeys TEXT, PRIMARY KEY ($closedGroupPublicKey, $senderPublicKey));" "$keyIndex INTEGER DEFAULT 0, $messageKeys TEXT, PRIMARY KEY ($closedGroupPublicKey, $senderPublicKey));"
// Private keys // Private keys
private val closedGroupPrivateKeyTable = "closed_group_private_key_table" private val closedGroupPrivateKeyTable = "closed_group_private_key_table"
@ -32,11 +38,18 @@ class SharedSenderKeysDatabase(context: Context, helper: SQLCipherOpenHelper) :
= "CREATE TABLE $closedGroupPrivateKeyTable ($closedGroupPublicKey STRING PRIMARY KEY, $closedGroupPrivateKey STRING);" = "CREATE TABLE $closedGroupPrivateKeyTable ($closedGroupPublicKey STRING PRIMARY KEY, $closedGroupPrivateKey STRING);"
} }
private fun getTable(collection: ClosedGroupRatchetCollectionType): String {
return when (collection) {
ClosedGroupRatchetCollectionType.Old -> oldClosedGroupRatchetTable
ClosedGroupRatchetCollectionType.Current -> currentClosedGroupRatchetTable
}
}
// region Ratchets & Sender Keys // region Ratchets & Sender Keys
override fun getClosedGroupRatchet(groupPublicKey: String, senderPublicKey: String): ClosedGroupRatchet? { override fun getClosedGroupRatchet(groupPublicKey: String, senderPublicKey: String, collection: ClosedGroupRatchetCollectionType): ClosedGroupRatchet? {
val database = databaseHelper.readableDatabase val database = databaseHelper.readableDatabase
val query = "${Companion.closedGroupPublicKey} = ? AND ${Companion.senderPublicKey} = ?" val query = "${Companion.closedGroupPublicKey} = ? AND ${Companion.senderPublicKey} = ?"
return database.get(closedGroupRatchetTable, query, arrayOf( groupPublicKey, senderPublicKey )) { cursor -> return database.get(getTable(collection), query, arrayOf( groupPublicKey, senderPublicKey )) { cursor ->
val chainKey = cursor.getString(Companion.chainKey) val chainKey = cursor.getString(Companion.chainKey)
val keyIndex = cursor.getInt(Companion.keyIndex) val keyIndex = cursor.getInt(Companion.keyIndex)
val messageKeys = cursor.getString(Companion.messageKeys).split("-") val messageKeys = cursor.getString(Companion.messageKeys).split("-")
@ -44,7 +57,7 @@ class SharedSenderKeysDatabase(context: Context, helper: SQLCipherOpenHelper) :
} }
} }
override fun setClosedGroupRatchet(groupPublicKey: String, senderPublicKey: String, ratchet: ClosedGroupRatchet) { override fun setClosedGroupRatchet(groupPublicKey: String, senderPublicKey: String, ratchet: ClosedGroupRatchet, collection: ClosedGroupRatchetCollectionType) {
val database = databaseHelper.writableDatabase val database = databaseHelper.writableDatabase
val values = ContentValues() val values = ContentValues()
values.put(Companion.closedGroupPublicKey, groupPublicKey) values.put(Companion.closedGroupPublicKey, groupPublicKey)
@ -53,23 +66,33 @@ class SharedSenderKeysDatabase(context: Context, helper: SQLCipherOpenHelper) :
values.put(Companion.keyIndex, ratchet.keyIndex) values.put(Companion.keyIndex, ratchet.keyIndex)
values.put(Companion.messageKeys, ratchet.messageKeys.joinToString("-")) values.put(Companion.messageKeys, ratchet.messageKeys.joinToString("-"))
val query = "${Companion.closedGroupPublicKey} = ? AND ${Companion.senderPublicKey} = ?" val query = "${Companion.closedGroupPublicKey} = ? AND ${Companion.senderPublicKey} = ?"
database.insertOrUpdate(closedGroupRatchetTable, values, query, arrayOf( groupPublicKey, senderPublicKey )) database.insertOrUpdate(getTable(collection), values, query, arrayOf( groupPublicKey, senderPublicKey ))
} }
override fun removeAllClosedGroupRatchets(groupPublicKey: String) { override fun removeAllClosedGroupRatchets(groupPublicKey: String, collection: ClosedGroupRatchetCollectionType) {
val database = databaseHelper.writableDatabase val database = databaseHelper.writableDatabase
val query = "${Companion.closedGroupPublicKey} = ?" val query = "${Companion.closedGroupPublicKey} = ?"
database.delete(closedGroupRatchetTable, query, arrayOf( groupPublicKey )) database.delete(getTable(collection), query, arrayOf( groupPublicKey ))
} }
override fun getAllClosedGroupSenderKeys(groupPublicKey: String): Set<ClosedGroupSenderKey> { override fun getAllClosedGroupRatchets(groupPublicKey: String, collection: ClosedGroupRatchetCollectionType): Set<Pair<String, ClosedGroupRatchet>> {
val database = databaseHelper.readableDatabase val database = databaseHelper.readableDatabase
val query = "${Companion.closedGroupPublicKey} = ?" val query = "${Companion.closedGroupPublicKey} = ?"
return database.getAll(closedGroupRatchetTable, query, arrayOf( groupPublicKey )) { cursor -> return database.getAll(getTable(collection), query, arrayOf( groupPublicKey )) { cursor ->
val chainKey = cursor.getString(Companion.chainKey) val chainKey = cursor.getString(Companion.chainKey)
val keyIndex = cursor.getInt(Companion.keyIndex) val keyIndex = cursor.getInt(Companion.keyIndex)
val messageKeys = cursor.getString(Companion.messageKeys).split("-")
val senderPublicKey = cursor.getString(Companion.senderPublicKey) val senderPublicKey = cursor.getString(Companion.senderPublicKey)
ClosedGroupSenderKey(Hex.fromStringCondensed(chainKey), keyIndex, Hex.fromStringCondensed(senderPublicKey)) val ratchet = ClosedGroupRatchet(chainKey, keyIndex, messageKeys)
Pair(senderPublicKey, ratchet)
}.toSet()
}
override fun getAllClosedGroupSenderKeys(groupPublicKey: String, collection: ClosedGroupRatchetCollectionType): Set<ClosedGroupSenderKey> {
return getAllClosedGroupRatchets(groupPublicKey, collection).map { pair ->
val senderPublicKey = pair.first
val ratchet = pair.second
ClosedGroupSenderKey(Hex.fromStringCondensed(ratchet.chainKey), ratchet.keyIndex, Hex.fromStringCondensed(senderPublicKey))
}.toSet() }.toSet()
} }
// endregion // endregion

View File

@ -153,7 +153,7 @@ class ClosedGroupUpdateMessageSendJob private constructor(parameters: Parameters
"New" -> { "New" -> {
val name = data.getString("name") val name = data.getString("name")
val groupPrivateKey = data.getByteArray("groupPrivateKey") val groupPrivateKey = data.getByteArray("groupPrivateKey")
val senderKeys = data.getString("senderKeys").split(" - ").map { ClosedGroupSenderKey.fromJSON(it)!! } val senderKeys = data.getStringOrDefault("senderKeys", "").split(" - ").mapNotNull { ClosedGroupSenderKey.fromJSON(it) } // Can be empty
val members = data.getString("members").split(" - ").map { Hex.fromStringCondensed(it) } val members = data.getString("members").split(" - ").map { Hex.fromStringCondensed(it) }
val admins = data.getString("admins").split(" - ").map { Hex.fromStringCondensed(it) } val admins = data.getString("admins").split(" - ").map { Hex.fromStringCondensed(it) }
kind = Kind.New(groupPublicKey, name, groupPrivateKey, senderKeys, members, admins) kind = Kind.New(groupPublicKey, name, groupPrivateKey, senderKeys, members, admins)

View File

@ -25,7 +25,9 @@ import org.whispersystems.signalservice.api.messages.SignalServiceGroup
import org.whispersystems.signalservice.api.messages.SignalServiceGroup.GroupType import org.whispersystems.signalservice.api.messages.SignalServiceGroup.GroupType
import org.whispersystems.signalservice.internal.push.SignalServiceProtos import org.whispersystems.signalservice.internal.push.SignalServiceProtos
import org.whispersystems.signalservice.internal.push.SignalServiceProtos.GroupContext import org.whispersystems.signalservice.internal.push.SignalServiceProtos.GroupContext
import org.whispersystems.signalservice.loki.api.SnodeAPI
import org.whispersystems.signalservice.loki.protocol.closedgroups.ClosedGroupRatchet import org.whispersystems.signalservice.loki.protocol.closedgroups.ClosedGroupRatchet
import org.whispersystems.signalservice.loki.protocol.closedgroups.ClosedGroupRatchetCollectionType
import org.whispersystems.signalservice.loki.protocol.closedgroups.ClosedGroupSenderKey import org.whispersystems.signalservice.loki.protocol.closedgroups.ClosedGroupSenderKey
import org.whispersystems.signalservice.loki.protocol.closedgroups.SharedSenderKeysImplementation import org.whispersystems.signalservice.loki.protocol.closedgroups.SharedSenderKeysImplementation
import org.whispersystems.signalservice.loki.utilities.hexEncodedPrivateKey import org.whispersystems.signalservice.loki.utilities.hexEncodedPrivateKey
@ -39,6 +41,12 @@ object ClosedGroupsProtocol {
val isSharedSenderKeysEnabled = true val isSharedSenderKeysEnabled = true
val groupSizeLimit = 20 val groupSizeLimit = 20
sealed class Error(val description: String) : Exception() {
object NoThread : Error("Couldn't find a thread associated with the given group public key")
object NoPrivateKey : Error("Couldn't find a private key associated with the given group public key.")
object InvalidUpdate : Error("Invalid group update.")
}
public fun createClosedGroup(context: Context, name: String, members: Collection<String>): Promise<String, Exception> { public fun createClosedGroup(context: Context, name: String, members: Collection<String>): Promise<String, Exception> {
val deferred = deferred<String, Exception>() val deferred = deferred<String, Exception>()
Thread { Thread {
@ -98,118 +106,135 @@ object ClosedGroupsProtocol {
val name = group.title val name = group.title
val oldMembers = group.members.map { it.serialize() }.toSet() val oldMembers = group.members.map { it.serialize() }.toSet()
val newMembers = oldMembers.minus(userPublicKey) val newMembers = oldMembers.minus(userPublicKey)
update(context, groupPublicKey, newMembers, name) return update(context, groupPublicKey, newMembers, name).get()
} }
public fun update(context: Context, groupPublicKey: String, members: Collection<String>, name: String) { public fun update(context: Context, groupPublicKey: String, members: Collection<String>, name: String): Promise<Unit, Exception> {
val userPublicKey = TextSecurePreferences.getLocalNumber(context) val deferred = deferred<Unit, Exception>()
val sskDatabase = DatabaseFactory.getSSKDatabase(context) Thread {
val groupDB = DatabaseFactory.getGroupDatabase(context) val userPublicKey = TextSecurePreferences.getLocalNumber(context)
val groupID = doubleEncodeGroupID(groupPublicKey) val sskDatabase = DatabaseFactory.getSSKDatabase(context)
val group = groupDB.getGroup(groupID).orNull() val groupDB = DatabaseFactory.getGroupDatabase(context)
if (group == null) { val groupID = doubleEncodeGroupID(groupPublicKey)
Log.d("Loki", "Can't update nonexistent closed group.") val group = groupDB.getGroup(groupID).orNull()
return if (group == null) {
} Log.d("Loki", "Can't update nonexistent closed group.")
val oldMembers = group.members.map { it.serialize() }.toSet() return@Thread deferred.reject(Error.NoThread)
val newMembers = members.minus(oldMembers)
val membersAsData = members.map { Hex.fromStringCondensed(it) }
val admins = group.admins.map { it.serialize() }
val adminsAsData = admins.map { Hex.fromStringCondensed(it) }
val groupPrivateKey = DatabaseFactory.getSSKDatabase(context).getClosedGroupPrivateKey(groupPublicKey)
if (groupPrivateKey == null) {
Log.d("Loki", "Couldn't get private key for closed group.")
return
}
val wasAnyUserRemoved = members.toSet().intersect(oldMembers) != oldMembers.toSet()
val removedMembers = oldMembers.minus(members)
val isUserLeaving = removedMembers.contains(userPublicKey)
var newSenderKeys = listOf<ClosedGroupSenderKey>()
if (wasAnyUserRemoved) {
if (isUserLeaving && removedMembers.count() != 1) {
Log.d("Loki", "Can't remove self and others simultaneously.")
return
} }
// Send the update to the group (don't include new ratchets as everyone should regenerate new ratchets individually) val oldMembers = group.members.map { it.serialize() }.toSet()
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.Info(Hex.fromStringCondensed(groupPublicKey), val newMembers = members.minus(oldMembers)
name, setOf(), membersAsData, adminsAsData) val membersAsData = members.map { Hex.fromStringCondensed(it) }
val job = ClosedGroupUpdateMessageSendJob(groupPublicKey, closedGroupUpdateKind) val admins = group.admins.map { it.serialize() }
job.setContext(context) val adminsAsData = admins.map { Hex.fromStringCondensed(it) }
job.onRun() // Run the job immediately val groupPrivateKey = DatabaseFactory.getSSKDatabase(context).getClosedGroupPrivateKey(groupPublicKey)
// Delete all ratchets (it's important that this happens * after * sending out the update) if (groupPrivateKey == null) {
sskDatabase.removeAllClosedGroupRatchets(groupPublicKey) Log.d("Loki", "Couldn't get private key for closed group.")
// Remove the group from the user's set of public keys to poll for if the user is leaving. Otherwise generate a new ratchet and return@Thread deferred.reject(Error.NoPrivateKey)
// send it out to all members (minus the removed ones) using established channels. }
if (isUserLeaving) { val wasAnyUserRemoved = members.toSet().intersect(oldMembers) != oldMembers.toSet()
sskDatabase.removeClosedGroupPrivateKey(groupPublicKey) val removedMembers = oldMembers.minus(members)
groupDB.setActive(groupID, false) val isUserLeaving = removedMembers.contains(userPublicKey)
groupDB.remove(groupID, Address.fromSerialized(userPublicKey)) var newSenderKeys = listOf<ClosedGroupSenderKey>()
// Notify the PN server if (wasAnyUserRemoved) {
LokiPushNotificationManager.performOperation(context, ClosedGroupOperation.Unsubscribe, groupPublicKey, userPublicKey) if (isUserLeaving && removedMembers.count() != 1) {
} else { Log.d("Loki", "Can't remove self and others simultaneously.")
return@Thread deferred.reject(Error.InvalidUpdate)
}
// Establish sessions if needed // Establish sessions if needed
establishSessionsWithMembersIfNeeded(context, members) establishSessionsWithMembersIfNeeded(context, members)
// Send closed group update messages to any new members using established channels // Send the update to the existing members using established channels (don't include new ratchets as everyone should regenerate new ratchets individually)
for (member in oldMembers) {
@Suppress("NAME_SHADOWING")
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.Info(Hex.fromStringCondensed(groupPublicKey),
name, setOf(), membersAsData, adminsAsData)
@Suppress("NAME_SHADOWING")
val job = ClosedGroupUpdateMessageSendJob(member, closedGroupUpdateKind)
job.setContext(context)
job.onRun() // Run the job immediately
}
val allOldRatchets = sskDatabase.getAllClosedGroupRatchets(groupPublicKey, ClosedGroupRatchetCollectionType.Current)
for (pair in allOldRatchets) {
val senderPublicKey = pair.first
val ratchet = pair.second
val collection = ClosedGroupRatchetCollectionType.Old
sskDatabase.setClosedGroupRatchet(groupPublicKey, senderPublicKey, ratchet, collection)
}
// Delete all ratchets (it's important that this happens * after * sending out the update)
sskDatabase.removeAllClosedGroupRatchets(groupPublicKey, ClosedGroupRatchetCollectionType.Current)
// Remove the group from the user's set of public keys to poll for if the user is leaving. Otherwise generate a new ratchet and
// send it out to all members (minus the removed ones) using established channels.
if (isUserLeaving) {
sskDatabase.removeClosedGroupPrivateKey(groupPublicKey)
groupDB.setActive(groupID, false)
groupDB.remove(groupID, Address.fromSerialized(userPublicKey))
// Notify the PN server
LokiPushNotificationManager.performOperation(context, ClosedGroupOperation.Unsubscribe, groupPublicKey, userPublicKey)
} else {
// Send closed group update messages to any new members using established channels
for (member in newMembers) {
@Suppress("NAME_SHADOWING")
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.New(Hex.fromStringCondensed(groupPublicKey), name,
Hex.fromStringCondensed(groupPrivateKey), listOf(), membersAsData, adminsAsData)
@Suppress("NAME_SHADOWING")
val job = ClosedGroupUpdateMessageSendJob(member, closedGroupUpdateKind)
ApplicationContext.getInstance(context).jobManager.add(job)
}
// Send out the user's new ratchet to all members (minus the removed ones) using established channels
val userRatchet = SharedSenderKeysImplementation.shared.generateRatchet(groupPublicKey, userPublicKey)
val userSenderKey = ClosedGroupSenderKey(Hex.fromStringCondensed(userRatchet.chainKey), userRatchet.keyIndex, Hex.fromStringCondensed(userPublicKey))
for (member in members) {
if (member == userPublicKey) { continue }
@Suppress("NAME_SHADOWING")
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.SenderKey(Hex.fromStringCondensed(groupPublicKey), userSenderKey)
@Suppress("NAME_SHADOWING")
val job = ClosedGroupUpdateMessageSendJob(member, closedGroupUpdateKind)
ApplicationContext.getInstance(context).jobManager.add(job)
}
}
} else if (newMembers.isNotEmpty()) {
// Generate ratchets for any new members
newSenderKeys = newMembers.map { publicKey ->
val ratchet = SharedSenderKeysImplementation.shared.generateRatchet(groupPublicKey, publicKey)
ClosedGroupSenderKey(Hex.fromStringCondensed(ratchet.chainKey), ratchet.keyIndex, Hex.fromStringCondensed(publicKey))
}
// Send a closed group update message to the existing members with the new members' ratchets (this message is aimed at the group)
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.Info(Hex.fromStringCondensed(groupPublicKey), name,
newSenderKeys, membersAsData, adminsAsData)
val job = ClosedGroupUpdateMessageSendJob(groupPublicKey, closedGroupUpdateKind)
ApplicationContext.getInstance(context).jobManager.add(job)
// Establish sessions if needed
establishSessionsWithMembersIfNeeded(context, newMembers)
// Send closed group update messages to the new members using established channels
var allSenderKeys = sskDatabase.getAllClosedGroupSenderKeys(groupPublicKey, ClosedGroupRatchetCollectionType.Current)
allSenderKeys = allSenderKeys.union(newSenderKeys)
for (member in newMembers) { for (member in newMembers) {
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.New(Hex.fromStringCondensed(groupPublicKey), name, val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.New(Hex.fromStringCondensed(groupPublicKey), name,
Hex.fromStringCondensed(groupPrivateKey), listOf(), membersAsData, adminsAsData) Hex.fromStringCondensed(groupPrivateKey), allSenderKeys, membersAsData, adminsAsData)
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
val job = ClosedGroupUpdateMessageSendJob(member, closedGroupUpdateKind) val job = ClosedGroupUpdateMessageSendJob(member, closedGroupUpdateKind)
ApplicationContext.getInstance(context).jobManager.add(job) ApplicationContext.getInstance(context).jobManager.add(job)
} }
// Send out the user's new ratchet to all members (minus the removed ones) using established channels } else {
val userRatchet = SharedSenderKeysImplementation.shared.generateRatchet(groupPublicKey, userPublicKey) val allSenderKeys = sskDatabase.getAllClosedGroupSenderKeys(groupPublicKey, ClosedGroupRatchetCollectionType.Current)
val userSenderKey = ClosedGroupSenderKey(Hex.fromStringCondensed(userRatchet.chainKey), userRatchet.keyIndex, Hex.fromStringCondensed(userPublicKey)) val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.Info(Hex.fromStringCondensed(groupPublicKey), name,
for (member in members) { allSenderKeys, membersAsData, adminsAsData)
if (member == userPublicKey) { continue } val job = ClosedGroupUpdateMessageSendJob(groupPublicKey, closedGroupUpdateKind)
@Suppress("NAME_SHADOWING")
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.SenderKey(Hex.fromStringCondensed(groupPublicKey), userSenderKey)
@Suppress("NAME_SHADOWING")
val job = ClosedGroupUpdateMessageSendJob(member, closedGroupUpdateKind)
ApplicationContext.getInstance(context).jobManager.add(job)
}
}
} else if (newMembers.isNotEmpty()) {
// Generate ratchets for any new members
newSenderKeys = newMembers.map { publicKey ->
val ratchet = SharedSenderKeysImplementation.shared.generateRatchet(groupPublicKey, publicKey)
ClosedGroupSenderKey(Hex.fromStringCondensed(ratchet.chainKey), ratchet.keyIndex, Hex.fromStringCondensed(publicKey))
}
// Send a closed group update message to the existing members with the new members' ratchets (this message is aimed at the group)
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.Info(Hex.fromStringCondensed(groupPublicKey), name,
newSenderKeys, membersAsData, adminsAsData)
val job = ClosedGroupUpdateMessageSendJob(groupPublicKey, closedGroupUpdateKind)
ApplicationContext.getInstance(context).jobManager.add(job)
// Establish sessions if needed
establishSessionsWithMembersIfNeeded(context, newMembers)
// Send closed group update messages to the new members using established channels
var allSenderKeys = sskDatabase.getAllClosedGroupSenderKeys(groupPublicKey);
allSenderKeys = allSenderKeys.union(newSenderKeys)
for (member in newMembers) {
@Suppress("NAME_SHADOWING")
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.New(Hex.fromStringCondensed(groupPublicKey), name,
Hex.fromStringCondensed(groupPrivateKey), allSenderKeys, membersAsData, adminsAsData)
@Suppress("NAME_SHADOWING")
val job = ClosedGroupUpdateMessageSendJob(member, closedGroupUpdateKind)
ApplicationContext.getInstance(context).jobManager.add(job) ApplicationContext.getInstance(context).jobManager.add(job)
} }
} else { // Update the group
val allSenderKeys = sskDatabase.getAllClosedGroupSenderKeys(groupPublicKey); groupDB.updateTitle(groupID, name)
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.Info(Hex.fromStringCondensed(groupPublicKey), name, if (!isUserLeaving) {
allSenderKeys, membersAsData, adminsAsData) // The call below sets isActive to true, so if the user is leaving we have to use groupDB.remove(...) instead
val job = ClosedGroupUpdateMessageSendJob(groupPublicKey, closedGroupUpdateKind) groupDB.updateMembers(groupID, members.map { Address.fromSerialized(it) })
ApplicationContext.getInstance(context).jobManager.add(job) }
} // Notify the user
// Update the group val infoType = if (isUserLeaving) GroupContext.Type.QUIT else GroupContext.Type.UPDATE
groupDB.updateTitle(groupID, name) val threadID = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(Recipient.from(context, Address.fromSerialized(groupID), false))
if (!isUserLeaving) { insertOutgoingInfoMessage(context, groupID, infoType, name, members, admins, threadID)
// The call below sets isActive to true, so if the user is leaving we have to use groupDB.remove(...) instead deferred.resolve(Unit)
groupDB.updateMembers(groupID, members.map { Address.fromSerialized(it) }) }.start()
} return deferred.promise
// Notify the user
val threadID = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(Recipient.from(context, Address.fromSerialized(groupID), false))
insertOutgoingInfoMessage(context, groupID, GroupContext.Type.UPDATE, name, members, admins, threadID)
} }
@JvmStatic @JvmStatic
@ -270,7 +295,7 @@ object ClosedGroupsProtocol {
senderKeys.forEach { senderKey -> senderKeys.forEach { senderKey ->
if (!members.contains(senderKey.publicKey.toHexString())) { return@forEach } if (!members.contains(senderKey.publicKey.toHexString())) { return@forEach }
val ratchet = ClosedGroupRatchet(senderKey.chainKey.toHexString(), senderKey.keyIndex, listOf()) val ratchet = ClosedGroupRatchet(senderKey.chainKey.toHexString(), senderKey.keyIndex, listOf())
sskDatabase.setClosedGroupRatchet(groupPublicKey, senderKey.publicKey.toHexString(), ratchet) sskDatabase.setClosedGroupRatchet(groupPublicKey, senderKey.publicKey.toHexString(), ratchet, ClosedGroupRatchetCollectionType.Current)
} }
// Sort out any discrepancies between the provided sender keys and what's required // Sort out any discrepancies between the provided sender keys and what's required
val missingSenderKeys = members.toSet().subtract(senderKeys.map { Hex.toStringCondensed(it.publicKey) }) val missingSenderKeys = members.toSet().subtract(senderKeys.map { Hex.toStringCondensed(it.publicKey) })
@ -340,7 +365,7 @@ object ClosedGroupsProtocol {
// Store the ratchets for any new members (it's important that this happens before the code below) // Store the ratchets for any new members (it's important that this happens before the code below)
senderKeys.forEach { senderKey -> senderKeys.forEach { senderKey ->
val ratchet = ClosedGroupRatchet(senderKey.chainKey.toHexString(), senderKey.keyIndex, listOf()) val ratchet = ClosedGroupRatchet(senderKey.chainKey.toHexString(), senderKey.keyIndex, listOf())
sskDatabase.setClosedGroupRatchet(groupPublicKey, senderKey.publicKey.toHexString(), ratchet) sskDatabase.setClosedGroupRatchet(groupPublicKey, senderKey.publicKey.toHexString(), ratchet, ClosedGroupRatchetCollectionType.Current)
} }
// Delete all ratchets and either: // Delete all ratchets and either:
// • Send out the user's new ratchet using established channels if other members of the group left or were removed // • Send out the user's new ratchet using established channels if other members of the group left or were removed
@ -349,7 +374,14 @@ object ClosedGroupsProtocol {
val wasAnyUserRemoved = members.toSet().intersect(oldMembers) != oldMembers.toSet() val wasAnyUserRemoved = members.toSet().intersect(oldMembers) != oldMembers.toSet()
val wasSenderRemoved = !members.contains(senderPublicKey) val wasSenderRemoved = !members.contains(senderPublicKey)
if (wasAnyUserRemoved) { if (wasAnyUserRemoved) {
sskDatabase.removeAllClosedGroupRatchets(groupPublicKey) val allOldRatchets = sskDatabase.getAllClosedGroupRatchets(groupPublicKey, ClosedGroupRatchetCollectionType.Current)
for (pair in allOldRatchets) {
@Suppress("NAME_SHADOWING") val senderPublicKey = pair.first
val ratchet = pair.second
val collection = ClosedGroupRatchetCollectionType.Old
sskDatabase.setClosedGroupRatchet(groupPublicKey, senderPublicKey, ratchet, collection)
}
sskDatabase.removeAllClosedGroupRatchets(groupPublicKey, ClosedGroupRatchetCollectionType.Current)
if (wasCurrentUserRemoved) { if (wasCurrentUserRemoved) {
sskDatabase.removeClosedGroupPrivateKey(groupPublicKey) sskDatabase.removeClosedGroupPrivateKey(groupPublicKey)
groupDB.setActive(groupID, false) groupDB.setActive(groupID, false)
@ -399,7 +431,7 @@ object ClosedGroupsProtocol {
// Respond to the request // Respond to the request
Log.d("Loki", "Responding to sender key request from: $senderPublicKey.") Log.d("Loki", "Responding to sender key request from: $senderPublicKey.")
ApplicationContext.getInstance(context).sendSessionRequestIfNeeded(senderPublicKey) ApplicationContext.getInstance(context).sendSessionRequestIfNeeded(senderPublicKey)
val userRatchet = DatabaseFactory.getSSKDatabase(context).getClosedGroupRatchet(groupPublicKey, userPublicKey) val userRatchet = DatabaseFactory.getSSKDatabase(context).getClosedGroupRatchet(groupPublicKey, userPublicKey, ClosedGroupRatchetCollectionType.Current)
?: SharedSenderKeysImplementation.shared.generateRatchet(groupPublicKey, userPublicKey) ?: SharedSenderKeysImplementation.shared.generateRatchet(groupPublicKey, userPublicKey)
val userSenderKey = ClosedGroupSenderKey(Hex.fromStringCondensed(userRatchet.chainKey), userRatchet.keyIndex, Hex.fromStringCondensed(userPublicKey)) val userSenderKey = ClosedGroupSenderKey(Hex.fromStringCondensed(userRatchet.chainKey), userRatchet.keyIndex, Hex.fromStringCondensed(userPublicKey))
val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.SenderKey(Hex.fromStringCondensed(groupPublicKey), userSenderKey) val closedGroupUpdateKind = ClosedGroupUpdateMessageSendJob.Kind.SenderKey(Hex.fromStringCondensed(groupPublicKey), userSenderKey)
@ -424,7 +456,7 @@ object ClosedGroupsProtocol {
// Store the sender key // Store the sender key
Log.d("Loki", "Received a sender key from: $senderPublicKey.") Log.d("Loki", "Received a sender key from: $senderPublicKey.")
val ratchet = ClosedGroupRatchet(senderKey.chainKey.toHexString(), senderKey.keyIndex, listOf()) val ratchet = ClosedGroupRatchet(senderKey.chainKey.toHexString(), senderKey.keyIndex, listOf())
sskDatabase.setClosedGroupRatchet(groupPublicKey, senderPublicKey, ratchet) sskDatabase.setClosedGroupRatchet(groupPublicKey, senderPublicKey, ratchet, ClosedGroupRatchetCollectionType.Current)
} }
@JvmStatic @JvmStatic

View File

@ -140,7 +140,12 @@ class SaveAttachmentTask : ProgressDialogAsyncTask<SaveAttachmentTask.Attachment
} }
} }
val mediaFileUri = resolver.insert(collectionUri, mediaRecord) var mediaFileUri: Uri?
try {
mediaFileUri = resolver.insert(collectionUri, mediaRecord)
} catch (exception: Exception) {
return null
}
if (mediaFileUri == null) return null if (mediaFileUri == null) return null
val inputStream = PartAuthority.getAttachmentStream(context, attachment.uri) val inputStream = PartAuthority.getAttachmentStream(context, attachment.uri)