mirror of
https://github.com/oxen-io/session-android.git
synced 2024-12-24 16:57:50 +00:00
Merge branch 'dev' of https://github.com/oxen-io/session-android into screenlock-timeout
This commit is contained in:
commit
b23144cb1a
20
app/src/main/java/org/thoughtcrime/securesms/AppContext.kt
Normal file
20
app/src/main/java/org/thoughtcrime/securesms/AppContext.kt
Normal file
@ -0,0 +1,20 @@
|
||||
package org.thoughtcrime.securesms
|
||||
|
||||
import android.util.Log
|
||||
import nl.komponents.kovenant.Kovenant
|
||||
import nl.komponents.kovenant.jvm.asDispatcher
|
||||
import org.session.libsignal.utilities.ThreadUtils
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
object AppContext {
|
||||
|
||||
fun configureKovenant() {
|
||||
Kovenant.context {
|
||||
callbackContext.dispatcher = Executors.newSingleThreadExecutor().asDispatcher()
|
||||
workerContext.dispatcher = ThreadUtils.executorPool.asDispatcher()
|
||||
multipleCompletion = { v1, v2 ->
|
||||
Log.d("Loki", "Promise resolved more than once (first with $v1, then with $v2); ignoring $v2.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -49,7 +49,7 @@ import org.session.libsession.utilities.dynamiclanguage.DynamicLanguageContextWr
|
||||
import org.session.libsession.utilities.dynamiclanguage.LocaleParser;
|
||||
import org.session.libsession.utilities.preferences.ProfileKeyUtil;
|
||||
import org.session.libsignal.service.api.util.StreamDetails;
|
||||
import org.session.libsignal.service.loki.database.LokiAPIDatabaseProtocol;
|
||||
import org.session.libsignal.service.loki.LokiAPIDatabaseProtocol;
|
||||
import org.session.libsignal.utilities.logging.Log;
|
||||
import org.signal.aesgcmprovider.AesGcmProvider;
|
||||
import org.thoughtcrime.securesms.components.TypingStatusSender;
|
||||
@ -93,7 +93,6 @@ import org.webrtc.voiceengine.WebRtcAudioUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Security;
|
||||
import java.util.Date;
|
||||
@ -104,6 +103,7 @@ import dagger.ObjectGraph;
|
||||
import kotlin.Unit;
|
||||
import kotlinx.coroutines.Job;
|
||||
import network.loki.messenger.BuildConfig;
|
||||
import nl.komponents.kovenant.Kovenant;
|
||||
|
||||
import static nl.komponents.kovenant.android.KovenantAndroid.startKovenant;
|
||||
import static nl.komponents.kovenant.android.KovenantAndroid.stopKovenant;
|
||||
@ -164,6 +164,7 @@ public class ApplicationContext extends MultiDexApplication implements Dependenc
|
||||
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
|
||||
// Loki
|
||||
// ========
|
||||
AppContext.INSTANCE.configureKovenant();
|
||||
messageNotifier = new OptimizedMessageNotifier(new DefaultMessageNotifier());
|
||||
broadcaster = new Broadcaster(this);
|
||||
threadNotificationHandler = new Handler(Looper.getMainLooper());
|
||||
|
@ -95,7 +95,7 @@ import org.session.libsession.utilities.GroupUtil;
|
||||
import org.session.libsession.utilities.MediaTypes;
|
||||
import org.session.libsignal.libsignal.InvalidMessageException;
|
||||
import org.session.libsignal.libsignal.util.guava.Optional;
|
||||
import org.session.libsignal.service.loki.utilities.mentions.Mention;
|
||||
import org.session.libsignal.service.loki.Mention;
|
||||
import org.session.libsignal.service.loki.utilities.HexEncodingKt;
|
||||
import org.session.libsignal.service.loki.utilities.PublicKeyValidation;
|
||||
import org.thoughtcrime.securesms.ApplicationContext;
|
||||
|
@ -25,10 +25,9 @@ import org.session.libsession.utilities.Util;
|
||||
|
||||
import org.session.libsignal.libsignal.util.guava.Optional;
|
||||
import org.session.libsignal.service.api.messages.SignalServiceAttachmentPointer;
|
||||
import org.session.libsignal.service.loki.database.LokiOpenGroupDatabaseProtocol;
|
||||
import org.session.libsignal.service.loki.LokiOpenGroupDatabaseProtocol;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
@ -44,6 +43,7 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt
|
||||
static final String GROUP_ID = "group_id";
|
||||
private static final String TITLE = "title";
|
||||
private static final String MEMBERS = "members";
|
||||
private static final String ZOMBIE_MEMBERS = "zombie_members";
|
||||
private static final String AVATAR = "avatar";
|
||||
private static final String AVATAR_ID = "avatar_id";
|
||||
private static final String AVATAR_KEY = "avatar_key";
|
||||
@ -64,6 +64,7 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt
|
||||
GROUP_ID + " TEXT, " +
|
||||
TITLE + " TEXT, " +
|
||||
MEMBERS + " TEXT, " +
|
||||
ZOMBIE_MEMBERS + " TEXT, " +
|
||||
AVATAR + " BLOB, " +
|
||||
AVATAR_ID + " INTEGER, " +
|
||||
AVATAR_KEY + " BLOB, " +
|
||||
@ -81,7 +82,7 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt
|
||||
};
|
||||
|
||||
private static final String[] GROUP_PROJECTION = {
|
||||
GROUP_ID, TITLE, MEMBERS, AVATAR, AVATAR_ID, AVATAR_KEY, AVATAR_CONTENT_TYPE, AVATAR_RELAY, AVATAR_DIGEST,
|
||||
GROUP_ID, TITLE, MEMBERS, ZOMBIE_MEMBERS, AVATAR, AVATAR_ID, AVATAR_KEY, AVATAR_CONTENT_TYPE, AVATAR_RELAY, AVATAR_DIGEST,
|
||||
TIMESTAMP, ACTIVE, MMS, AVATAR_URL, ADMINS
|
||||
};
|
||||
|
||||
@ -162,7 +163,7 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt
|
||||
}
|
||||
|
||||
public @NonNull List<Recipient> getGroupMembers(String groupId, boolean includeSelf) {
|
||||
List<Address> members = getCurrentMembers(groupId);
|
||||
List<Address> members = getCurrentMembers(groupId, false);
|
||||
List<Recipient> recipients = new LinkedList<>();
|
||||
|
||||
for (Address member : members) {
|
||||
@ -177,6 +178,17 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt
|
||||
return recipients;
|
||||
}
|
||||
|
||||
public @NonNull List<Recipient> getGroupZombieMembers(String groupId) {
|
||||
List<Address> members = getCurrentZombieMembers(groupId);
|
||||
List<Recipient> recipients = new LinkedList<>();
|
||||
|
||||
for (Address member : members) {
|
||||
recipients.add(Recipient.from(context, member, false));
|
||||
}
|
||||
|
||||
return recipients;
|
||||
}
|
||||
|
||||
public long create(@NonNull String groupId, @Nullable String title, @NonNull List<Address> members,
|
||||
@Nullable SignalServiceAttachmentPointer avatar, @Nullable String relay, @Nullable List<Address> admins, @NonNull Long formationTimestamp)
|
||||
{
|
||||
@ -300,6 +312,16 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt
|
||||
});
|
||||
}
|
||||
|
||||
public void updateZombieMembers(String groupId, List<Address> members) {
|
||||
Collections.sort(members);
|
||||
|
||||
ContentValues contents = new ContentValues();
|
||||
contents.put(ZOMBIE_MEMBERS, Address.toSerializedList(members, ','));
|
||||
contents.put(ACTIVE, 1);
|
||||
databaseHelper.getWritableDatabase().update(TABLE_NAME, contents, GROUP_ID + " = ?",
|
||||
new String[] {groupId});
|
||||
}
|
||||
|
||||
public void updateAdmins(String groupId, List<Address> admins) {
|
||||
Collections.sort(admins);
|
||||
|
||||
@ -311,7 +333,7 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt
|
||||
}
|
||||
|
||||
public void removeMember(String groupId, Address source) {
|
||||
List<Address> currentMembers = getCurrentMembers(groupId);
|
||||
List<Address> currentMembers = getCurrentMembers(groupId, false);
|
||||
currentMembers.remove(source);
|
||||
|
||||
ContentValues contents = new ContentValues();
|
||||
@ -329,17 +351,21 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt
|
||||
});
|
||||
}
|
||||
|
||||
private List<Address> getCurrentMembers(String groupId) {
|
||||
private List<Address> getCurrentMembers(String groupId, boolean zombieMembers) {
|
||||
Cursor cursor = null;
|
||||
|
||||
String membersColumn = MEMBERS;
|
||||
if (zombieMembers) membersColumn = ZOMBIE_MEMBERS;
|
||||
|
||||
try {
|
||||
cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, new String[] {MEMBERS},
|
||||
cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, new String[] {membersColumn},
|
||||
GROUP_ID + " = ?",
|
||||
new String[] {groupId},
|
||||
null, null, null);
|
||||
|
||||
if (cursor != null && cursor.moveToFirst()) {
|
||||
String serializedMembers = cursor.getString(cursor.getColumnIndexOrThrow(MEMBERS));
|
||||
String serializedMembers = cursor.getString(cursor.getColumnIndexOrThrow(membersColumn));
|
||||
if (serializedMembers != null && !serializedMembers.isEmpty())
|
||||
return Address.fromSerializedList(serializedMembers, ',');
|
||||
}
|
||||
|
||||
@ -350,6 +376,10 @@ public class GroupDatabase extends Database implements LokiOpenGroupDatabaseProt
|
||||
}
|
||||
}
|
||||
|
||||
private List<Address> getCurrentZombieMembers(String groupId) {
|
||||
return getCurrentMembers(groupId, true);
|
||||
}
|
||||
|
||||
public boolean isActive(String groupId) {
|
||||
Optional<GroupRecord> record = getGroup(groupId);
|
||||
return record.isPresent() && record.get().isActive();
|
||||
|
@ -391,6 +391,10 @@ class Storage(context: Context, helper: SQLCipherOpenHelper) : Database(context,
|
||||
DatabaseFactory.getGroupDatabase(context).setActive(groupID, value)
|
||||
}
|
||||
|
||||
override fun getZombieMember(groupID: String): Set<String> {
|
||||
return DatabaseFactory.getGroupDatabase(context).getGroupZombieMembers(groupID).map { it.address.serialize() }.toHashSet()
|
||||
}
|
||||
|
||||
override fun removeMember(groupID: String, member: Address) {
|
||||
DatabaseFactory.getGroupDatabase(context).removeMember(groupID, member)
|
||||
}
|
||||
@ -399,6 +403,10 @@ class Storage(context: Context, helper: SQLCipherOpenHelper) : Database(context,
|
||||
DatabaseFactory.getGroupDatabase(context).updateMembers(groupID, members)
|
||||
}
|
||||
|
||||
override fun updateZombieMembers(groupID: String, members: List<Address>) {
|
||||
DatabaseFactory.getGroupDatabase(context).updateZombieMembers(groupID, members)
|
||||
}
|
||||
|
||||
override fun insertIncomingInfoMessage(context: Context, senderPublicKey: String, groupID: String, type: SignalServiceGroup.Type, name: String, members: Collection<String>, admins: Collection<String>, sentTimestamp: Long) {
|
||||
val group = SignalServiceGroup(type, GroupUtil.getDecodedGroupIDAsData(groupID), SignalServiceGroup.GroupType.SIGNAL, name, members.toList(), null, admins.toList())
|
||||
val m = IncomingTextMessage(Address.fromSerialized(senderPublicKey), 1, sentTimestamp, "", Optional.of(group), 0, true)
|
||||
|
@ -54,9 +54,10 @@ public class SQLCipherOpenHelper extends SQLiteOpenHelper {
|
||||
private static final int lokiV20 = 41;
|
||||
private static final int lokiV21 = 42;
|
||||
private static final int lokiV22 = 43;
|
||||
private static final int lokiV23 = 44;
|
||||
|
||||
// Loki - onUpgrade(...) must be updated to use Loki version numbers if Signal makes any database changes
|
||||
private static final int DATABASE_VERSION = lokiV22;
|
||||
private static final int DATABASE_VERSION = lokiV23;
|
||||
private static final String DATABASE_NAME = "signal.db";
|
||||
|
||||
private final Context context;
|
||||
@ -272,6 +273,10 @@ public class SQLCipherOpenHelper extends SQLiteOpenHelper {
|
||||
"SendDeliveryReceiptJob");
|
||||
}
|
||||
|
||||
if (oldVersion < lokiV23) {
|
||||
db.execSQL("ALTER TABLE groups ADD COLUMN zombie_members TEXT");
|
||||
}
|
||||
|
||||
db.setTransactionSuccessful();
|
||||
} finally {
|
||||
db.endTransaction();
|
||||
|
@ -37,8 +37,14 @@ import java.io.IOException
|
||||
|
||||
class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
private val originalMembers = HashSet<String>()
|
||||
private val zombies = HashSet<String>()
|
||||
private val members = HashSet<String>()
|
||||
private val allMembers: Set<String>
|
||||
get() {
|
||||
return members + zombies
|
||||
}
|
||||
private var hasNameChanged = false
|
||||
private var isSelfAdmin = false
|
||||
private var isLoading = false
|
||||
set(newValue) { field = newValue; invalidateOptionsMenu() }
|
||||
|
||||
@ -54,7 +60,10 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
}
|
||||
|
||||
private val memberListAdapter by lazy {
|
||||
EditClosedGroupMembersAdapter(this, GlideApp.with(this), this::onMemberClick)
|
||||
if (isSelfAdmin)
|
||||
EditClosedGroupMembersAdapter(this, GlideApp.with(this), isSelfAdmin, this::onMemberClick)
|
||||
else
|
||||
EditClosedGroupMembersAdapter(this, GlideApp.with(this), isSelfAdmin)
|
||||
}
|
||||
|
||||
private lateinit var mainContentContainer: LinearLayout
|
||||
@ -81,7 +90,10 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
ThemeUtil.getThemedDrawableResId(this, R.attr.actionModeCloseDrawable))
|
||||
|
||||
groupID = intent.getStringExtra(groupIDKey)!!
|
||||
originalName = DatabaseFactory.getGroupDatabase(this).getGroup(groupID).get().title
|
||||
val groupInfo = DatabaseFactory.getGroupDatabase(this).getGroup(groupID).get()
|
||||
originalName = groupInfo.title
|
||||
isSelfAdmin = groupInfo.admins.any{ it.serialize() == TextSecurePreferences.getLocalNumber(this) }
|
||||
|
||||
name = originalName
|
||||
|
||||
mainContentContainer = findViewById(R.id.mainContentContainer)
|
||||
@ -116,31 +128,35 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
LoaderManager.getInstance(this).initLoader(loaderID, null, object : LoaderManager.LoaderCallbacks<List<String>> {
|
||||
LoaderManager.getInstance(this).initLoader(loaderID, null, object : LoaderManager.LoaderCallbacks<GroupMembers> {
|
||||
|
||||
override fun onCreateLoader(id: Int, bundle: Bundle?): Loader<List<String>> {
|
||||
override fun onCreateLoader(id: Int, bundle: Bundle?): Loader<GroupMembers> {
|
||||
return EditClosedGroupLoader(this@EditClosedGroupActivity, groupID)
|
||||
}
|
||||
|
||||
override fun onLoadFinished(loader: Loader<List<String>>, members: List<String>) {
|
||||
override fun onLoadFinished(loader: Loader<GroupMembers>, groupMembers: GroupMembers) {
|
||||
// We no longer need any subsequent loading events
|
||||
// (they will occur on every activity resume).
|
||||
LoaderManager.getInstance(this@EditClosedGroupActivity).destroyLoader(loaderID)
|
||||
|
||||
members.clear()
|
||||
members.addAll(groupMembers.members.toHashSet())
|
||||
zombies.clear()
|
||||
zombies.addAll(groupMembers.zombieMembers.toHashSet())
|
||||
originalMembers.clear()
|
||||
originalMembers.addAll(members.toHashSet())
|
||||
updateMembers(originalMembers)
|
||||
originalMembers.addAll(members + zombies)
|
||||
updateMembers()
|
||||
}
|
||||
|
||||
override fun onLoaderReset(loader: Loader<List<String>>) {
|
||||
updateMembers(setOf())
|
||||
override fun onLoaderReset(loader: Loader<GroupMembers>) {
|
||||
updateMembers()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
override fun onCreateOptionsMenu(menu: Menu): Boolean {
|
||||
menuInflater.inflate(R.menu.menu_edit_closed_group, menu)
|
||||
return members.isNotEmpty() && !isLoading
|
||||
return allMembers.isNotEmpty() && !isLoading
|
||||
}
|
||||
// endregion
|
||||
|
||||
@ -153,8 +169,8 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
if (data == null || data.extras == null || !data.hasExtra(SelectContactsActivity.selectedContactsKey)) return
|
||||
|
||||
val selectedContacts = data.extras!!.getStringArray(SelectContactsActivity.selectedContactsKey)!!.toSet()
|
||||
val changedMembers = members + selectedContacts
|
||||
updateMembers(changedMembers)
|
||||
members.addAll(selectedContacts)
|
||||
updateMembers()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -173,17 +189,12 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateMembers(members: Set<String>) {
|
||||
this.members.clear()
|
||||
this.members.addAll(members)
|
||||
memberListAdapter.setMembers(members)
|
||||
private fun updateMembers() {
|
||||
memberListAdapter.setMembers(allMembers)
|
||||
memberListAdapter.setZombieMembers(zombies)
|
||||
|
||||
val admins = DatabaseFactory.getGroupDatabase(this).getGroup(groupID).get().admins.map { it.toString() }.toMutableSet()
|
||||
admins.remove(TextSecurePreferences.getLocalNumber(this))
|
||||
memberListAdapter.setLockedMembers(admins)
|
||||
|
||||
mainContentContainer.visibility = if (members.isEmpty()) View.GONE else View.VISIBLE
|
||||
emptyStateContainer.visibility = if (members.isEmpty()) View.VISIBLE else View.GONE
|
||||
mainContentContainer.visibility = if (allMembers.isEmpty()) View.GONE else View.VISIBLE
|
||||
emptyStateContainer.visibility = if (allMembers.isEmpty()) View.VISIBLE else View.GONE
|
||||
|
||||
invalidateOptionsMenu()
|
||||
}
|
||||
@ -200,8 +211,9 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
private fun onMemberClick(member: String) {
|
||||
val bottomSheet = ClosedGroupEditingOptionsBottomSheet()
|
||||
bottomSheet.onRemoveTapped = {
|
||||
val changedMembers = members - member
|
||||
updateMembers(changedMembers)
|
||||
if (zombies.contains(member)) zombies.remove(member)
|
||||
else members.remove(member)
|
||||
updateMembers()
|
||||
bottomSheet.dismiss()
|
||||
}
|
||||
bottomSheet.show(supportFragmentManager, "GroupEditingOptionsBottomSheet")
|
||||
@ -209,7 +221,7 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
|
||||
private fun onAddMembersClick() {
|
||||
val intent = Intent(this@EditClosedGroupActivity, SelectContactsActivity::class.java)
|
||||
intent.putExtra(SelectContactsActivity.usersToExcludeKey, members.toTypedArray())
|
||||
intent.putExtra(SelectContactsActivity.usersToExcludeKey, allMembers.toTypedArray())
|
||||
intent.putExtra(SelectContactsActivity.emptyStateTextKey, "No contacts to add")
|
||||
startActivityForResult(intent, addUsersRequestCode)
|
||||
}
|
||||
@ -229,7 +241,7 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
}
|
||||
|
||||
private fun commitChanges() {
|
||||
val hasMemberListChanges = (members != originalMembers)
|
||||
val hasMemberListChanges = (allMembers != originalMembers)
|
||||
|
||||
if (!hasNameChanged && !hasMemberListChanges) {
|
||||
return finish()
|
||||
@ -237,15 +249,13 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
|
||||
val name = if (hasNameChanged) this.name else originalName
|
||||
|
||||
val members = this.members.map {
|
||||
val members = this.allMembers.map {
|
||||
Recipient.from(this, Address.fromSerialized(it), false)
|
||||
}.toSet()
|
||||
val originalMembers = this.originalMembers.map {
|
||||
Recipient.from(this, Address.fromSerialized(it), false)
|
||||
}.toSet()
|
||||
|
||||
val admins = members.toSet() //TODO For now, consider all the users to be admins.
|
||||
|
||||
var isClosedGroup: Boolean
|
||||
var groupPublicKey: String?
|
||||
try {
|
||||
@ -303,4 +313,6 @@ class EditClosedGroupActivity : PassphraseRequiredActionBarActivity() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class GroupMembers(val members: List<String>, val zombieMembers: List<String>) { }
|
||||
}
|
@ -4,12 +4,19 @@ import android.content.Context
|
||||
import org.thoughtcrime.securesms.database.DatabaseFactory
|
||||
import org.thoughtcrime.securesms.util.AsyncLoader
|
||||
|
||||
class EditClosedGroupLoader(context: Context, val groupID: String) : AsyncLoader<List<String>>(context) {
|
||||
class EditClosedGroupLoader(context: Context, val groupID: String) : AsyncLoader<EditClosedGroupActivity.GroupMembers>(context) {
|
||||
|
||||
override fun loadInBackground(): List<String> {
|
||||
val members = DatabaseFactory.getGroupDatabase(context).getGroupMembers(groupID, true)
|
||||
return members.map {
|
||||
override fun loadInBackground(): EditClosedGroupActivity.GroupMembers {
|
||||
val groupDatabase = DatabaseFactory.getGroupDatabase(context)
|
||||
val members = groupDatabase.getGroupMembers(groupID, true)
|
||||
val zombieMembers = groupDatabase.getGroupZombieMembers(groupID)
|
||||
return EditClosedGroupActivity.GroupMembers(
|
||||
members.map {
|
||||
it.address.toString()
|
||||
},
|
||||
zombieMembers.map {
|
||||
it.address.toString()
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
@ -7,15 +7,17 @@ import org.session.libsession.messaging.threads.Address
|
||||
import org.thoughtcrime.securesms.loki.views.UserView
|
||||
import org.thoughtcrime.securesms.mms.GlideRequests
|
||||
import org.session.libsession.messaging.threads.recipients.Recipient
|
||||
import org.session.libsession.utilities.TextSecurePreferences
|
||||
|
||||
class EditClosedGroupMembersAdapter(
|
||||
private val context: Context,
|
||||
private val glide: GlideRequests,
|
||||
private val admin: Boolean,
|
||||
private val memberClickListener: ((String) -> Unit)? = null
|
||||
) : RecyclerView.Adapter<EditClosedGroupMembersAdapter.ViewHolder>() {
|
||||
|
||||
private val members = ArrayList<String>()
|
||||
private val lockedMembers = HashSet<String>()
|
||||
private val zombieMembers = ArrayList<String>()
|
||||
|
||||
fun setMembers(members: Collection<String>) {
|
||||
this.members.clear()
|
||||
@ -23,9 +25,9 @@ class EditClosedGroupMembersAdapter(
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
fun setLockedMembers(members: Collection<String>) {
|
||||
this.lockedMembers.clear()
|
||||
this.lockedMembers.addAll(members)
|
||||
fun setZombieMembers(members: Collection<String>) {
|
||||
this.zombieMembers.clear()
|
||||
this.zombieMembers.addAll(members)
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
@ -39,15 +41,20 @@ class EditClosedGroupMembersAdapter(
|
||||
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
|
||||
val member = members[position]
|
||||
|
||||
val lockedMember = lockedMembers.contains(member)
|
||||
val unlocked = admin && member != TextSecurePreferences.getLocalNumber(context)
|
||||
|
||||
viewHolder.view.bind(Recipient.from(
|
||||
context,
|
||||
Address.fromSerialized(member), false),
|
||||
glide,
|
||||
if (lockedMember) UserView.ActionIndicator.None else UserView.ActionIndicator.Menu)
|
||||
if (unlocked) UserView.ActionIndicator.Menu else UserView.ActionIndicator.None)
|
||||
|
||||
if (!lockedMember) {
|
||||
if (zombieMembers.contains(member))
|
||||
viewHolder.view.alpha = 0.5F
|
||||
else
|
||||
viewHolder.view.alpha = 1F
|
||||
|
||||
if (unlocked) {
|
||||
viewHolder.view.setOnClickListener { this.memberClickListener?.invoke(member) }
|
||||
}
|
||||
}
|
||||
|
@ -27,7 +27,7 @@ import kotlinx.coroutines.launch
|
||||
import network.loki.messenger.R
|
||||
import org.session.libsession.utilities.TextSecurePreferences
|
||||
import org.session.libsignal.libsignal.util.KeyHelper
|
||||
import org.session.libsignal.service.loki.crypto.MnemonicCodec
|
||||
import org.session.libsignal.service.loki.MnemonicCodec
|
||||
import org.session.libsignal.service.loki.utilities.hexEncodedPublicKey
|
||||
import org.session.libsignal.utilities.Hex
|
||||
import org.session.libsignal.utilities.logging.Log
|
||||
|
@ -15,7 +15,7 @@ import kotlinx.android.synthetic.main.activity_recovery_phrase_restore.*
|
||||
import network.loki.messenger.R
|
||||
import org.session.libsession.utilities.TextSecurePreferences
|
||||
import org.session.libsignal.libsignal.util.KeyHelper
|
||||
import org.session.libsignal.service.loki.crypto.MnemonicCodec
|
||||
import org.session.libsignal.service.loki.MnemonicCodec
|
||||
import org.session.libsignal.service.loki.utilities.hexEncodedPublicKey
|
||||
import org.session.libsignal.utilities.Hex
|
||||
import org.thoughtcrime.securesms.BaseActionBarActivity
|
||||
|
@ -16,7 +16,7 @@ import org.session.libsession.utilities.IdentityKeyUtil
|
||||
import org.thoughtcrime.securesms.loki.utilities.MnemonicUtilities
|
||||
import org.thoughtcrime.securesms.loki.utilities.getColorWithID
|
||||
import org.session.libsession.utilities.TextSecurePreferences
|
||||
import org.session.libsignal.service.loki.crypto.MnemonicCodec
|
||||
import org.session.libsignal.service.loki.MnemonicCodec
|
||||
import org.session.libsignal.service.loki.utilities.hexEncodedPrivateKey
|
||||
|
||||
class SeedActivity : BaseActionBarActivity() {
|
||||
|
@ -9,11 +9,11 @@ import nl.komponents.kovenant.all
|
||||
import nl.komponents.kovenant.functional.map
|
||||
import org.session.libsession.messaging.jobs.MessageReceiveJob
|
||||
import org.session.libsession.messaging.open_groups.OpenGroup
|
||||
import org.session.libsession.messaging.sending_receiving.pollers.ClosedGroupPoller
|
||||
import org.session.libsession.messaging.sending_receiving.pollers.OpenGroupPoller
|
||||
import org.session.libsession.snode.SnodeAPI
|
||||
import org.session.libsession.utilities.TextSecurePreferences
|
||||
import org.session.libsignal.utilities.logging.Log
|
||||
import org.thoughtcrime.securesms.ApplicationContext
|
||||
import org.thoughtcrime.securesms.database.DatabaseFactory
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.TimeUnit
|
||||
@ -79,7 +79,7 @@ class BackgroundPollWorker(val context: Context, params: WorkerParameters) : Wor
|
||||
promises.addAll(privateChatsPromise.get())
|
||||
|
||||
// Closed groups
|
||||
promises.addAll(ApplicationContext.getInstance(context).closedGroupPoller.pollOnce())
|
||||
promises.addAll(ClosedGroupPoller().pollOnce())
|
||||
|
||||
// Open Groups
|
||||
val openGroups = DatabaseFactory.getLokiThreadDatabase(context).getAllPublicChats().map { (_,chat)->
|
||||
|
@ -8,7 +8,7 @@ import org.session.libsignal.libsignal.ecc.DjbECPrivateKey
|
||||
import org.session.libsignal.libsignal.ecc.DjbECPublicKey
|
||||
import org.session.libsignal.libsignal.ecc.ECKeyPair
|
||||
import org.session.libsignal.service.loki.Snode
|
||||
import org.session.libsignal.service.loki.database.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.utilities.PublicKeyValidation
|
||||
import org.session.libsignal.service.loki.utilities.removing05PrefixIfNeeded
|
||||
import org.session.libsignal.service.loki.utilities.toHexString
|
||||
|
@ -2,7 +2,6 @@ package org.thoughtcrime.securesms.loki.database
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import org.session.libsession.messaging.threads.Address
|
||||
import org.thoughtcrime.securesms.database.Database
|
||||
import org.thoughtcrime.securesms.database.DatabaseFactory
|
||||
import org.thoughtcrime.securesms.database.helpers.SQLCipherOpenHelper
|
||||
@ -10,7 +9,7 @@ import org.thoughtcrime.securesms.loki.utilities.get
|
||||
import org.thoughtcrime.securesms.loki.utilities.getInt
|
||||
import org.thoughtcrime.securesms.loki.utilities.getString
|
||||
import org.thoughtcrime.securesms.loki.utilities.insertOrUpdate
|
||||
import org.session.libsignal.service.loki.database.LokiMessageDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.LokiMessageDatabaseProtocol
|
||||
|
||||
class LokiMessageDatabase(context: Context, helper: SQLCipherOpenHelper) : Database(context, helper), LokiMessageDatabaseProtocol {
|
||||
|
||||
|
@ -11,7 +11,7 @@ import org.thoughtcrime.securesms.loki.utilities.get
|
||||
import org.thoughtcrime.securesms.loki.utilities.insertOrUpdate
|
||||
import org.session.libsession.messaging.threads.recipients.Recipient
|
||||
import org.session.libsession.utilities.TextSecurePreferences
|
||||
import org.session.libsignal.service.loki.database.LokiUserDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.LokiUserDatabaseProtocol
|
||||
|
||||
class LokiUserDatabase(context: Context, helper: SQLCipherOpenHelper) : Database(context, helper), LokiUserDatabaseProtocol {
|
||||
|
||||
|
@ -15,7 +15,7 @@ import kotlinx.android.synthetic.main.dialog_seed.view.*
|
||||
import network.loki.messenger.R
|
||||
import org.session.libsession.utilities.IdentityKeyUtil
|
||||
import org.thoughtcrime.securesms.loki.utilities.MnemonicUtilities
|
||||
import org.session.libsignal.service.loki.crypto.MnemonicCodec
|
||||
import org.session.libsignal.service.loki.MnemonicCodec
|
||||
import org.session.libsignal.service.loki.utilities.hexEncodedPrivateKey
|
||||
|
||||
|
||||
|
@ -7,19 +7,8 @@ import org.session.libsession.messaging.messages.Destination
|
||||
import org.session.libsession.messaging.messages.control.ConfigurationMessage
|
||||
import org.session.libsession.messaging.sending_receiving.MessageSender
|
||||
import org.session.libsession.messaging.threads.Address
|
||||
import org.session.libsession.messaging.threads.recipients.Recipient
|
||||
import org.session.libsession.utilities.TextSecurePreferences
|
||||
import org.session.libsession.utilities.preferences.ProfileKeyUtil
|
||||
import org.session.libsignal.service.internal.push.SignalServiceProtos
|
||||
import org.session.libsignal.service.internal.push.SignalServiceProtos.DataMessage
|
||||
import org.session.libsignal.service.loki.utilities.removing05PrefixIfNeeded
|
||||
import org.session.libsignal.utilities.Base64
|
||||
import org.session.libsignal.utilities.Hex
|
||||
import org.thoughtcrime.securesms.ApplicationContext
|
||||
import org.thoughtcrime.securesms.database.DatabaseFactory
|
||||
import org.thoughtcrime.securesms.jobs.RetrieveProfileAvatarJob
|
||||
import org.thoughtcrime.securesms.loki.utilities.ContactUtilities
|
||||
import org.thoughtcrime.securesms.loki.utilities.OpenGroupUtilities
|
||||
|
||||
object MultiDeviceProtocol {
|
||||
|
||||
@ -51,80 +40,4 @@ object MultiDeviceProtocol {
|
||||
TextSecurePreferences.setLastConfigurationSyncTime(context, System.currentTimeMillis())
|
||||
}
|
||||
|
||||
// TODO: remove this after we migrate to new message receiving pipeline
|
||||
@JvmStatic
|
||||
fun handleConfigurationMessage(context: Context, content: SignalServiceProtos.Content, senderPublicKey: String, timestamp: Long) {
|
||||
synchronized(this) {
|
||||
val userPublicKey = TextSecurePreferences.getLocalNumber(context) ?: return
|
||||
if (TextSecurePreferences.getConfigurationMessageSynced(context) && !TextSecurePreferences.shouldUpdateProfile(context, timestamp)) return
|
||||
if (senderPublicKey != userPublicKey) return
|
||||
TextSecurePreferences.setConfigurationMessageSynced(context, true)
|
||||
TextSecurePreferences.setLastProfileUpdateTime(context, timestamp)
|
||||
|
||||
val configurationMessage = ConfigurationMessage.fromProto(content) ?: return
|
||||
|
||||
val storage = MessagingModuleConfiguration.shared.storage
|
||||
val allClosedGroupPublicKeys = storage.getAllClosedGroupPublicKeys()
|
||||
|
||||
val threadDatabase = DatabaseFactory.getThreadDatabase(context)
|
||||
val recipientDatabase = DatabaseFactory.getRecipientDatabase(context)
|
||||
|
||||
val ourRecipient = Recipient.from(context, Address.fromSerialized(userPublicKey),false)
|
||||
|
||||
for (closedGroup in configurationMessage.closedGroups) {
|
||||
if (allClosedGroupPublicKeys.contains(closedGroup.publicKey)) continue
|
||||
|
||||
val closedGroupUpdate = DataMessage.ClosedGroupControlMessage.newBuilder()
|
||||
closedGroupUpdate.type = DataMessage.ClosedGroupControlMessage.Type.NEW
|
||||
closedGroupUpdate.publicKey = ByteString.copyFrom(Hex.fromStringCondensed(closedGroup.publicKey))
|
||||
closedGroupUpdate.name = closedGroup.name
|
||||
val encryptionKeyPair = SignalServiceProtos.KeyPair.newBuilder()
|
||||
encryptionKeyPair.publicKey = ByteString.copyFrom(closedGroup.encryptionKeyPair!!.publicKey.serialize().removing05PrefixIfNeeded())
|
||||
encryptionKeyPair.privateKey = ByteString.copyFrom(closedGroup.encryptionKeyPair!!.privateKey.serialize())
|
||||
closedGroupUpdate.encryptionKeyPair = encryptionKeyPair.build()
|
||||
closedGroupUpdate.addAllMembers(closedGroup.members.map { ByteString.copyFrom(Hex.fromStringCondensed(it)) })
|
||||
closedGroupUpdate.addAllAdmins(closedGroup.admins.map { ByteString.copyFrom(Hex.fromStringCondensed(it)) })
|
||||
|
||||
ClosedGroupsProtocolV2.handleNewClosedGroup(context, closedGroupUpdate.build(), userPublicKey, timestamp)
|
||||
}
|
||||
val allOpenGroups = storage.getAllOpenGroups().map { it.value.server }
|
||||
for (openGroup in configurationMessage.openGroups) {
|
||||
if (allOpenGroups.contains(openGroup)) continue
|
||||
OpenGroupUtilities.addGroup(context, openGroup, 1)
|
||||
}
|
||||
if (configurationMessage.displayName.isNotEmpty()) {
|
||||
TextSecurePreferences.setProfileName(context, configurationMessage.displayName)
|
||||
recipientDatabase.setProfileName(ourRecipient, configurationMessage.displayName)
|
||||
}
|
||||
if (configurationMessage.profileKey.isNotEmpty()) {
|
||||
val profileKey = Base64.encodeBytes(configurationMessage.profileKey)
|
||||
ProfileKeyUtil.setEncodedProfileKey(context, profileKey)
|
||||
recipientDatabase.setProfileKey(ourRecipient, configurationMessage.profileKey)
|
||||
if (!configurationMessage.profilePicture.isNullOrEmpty() && TextSecurePreferences.getProfilePictureURL(context) != configurationMessage.profilePicture) {
|
||||
TextSecurePreferences.setProfilePictureURL(context, configurationMessage.profilePicture)
|
||||
ApplicationContext.getInstance(context).jobManager.add(RetrieveProfileAvatarJob(ourRecipient, configurationMessage.profilePicture))
|
||||
}
|
||||
}
|
||||
for (contact in configurationMessage.contacts) {
|
||||
val address = Address.fromSerialized(contact.publicKey)
|
||||
val recipient = Recipient.from(context, address, true)
|
||||
if (!contact.profilePicture.isNullOrEmpty()) {
|
||||
recipientDatabase.setProfileAvatar(recipient, contact.profilePicture)
|
||||
}
|
||||
if (contact.profileKey?.isNotEmpty() == true) {
|
||||
recipientDatabase.setProfileKey(recipient, contact.profileKey)
|
||||
}
|
||||
if (contact.name.isNotEmpty()) {
|
||||
recipientDatabase.setProfileName(recipient, contact.name)
|
||||
}
|
||||
recipientDatabase.setProfileSharing(recipient, true)
|
||||
recipientDatabase.setRegistered(recipient, Recipient.RegisteredState.REGISTERED)
|
||||
// create Thread if needed
|
||||
threadDatabase.getOrCreateThreadIdFor(recipient)
|
||||
}
|
||||
if (configurationMessage.contacts.isNotEmpty()) {
|
||||
threadDatabase.notifyUpdatedFromConfig()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -3,8 +3,9 @@ package org.thoughtcrime.securesms.loki.utilities
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager
|
||||
import org.session.libsignal.service.loki.Broadcaster
|
||||
|
||||
class Broadcaster(private val context: Context) : org.session.libsignal.service.loki.utilities.Broadcaster {
|
||||
class Broadcaster(private val context: Context) : Broadcaster {
|
||||
|
||||
override fun broadcast(event: String) {
|
||||
val intent = Intent(event)
|
||||
|
@ -1,10 +1,6 @@
|
||||
package org.thoughtcrime.securesms.loki.utilities
|
||||
|
||||
import android.content.Context
|
||||
import org.session.libsignal.service.loki.crypto.MnemonicCodec
|
||||
import org.session.libsignal.service.loki.utilities.removing05PrefixIfNeeded
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
|
||||
object MnemonicUtilities {
|
||||
|
||||
|
@ -10,7 +10,7 @@ import android.widget.ListView
|
||||
import org.thoughtcrime.securesms.database.DatabaseFactory
|
||||
import org.thoughtcrime.securesms.loki.utilities.toPx
|
||||
import org.thoughtcrime.securesms.mms.GlideRequests
|
||||
import org.session.libsignal.service.loki.utilities.mentions.Mention
|
||||
import org.session.libsignal.service.loki.Mention
|
||||
|
||||
class MentionCandidateSelectionView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : ListView(context, attrs, defStyleAttr) {
|
||||
private var mentionCandidates = listOf<Mention>()
|
||||
|
@ -9,7 +9,7 @@ import android.widget.LinearLayout
|
||||
import kotlinx.android.synthetic.main.view_mention_candidate.view.*
|
||||
import network.loki.messenger.R
|
||||
import org.session.libsession.messaging.open_groups.OpenGroupAPI
|
||||
import org.session.libsignal.service.loki.utilities.mentions.Mention
|
||||
import org.session.libsignal.service.loki.Mention
|
||||
import org.thoughtcrime.securesms.mms.GlideRequests
|
||||
|
||||
class MentionCandidateView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : LinearLayout(context, attrs, defStyleAttr) {
|
||||
|
@ -146,13 +146,13 @@ class ProfilePictureView : RelativeLayout {
|
||||
private fun setProfilePictureIfNeeded(imageView: ImageView, publicKey: String, displayName: String?, @DimenRes sizeResId: Int) {
|
||||
if (publicKey.isNotEmpty()) {
|
||||
val recipient = Recipient.from(context, Address.fromSerialized(publicKey), false)
|
||||
if (imagesCached.contains(recipient.profileAvatar.orEmpty())) return
|
||||
if (imagesCached.contains(publicKey)) return
|
||||
val signalProfilePicture = recipient.contactPhoto
|
||||
if (signalProfilePicture != null && (signalProfilePicture as? ProfileContactPhoto)?.avatarObject != "0"
|
||||
&& (signalProfilePicture as? ProfileContactPhoto)?.avatarObject != "") {
|
||||
glide.clear(imageView)
|
||||
glide.load(signalProfilePicture).diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).circleCrop().into(imageView)
|
||||
imagesCached.add(recipient.profileAvatar.orEmpty())
|
||||
imagesCached.add(publicKey)
|
||||
} else {
|
||||
val sizeInPX = resources.getDimensionPixelSize(sizeResId)
|
||||
glide.clear(imageView)
|
||||
@ -162,7 +162,7 @@ class ProfilePictureView : RelativeLayout {
|
||||
publicKey,
|
||||
displayName
|
||||
)).diskCacheStrategy(DiskCacheStrategy.ALL).circleCrop().into(imageView)
|
||||
imagesCached.add(recipient.profileAvatar.orEmpty())
|
||||
imagesCached.add(publicKey)
|
||||
}
|
||||
} else {
|
||||
imageView.setImageDrawable(null)
|
||||
|
@ -108,8 +108,10 @@ interface StorageProtocol {
|
||||
fun createGroup(groupID: String, title: String?, members: List<Address>, avatar: SignalServiceAttachmentPointer?, relay: String?, admins: List<Address>, formationTimestamp: Long)
|
||||
fun isGroupActive(groupPublicKey: String): Boolean
|
||||
fun setActive(groupID: String, value: Boolean)
|
||||
fun getZombieMember(groupID: String): Set<String>
|
||||
fun removeMember(groupID: String, member: Address)
|
||||
fun updateMembers(groupID: String, members: List<Address>)
|
||||
fun updateZombieMembers(groupID: String, members: List<Address>)
|
||||
// Closed Group
|
||||
fun getAllClosedGroupPublicKeys(): Set<String>
|
||||
fun getAllActiveClosedGroupPublicKeys(): Set<String>
|
||||
|
@ -8,7 +8,7 @@ import org.session.libsession.snode.OnionRequestAPI
|
||||
import org.session.libsignal.utilities.logging.Log
|
||||
import org.session.libsignal.utilities.Base64
|
||||
import org.session.libsignal.utilities.JsonUtil
|
||||
import org.session.libsignal.service.loki.database.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.utilities.*
|
||||
import java.net.URL
|
||||
|
||||
|
@ -14,7 +14,7 @@ import org.session.libsignal.service.internal.crypto.PaddingInputStream
|
||||
import org.session.libsignal.service.internal.push.PushAttachmentData
|
||||
import org.session.libsignal.service.internal.push.http.AttachmentCipherOutputStreamFactory
|
||||
import org.session.libsignal.service.internal.util.Util
|
||||
import org.session.libsignal.service.loki.utilities.PlaintextOutputStreamFactory
|
||||
import org.session.libsignal.service.loki.PlaintextOutputStreamFactory
|
||||
import org.session.libsignal.utilities.logging.Log
|
||||
|
||||
class AttachmentUploadJob(val attachmentID: Long, val threadID: String, val message: Message, val messageSendJobID: String) : Job {
|
||||
|
@ -1,9 +1,9 @@
|
||||
package org.session.libsession.messaging.mentions
|
||||
|
||||
import org.session.libsession.messaging.MessagingModuleConfiguration
|
||||
import org.session.libsignal.service.loki.utilities.mentions.Mention
|
||||
import org.session.libsignal.service.loki.Mention
|
||||
|
||||
import org.session.libsignal.service.loki.database.LokiUserDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.LokiUserDatabaseProtocol
|
||||
|
||||
class MentionsManager(private val userPublicKey: String, private val userDatabase: LokiUserDatabaseProtocol) {
|
||||
var userPublicKeyCache = mutableMapOf<Long, Set<String>>() // Thread ID to set of user hex encoded public keys
|
||||
|
@ -145,7 +145,7 @@ class ClosedGroupControlMessage() : ControlMessage() {
|
||||
}
|
||||
is Kind.EncryptionKeyPair -> {
|
||||
closedGroupControlMessage.type = DataMessage.ClosedGroupControlMessage.Type.ENCRYPTION_KEY_PAIR
|
||||
closedGroupControlMessage.publicKey = kind.publicKey
|
||||
closedGroupControlMessage.publicKey = kind.publicKey ?: ByteString.EMPTY
|
||||
closedGroupControlMessage.addAllWrappers(kind.wrappers.map { it.toProto() })
|
||||
}
|
||||
is Kind.NameChange -> {
|
||||
|
@ -21,7 +21,6 @@ import java.util.*
|
||||
object OpenGroupAPI: DotNetAPI() {
|
||||
|
||||
private val moderators: HashMap<String, HashMap<Long, Set<String>>> = hashMapOf() // Server URL to (channel ID to set of moderator IDs)
|
||||
val sharedContext = Kovenant.createContext()
|
||||
|
||||
// region Settings
|
||||
private val fallbackBatchCount = 64
|
||||
@ -61,7 +60,7 @@ object OpenGroupAPI: DotNetAPI() {
|
||||
parameters["count"] = fallbackBatchCount
|
||||
parameters["include_deleted"] = 0
|
||||
}
|
||||
return execute(HTTPVerb.GET, server, "channels/$channel/messages", parameters = parameters).then(sharedContext) { json ->
|
||||
return execute(HTTPVerb.GET, server, "channels/$channel/messages", parameters = parameters).then { json ->
|
||||
try {
|
||||
val data = json["data"] as List<Map<*, *>>
|
||||
val messages = data.mapNotNull { message ->
|
||||
@ -166,7 +165,7 @@ object OpenGroupAPI: DotNetAPI() {
|
||||
} else {
|
||||
parameters["count"] = fallbackBatchCount
|
||||
}
|
||||
return execute(HTTPVerb.GET, server, "loki/v1/channel/$channel/deletes", parameters = parameters).then(sharedContext) { json ->
|
||||
return execute(HTTPVerb.GET, server, "loki/v1/channel/$channel/deletes", parameters = parameters).then { json ->
|
||||
try {
|
||||
val deletedMessageServerIDs = (json["data"] as List<Map<*, *>>).mapNotNull { deletion ->
|
||||
try {
|
||||
@ -202,7 +201,7 @@ object OpenGroupAPI: DotNetAPI() {
|
||||
retryIfNeeded(maxRetryCount) {
|
||||
Log.d("Loki", "Sending message to open group with ID: $channel on server: $server.")
|
||||
val parameters = signedMessage.toJSON()
|
||||
execute(HTTPVerb.POST, server, "channels/$channel/messages", parameters = parameters).then(sharedContext) { json ->
|
||||
execute(HTTPVerb.POST, server, "channels/$channel/messages", parameters = parameters).then { json ->
|
||||
try {
|
||||
val data = json["data"] as Map<*, *>
|
||||
val serverID = (data["id"] as? Long) ?: (data["id"] as? Int)?.toLong() ?: (data["id"] as String).toLong()
|
||||
@ -255,7 +254,7 @@ object OpenGroupAPI: DotNetAPI() {
|
||||
|
||||
@JvmStatic
|
||||
fun getModerators(channel: Long, server: String): Promise<Set<String>, Exception> {
|
||||
return execute(HTTPVerb.GET, server, "loki/v1/channel/$channel/get_moderators").then(sharedContext) { json ->
|
||||
return execute(HTTPVerb.GET, server, "loki/v1/channel/$channel/get_moderators").then { json ->
|
||||
try {
|
||||
@Suppress("UNCHECKED_CAST") val moderators = json["moderators"] as? List<String>
|
||||
val moderatorsAsSet = moderators.orEmpty().toSet()
|
||||
@ -276,7 +275,7 @@ object OpenGroupAPI: DotNetAPI() {
|
||||
fun getChannelInfo(channel: Long, server: String): Promise<OpenGroupInfo, Exception> {
|
||||
return retryIfNeeded(maxRetryCount) {
|
||||
val parameters = mapOf( "include_annotations" to 1 )
|
||||
execute(HTTPVerb.GET, server, "/channels/$channel", parameters = parameters).then(sharedContext) { json ->
|
||||
execute(HTTPVerb.GET, server, "/channels/$channel", parameters = parameters).then { json ->
|
||||
try {
|
||||
val data = json["data"] as Map<*, *>
|
||||
val annotations = data["annotations"] as List<Map<*, *>>
|
||||
@ -357,7 +356,7 @@ object OpenGroupAPI: DotNetAPI() {
|
||||
|
||||
@JvmStatic
|
||||
fun getDisplayNames(publicKeys: Set<String>, server: String): Promise<Map<String, String>, Exception> {
|
||||
return getUserProfiles(publicKeys, server, false).map(sharedContext) { json ->
|
||||
return getUserProfiles(publicKeys, server, false).map { json ->
|
||||
val mapping = mutableMapOf<String, String>()
|
||||
for (user in json) {
|
||||
if (user["username"] != null) {
|
||||
|
@ -169,15 +169,24 @@ fun MessageSender.removeMembers(groupPublicKey: String, membersToRemove: List<St
|
||||
Log.d("Loki", "Invalid closed group update.")
|
||||
throw Error.InvalidClosedGroupUpdate
|
||||
}
|
||||
val updatedMembers = group.members.map { it.serialize() }.toSet() - membersToRemove
|
||||
// Save the new group members
|
||||
storage.updateMembers(groupID, updatedMembers.map { Address.fromSerialized(it) })
|
||||
val removeMembersAsData = membersToRemove.map { ByteString.copyFrom(Hex.fromStringCondensed(it)) }
|
||||
val admins = group.admins.map { it.serialize() }
|
||||
if (!admins.contains(userPublicKey)) {
|
||||
Log.d("Loki", "Only an admin can remove members from a group.")
|
||||
throw Error.InvalidClosedGroupUpdate
|
||||
}
|
||||
val updatedMembers = group.members.map { it.serialize() }.toSet() - membersToRemove
|
||||
if (membersToRemove.any { it in admins } && updatedMembers.isNotEmpty()) {
|
||||
Log.d("Loki", "Can't remove admin from closed group unless the group is destroyed entirely.")
|
||||
throw Error.InvalidClosedGroupUpdate
|
||||
}
|
||||
|
||||
// Save the new group members
|
||||
storage.updateMembers(groupID, updatedMembers.map { Address.fromSerialized(it) })
|
||||
// Update the zombie list
|
||||
val oldZombies = storage.getZombieMember(groupID)
|
||||
storage.updateZombieMembers(groupID, oldZombies.minus(membersToRemove).map { Address.fromSerialized(it) })
|
||||
|
||||
val removeMembersAsData = membersToRemove.map { ByteString.copyFrom(Hex.fromStringCondensed(it)) }
|
||||
val name = group.title
|
||||
// Send the update to the group
|
||||
val memberUpdateKind = ClosedGroupControlMessage.Kind.MembersRemoved(removeMembersAsData)
|
||||
@ -185,14 +194,21 @@ fun MessageSender.removeMembers(groupPublicKey: String, membersToRemove: List<St
|
||||
val closedGroupControlMessage = ClosedGroupControlMessage(memberUpdateKind)
|
||||
closedGroupControlMessage.sentTimestamp = sentTime
|
||||
send(closedGroupControlMessage, Address.fromSerialized(groupID))
|
||||
val isCurrentUserAdmin = admins.contains(userPublicKey)
|
||||
if (isCurrentUserAdmin) {
|
||||
|
||||
// Send the new encryption key pair to the remaining group members
|
||||
// At this stage we know the user is admin, no need to test
|
||||
generateAndSendNewEncryptionKeyPair(groupPublicKey, updatedMembers)
|
||||
}
|
||||
// Notify the user
|
||||
|
||||
// Insert an outgoing notification
|
||||
// we don't display zombie members in the notification as users have already been notified when those members left
|
||||
val notificationMembers = membersToRemove.minus(oldZombies)
|
||||
if (notificationMembers.isNotEmpty()) {
|
||||
// no notification to display when only zombies have been removed
|
||||
val infoType = SignalServiceGroup.Type.MEMBER_REMOVED
|
||||
val threadID = storage.getOrCreateThreadIdFor(Address.fromSerialized(groupID))
|
||||
storage.insertOutgoingInfoMessage(context, groupID, infoType, name, membersToRemove, admins, threadID, sentTime)
|
||||
storage.insertOutgoingInfoMessage(context, groupID, infoType, name, notificationMembers, admins, threadID, sentTime)
|
||||
}
|
||||
}
|
||||
|
||||
fun MessageSender.leave(groupPublicKey: String, notifyUser: Boolean = true): Promise<Unit, Exception> {
|
||||
|
@ -111,7 +111,7 @@ private fun MessageReceiver.handleDataExtractionNotification(message: DataExtrac
|
||||
|
||||
// Configuration message handling
|
||||
|
||||
private fun MessageReceiver.handleConfigurationMessage(message: ConfigurationMessage) {
|
||||
private fun handleConfigurationMessage(message: ConfigurationMessage) {
|
||||
val context = MessagingModuleConfiguration.shared.context
|
||||
val storage = MessagingModuleConfiguration.shared.storage
|
||||
if (TextSecurePreferences.getConfigurationMessageSynced(context) && !TextSecurePreferences.shouldUpdateProfile(context, message.sentTimestamp!!)) return
|
||||
@ -148,30 +148,28 @@ private fun MessageReceiver.handleConfigurationMessage(message: ConfigurationMes
|
||||
fun MessageReceiver.handleVisibleMessage(message: VisibleMessage, proto: SignalServiceProtos.Content, openGroupID: String?) {
|
||||
val storage = MessagingModuleConfiguration.shared.storage
|
||||
val context = MessagingModuleConfiguration.shared.context
|
||||
val userPublicKey = storage.getUserPublicKey()
|
||||
// Update profile if needed
|
||||
val newProfile = message.profile
|
||||
if (newProfile != null) {
|
||||
if (newProfile != null && openGroupID.isNullOrEmpty() && userPublicKey != message.sender) {
|
||||
val profileManager = SSKEnvironment.shared.profileManager
|
||||
val recipient = Recipient.from(context, Address.fromSerialized(message.sender!!), false)
|
||||
val displayName = newProfile.displayName!!
|
||||
val userPublicKey = storage.getUserPublicKey()
|
||||
if (openGroupID == null) {
|
||||
if (userPublicKey == message.sender) {
|
||||
// Update the user's local name if the message came from their master device
|
||||
TextSecurePreferences.setProfileName(context, displayName)
|
||||
}
|
||||
if (displayName.isNotEmpty()) {
|
||||
profileManager.setDisplayName(context, recipient, displayName)
|
||||
}
|
||||
if (recipient.profileKey == null || !MessageDigest.isEqual(recipient.profileKey, newProfile.profileKey)) {
|
||||
if (newProfile.profileKey?.isNotEmpty() == true && !MessageDigest.isEqual(recipient.profileKey, newProfile.profileKey)) {
|
||||
profileManager.setProfileKey(context, recipient, newProfile.profileKey!!)
|
||||
profileManager.setUnidentifiedAccessMode(context, recipient, Recipient.UnidentifiedAccessMode.UNKNOWN)
|
||||
val url = newProfile.profilePictureURL.orEmpty()
|
||||
profileManager.setProfilePictureURL(context, recipient, url)
|
||||
val newUrl = newProfile.profilePictureURL
|
||||
if (!newUrl.isNullOrEmpty()) {
|
||||
profileManager.setProfilePictureURL(context, recipient, newUrl)
|
||||
if (userPublicKey == message.sender) {
|
||||
profileManager.updateOpenGroupProfilePicturesIfNeeded(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Get or create thread
|
||||
val threadID = storage.getOrCreateThreadIdFor(message.syncTarget
|
||||
?: message.sender!!, message.groupPublicKey, openGroupID)
|
||||
@ -286,7 +284,8 @@ private fun MessageReceiver.handleClosedGroupEncryptionKeyPair(message: ClosedGr
|
||||
val storage = MessagingModuleConfiguration.shared.storage
|
||||
val senderPublicKey = message.sender ?: return
|
||||
val kind = message.kind!! as? ClosedGroupControlMessage.Kind.EncryptionKeyPair ?: return
|
||||
val groupPublicKey = kind.publicKey?.toByteArray()?.toHexString() ?: message.groupPublicKey ?: return
|
||||
var groupPublicKey = kind.publicKey?.toByteArray()?.toHexString()
|
||||
if (groupPublicKey.isNullOrEmpty()) groupPublicKey = message.groupPublicKey ?: return
|
||||
val userPublicKey = storage.getUserPublicKey()!!
|
||||
val userKeyPair = storage.getUserX25519KeyPair()
|
||||
// Unwrap the message
|
||||
@ -300,7 +299,7 @@ private fun MessageReceiver.handleClosedGroupEncryptionKeyPair(message: ClosedGr
|
||||
return
|
||||
}
|
||||
if (!group.admins.map { it.toString() }.contains(senderPublicKey)) {
|
||||
Log.d("Loki", "Ignoring closed group encryption key pair from non-member.")
|
||||
Log.d("Loki", "Ignoring closed group encryption key pair from non-admin.")
|
||||
return
|
||||
}
|
||||
// Find our wrapper and decrypt it if possible
|
||||
@ -381,6 +380,7 @@ private fun MessageReceiver.handleClosedGroupMembersAdded(message: ClosedGroupCo
|
||||
val updateMembers = kind.members.map { it.toByteArray().toHexString() }
|
||||
val newMembers = members + updateMembers
|
||||
storage.updateMembers(groupID, newMembers.map { Address.fromSerialized(it) })
|
||||
|
||||
// Notify the user
|
||||
if (userPublicKey == senderPublicKey) {
|
||||
// sender is a linked device
|
||||
@ -403,6 +403,11 @@ private fun MessageReceiver.handleClosedGroupMembersAdded(message: ClosedGroupCo
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the given members from the group IF
|
||||
/// • it wasn't the admin that was removed (that should happen through a `MEMBER_LEFT` message).
|
||||
/// • the admin sent the message (only the admin can truly remove members).
|
||||
/// If we're among the users that were removed, delete all encryption key pairs and the group public key, unsubscribe
|
||||
/// from push notifications for this closed group, and remove the given members from the zombie list for this group.
|
||||
private fun MessageReceiver.handleClosedGroupMembersRemoved(message: ClosedGroupControlMessage) {
|
||||
val context = MessagingModuleConfiguration.shared.context
|
||||
val storage = MessagingModuleConfiguration.shared.storage
|
||||
@ -416,7 +421,7 @@ private fun MessageReceiver.handleClosedGroupMembersRemoved(message: ClosedGroup
|
||||
return
|
||||
}
|
||||
if (!group.isActive) {
|
||||
Log.d("Loki", "Ignoring closed group info message for inactive group")
|
||||
Log.d("Loki", "Ignoring closed group info message for inactive group.")
|
||||
return
|
||||
}
|
||||
val name = group.title
|
||||
@ -427,6 +432,18 @@ private fun MessageReceiver.handleClosedGroupMembersRemoved(message: ClosedGroup
|
||||
// Users that are part of this remove update
|
||||
val updateMembers = kind.members.map { it.toByteArray().toHexString() }
|
||||
|
||||
// Check that the admin wasn't removed
|
||||
if (updateMembers.contains(admins.first())) {
|
||||
Log.d("Loki", "Ignoring invalid closed group update.")
|
||||
return
|
||||
}
|
||||
|
||||
// Check that the message was sent by the group admin
|
||||
if (!admins.contains(senderPublicKey)) {
|
||||
Log.d("Loki", "Ignoring invalid closed group update.")
|
||||
return
|
||||
}
|
||||
|
||||
if (!isValidGroupUpdate(group, message.sentTimestamp!!, senderPublicKey)) { return }
|
||||
// If admin leaves the group is disbanded
|
||||
val didAdminLeave = admins.any { it in updateMembers }
|
||||
@ -443,25 +460,34 @@ private fun MessageReceiver.handleClosedGroupMembersRemoved(message: ClosedGroup
|
||||
if (didAdminLeave || wasCurrentUserRemoved) {
|
||||
disableLocalGroupAndUnsubscribe(groupPublicKey, groupID, userPublicKey)
|
||||
} else {
|
||||
val isCurrentUserAdmin = admins.contains(userPublicKey)
|
||||
storage.updateMembers(groupID, newMembers.map { Address.fromSerialized(it) })
|
||||
if (isCurrentUserAdmin) {
|
||||
MessageSender.generateAndSendNewEncryptionKeyPair(groupPublicKey, newMembers)
|
||||
}
|
||||
}
|
||||
// update zombie members
|
||||
val zombies = storage.getZombieMember(groupID)
|
||||
storage.updateZombieMembers(groupID, zombies.minus(updateMembers).map { Address.fromSerialized(it) })
|
||||
|
||||
val type = if (senderLeft) SignalServiceGroup.Type.QUIT
|
||||
else SignalServiceGroup.Type.MEMBER_REMOVED
|
||||
|
||||
// Notify the user
|
||||
// we don't display zombie members in the notification as users have already been notified when those members left
|
||||
val notificationMembers = updateMembers.minus(zombies)
|
||||
if (notificationMembers.isNotEmpty()) {
|
||||
// no notification to display when only zombies have been removed
|
||||
if (userPublicKey == senderPublicKey) {
|
||||
// sender is a linked device
|
||||
val threadID = storage.getOrCreateThreadIdFor(Address.fromSerialized(groupID))
|
||||
storage.insertOutgoingInfoMessage(context, groupID, type, name, updateMembers, admins, threadID, message.sentTimestamp!!)
|
||||
storage.insertOutgoingInfoMessage(context, groupID, type, name, notificationMembers, admins, threadID, message.sentTimestamp!!)
|
||||
} else {
|
||||
storage.insertIncomingInfoMessage(context, senderPublicKey, groupID, type, name, updateMembers, admins, message.sentTimestamp!!)
|
||||
storage.insertIncomingInfoMessage(context, senderPublicKey, groupID, type, name, notificationMembers, admins, message.sentTimestamp!!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// If a regular member left:
|
||||
/// • Mark them as a zombie (to be removed by the admin later).
|
||||
/// If the admin left:
|
||||
/// • Unsubscribe from PNs, delete the group public key, etc. as the group will be disbanded.
|
||||
private fun MessageReceiver.handleClosedGroupMemberLeft(message: ClosedGroupControlMessage) {
|
||||
val context = MessagingModuleConfiguration.shared.context
|
||||
val storage = MessagingModuleConfiguration.shared.storage
|
||||
@ -494,11 +520,10 @@ private fun MessageReceiver.handleClosedGroupMemberLeft(message: ClosedGroupCont
|
||||
// admin left the group of linked device left the group
|
||||
disableLocalGroupAndUnsubscribe(groupPublicKey, groupID, userPublicKey)
|
||||
} else {
|
||||
val isCurrentUserAdmin = admins.contains(userPublicKey)
|
||||
storage.updateMembers(groupID, updatedMemberList.map { Address.fromSerialized(it) })
|
||||
if (isCurrentUserAdmin) {
|
||||
MessageSender.generateAndSendNewEncryptionKeyPair(groupPublicKey, updatedMemberList)
|
||||
}
|
||||
// update zombie members
|
||||
val zombies = storage.getZombieMember(groupID)
|
||||
storage.updateZombieMembers(groupID, zombies.plus(senderPublicKey).map { Address.fromSerialized(it) })
|
||||
}
|
||||
// Notify the user
|
||||
if (userLeft) {
|
||||
|
@ -23,7 +23,7 @@ import org.session.libsignal.service.internal.push.http.DigestingRequestBody
|
||||
import org.session.libsignal.service.internal.push.http.ProfileCipherOutputStreamFactory
|
||||
import org.session.libsignal.utilities.Hex
|
||||
import org.session.libsignal.utilities.JsonUtil
|
||||
import org.session.libsignal.service.loki.api.utilities.HTTP
|
||||
import org.session.libsignal.service.loki.HTTP
|
||||
import org.session.libsignal.service.loki.utilities.*
|
||||
import org.session.libsignal.utilities.*
|
||||
import org.session.libsignal.utilities.Base64
|
||||
|
@ -12,12 +12,14 @@ import org.session.libsignal.utilities.logging.Log
|
||||
import org.session.libsignal.utilities.Base64
|
||||
import org.session.libsignal.utilities.*
|
||||
import org.session.libsignal.service.loki.Snode
|
||||
import org.session.libsignal.service.loki.api.utilities.*
|
||||
import org.session.libsignal.service.loki.*
|
||||
import org.session.libsession.utilities.AESGCM.EncryptionResult
|
||||
import org.session.libsignal.utilities.ThreadUtils
|
||||
import org.session.libsession.utilities.getBodyForOnionRequest
|
||||
import org.session.libsession.utilities.getHeadersForOnionRequest
|
||||
import org.session.libsignal.service.loki.database.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.Broadcaster
|
||||
import org.session.libsignal.service.loki.HTTP
|
||||
import org.session.libsignal.service.loki.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.utilities.*
|
||||
|
||||
private typealias Path = List<Snode>
|
||||
|
@ -10,9 +10,9 @@ import org.session.libsession.messaging.utilities.MessageWrapper
|
||||
import org.session.libsession.snode.utilities.getRandomElement
|
||||
import org.session.libsignal.service.internal.push.SignalServiceProtos
|
||||
import org.session.libsignal.service.loki.Snode
|
||||
import org.session.libsignal.service.loki.api.utilities.HTTP
|
||||
import org.session.libsignal.service.loki.database.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.utilities.Broadcaster
|
||||
import org.session.libsignal.service.loki.HTTP
|
||||
import org.session.libsignal.service.loki.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.Broadcaster
|
||||
import org.session.libsignal.service.loki.utilities.prettifiedDescription
|
||||
import org.session.libsignal.service.loki.utilities.removing05PrefixIfNeeded
|
||||
import org.session.libsignal.service.loki.utilities.retryIfNeeded
|
||||
|
@ -1,7 +1,7 @@
|
||||
package org.session.libsession.snode
|
||||
|
||||
import org.session.libsignal.service.loki.database.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.utilities.Broadcaster
|
||||
import org.session.libsignal.service.loki.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.Broadcaster
|
||||
|
||||
class SnodeModule(val storage: LokiAPIDatabaseProtocol, val broadcaster: Broadcaster) {
|
||||
|
||||
|
@ -22,7 +22,6 @@ import org.session.libsignal.service.api.messages.SignalServiceEnvelope;
|
||||
import org.session.libsignal.service.api.messages.SignalServiceGroup;
|
||||
import org.session.libsignal.service.api.messages.SignalServiceReceiptMessage;
|
||||
import org.session.libsignal.service.api.messages.SignalServiceTypingMessage;
|
||||
import org.session.libsignal.service.api.messages.shared.SharedContact;
|
||||
import org.session.libsignal.service.api.push.SignalServiceAddress;
|
||||
import org.session.libsignal.service.internal.push.PushTransportDetails;
|
||||
import org.session.libsignal.service.internal.push.SignalServiceProtos;
|
||||
@ -34,7 +33,7 @@ import org.session.libsignal.service.internal.push.SignalServiceProtos.ReceiptMe
|
||||
import org.session.libsignal.service.internal.push.SignalServiceProtos.TypingMessage;
|
||||
import org.session.libsignal.service.loki.api.crypto.SessionProtocol;
|
||||
import org.session.libsignal.service.loki.api.crypto.SessionProtocolUtilities;
|
||||
import org.session.libsignal.service.loki.database.LokiAPIDatabaseProtocol;
|
||||
import org.session.libsignal.service.loki.LokiAPIDatabaseProtocol;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
|
@ -1,6 +1,5 @@
|
||||
package org.session.libsignal.service.api.messages.shared;
|
||||
|
||||
|
||||
import org.session.libsignal.libsignal.util.guava.Optional;
|
||||
import org.session.libsignal.service.api.messages.SignalServiceAttachment;
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
package org.session.libsignal.service.loki.utilities
|
||||
package org.session.libsignal.service.loki
|
||||
|
||||
interface Broadcaster {
|
||||
|
@ -1,4 +1,4 @@
|
||||
package org.session.libsignal.service.loki.api.utilities
|
||||
package org.session.libsignal.service.loki
|
||||
|
||||
import okhttp3.*
|
||||
import org.session.libsignal.utilities.logging.Log
|
@ -1,4 +1,4 @@
|
||||
package org.session.libsignal.service.loki.database
|
||||
package org.session.libsignal.service.loki
|
||||
|
||||
import org.session.libsignal.libsignal.ecc.ECKeyPair
|
||||
import org.session.libsignal.service.loki.Snode
|
@ -1,4 +1,4 @@
|
||||
package org.session.libsignal.service.loki.database
|
||||
package org.session.libsignal.service.loki
|
||||
|
||||
interface LokiMessageDatabaseProtocol {
|
||||
|
@ -1,4 +1,4 @@
|
||||
package org.session.libsignal.service.loki.database
|
||||
package org.session.libsignal.service.loki
|
||||
|
||||
interface LokiOpenGroupDatabaseProtocol {
|
||||
|
@ -1,4 +1,4 @@
|
||||
package org.session.libsignal.service.loki.database
|
||||
package org.session.libsignal.service.loki
|
||||
|
||||
interface LokiUserDatabaseProtocol {
|
||||
|
@ -1,3 +1,3 @@
|
||||
package org.session.libsignal.service.loki.utilities.mentions
|
||||
package org.session.libsignal.service.loki
|
||||
|
||||
data class Mention(val publicKey: String, val displayName: String)
|
@ -1,6 +1,5 @@
|
||||
package org.session.libsignal.service.loki.crypto
|
||||
package org.session.libsignal.service.loki
|
||||
|
||||
import java.io.File
|
||||
import java.util.zip.CRC32
|
||||
|
||||
/**
|
||||
@ -95,8 +94,10 @@ class MnemonicCodec(private val loadFileContents: (String) -> String) {
|
||||
var result = ""
|
||||
val n = truncatedWordSet.size.toLong()
|
||||
// Check preconditions
|
||||
if (words.size < 12) { throw DecodingError.InputTooShort }
|
||||
if (words.size % 3 == 0) { throw DecodingError.MissingLastWord }
|
||||
if (words.size < 12) { throw DecodingError.InputTooShort
|
||||
}
|
||||
if (words.size % 3 == 0) { throw DecodingError.MissingLastWord
|
||||
}
|
||||
// Get checksum word
|
||||
val checksumWord = words.removeAt(words.lastIndex)
|
||||
// Decode
|
||||
@ -106,7 +107,8 @@ class MnemonicCodec(private val loadFileContents: (String) -> String) {
|
||||
val w2 = truncatedWordSet.indexOf(words[chunkStartIndex + 1].substring(0 until prefixLength))
|
||||
val w3 = truncatedWordSet.indexOf(words[chunkStartIndex + 2].substring(0 until prefixLength))
|
||||
val x = w1 + n * ((n - w1 + w2) % n) + n * n * ((n - w2 + w3) % n)
|
||||
if (x % n != w1.toLong()) { throw DecodingError.Generic }
|
||||
if (x % n != w1.toLong()) { throw DecodingError.Generic
|
||||
}
|
||||
val string = "0000000" + x.toString(16)
|
||||
result += swap(string.substring(string.length - 8 until string.length))
|
||||
} catch (e: Exception) {
|
||||
@ -116,7 +118,8 @@ class MnemonicCodec(private val loadFileContents: (String) -> String) {
|
||||
// Verify checksum
|
||||
val checksumIndex = determineChecksumIndex(words, prefixLength)
|
||||
val expectedChecksumWord = words[checksumIndex]
|
||||
if (expectedChecksumWord.substring(0 until prefixLength) != checksumWord.substring(0 until prefixLength)) { throw DecodingError.VerificationFailed }
|
||||
if (expectedChecksumWord.substring(0 until prefixLength) != checksumWord.substring(0 until prefixLength)) { throw DecodingError.VerificationFailed
|
||||
}
|
||||
// Return
|
||||
return result
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package org.session.libsignal.service.loki.utilities
|
||||
package org.session.libsignal.service.loki
|
||||
|
||||
import org.session.libsignal.service.api.crypto.DigestingOutputStream
|
||||
import org.session.libsignal.service.internal.push.http.OutputStreamFactory
|
@ -1,7 +1,7 @@
|
||||
package org.session.libsignal.service.loki.api.crypto
|
||||
|
||||
import org.session.libsignal.libsignal.ecc.ECKeyPair
|
||||
import org.session.libsignal.service.loki.database.LokiAPIDatabaseProtocol
|
||||
import org.session.libsignal.service.loki.LokiAPIDatabaseProtocol
|
||||
|
||||
interface SessionProtocol {
|
||||
|
@ -1,4 +1,4 @@
|
||||
package org.session.libsignal.service.loki.api
|
||||
package org.session.libsignal.service.loki
|
||||
|
||||
import org.session.libsignal.service.internal.push.SignalServiceProtos
|
||||
|
@ -1,49 +0,0 @@
|
||||
package org.session.libsignal.service.loki.api.utilities
|
||||
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.Request
|
||||
import okio.Buffer
|
||||
import org.session.libsignal.utilities.Base64
|
||||
import java.io.IOException
|
||||
import java.util.*
|
||||
|
||||
internal fun Request.getHeadersForOnionRequest(): Map<String, Any> {
|
||||
val result = mutableMapOf<String, Any>()
|
||||
val contentType = body()?.contentType()
|
||||
if (contentType != null) {
|
||||
result["content-type"] = contentType.toString()
|
||||
}
|
||||
val headers = headers()
|
||||
for (name in headers.names()) {
|
||||
val value = headers.get(name)
|
||||
if (value != null) {
|
||||
if (value.toLowerCase(Locale.US) == "true" || value.toLowerCase(Locale.US) == "false") {
|
||||
result[name] = value.toBoolean()
|
||||
} else if (value.toIntOrNull() != null) {
|
||||
result[name] = value.toInt()
|
||||
} else {
|
||||
result[name] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
internal fun Request.getBodyForOnionRequest(): Any? {
|
||||
try {
|
||||
val copyOfThis = newBuilder().build()
|
||||
val buffer = Buffer()
|
||||
val body = copyOfThis.body() ?: return null
|
||||
body.writeTo(buffer)
|
||||
val bodyAsData = buffer.readByteArray()
|
||||
if (body is MultipartBody) {
|
||||
val base64EncodedBody: String = Base64.encodeBytes(bodyAsData)
|
||||
return mapOf( "fileUpload" to base64EncodedBody )
|
||||
} else {
|
||||
val charset = body.contentType()?.charset() ?: Charsets.UTF_8
|
||||
return bodyAsData?.toString(charset)
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
return null
|
||||
}
|
||||
}
|
@ -67,32 +67,11 @@ public class JsonUtil {
|
||||
}
|
||||
}
|
||||
|
||||
public static class IdentityKeySerializer extends JsonSerializer<IdentityKey> {
|
||||
@Override
|
||||
public void serialize(IdentityKey value, JsonGenerator gen, SerializerProvider serializers)
|
||||
throws IOException
|
||||
{
|
||||
gen.writeString(Base64.encodeBytesWithoutPadding(value.serialize()));
|
||||
}
|
||||
}
|
||||
|
||||
public static class IdentityKeyDeserializer extends JsonDeserializer<IdentityKey> {
|
||||
@Override
|
||||
public IdentityKey deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||
try {
|
||||
return new IdentityKey(Base64.decodeWithoutPadding(p.getValueAsString()), 0);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static ObjectMapper getMapper() {
|
||||
return objectMapper;
|
||||
}
|
||||
|
||||
public static class SaneJSONObject {
|
||||
|
||||
private final JSONObject delegate;
|
||||
|
||||
public SaneJSONObject(JSONObject delegate) {
|
||||
|
@ -1,25 +1,11 @@
|
||||
@file:JvmName("PromiseUtilities")
|
||||
package org.session.libsignal.utilities
|
||||
|
||||
import nl.komponents.kovenant.Context
|
||||
import nl.komponents.kovenant.Kovenant
|
||||
import nl.komponents.kovenant.Promise
|
||||
import nl.komponents.kovenant.deferred
|
||||
import nl.komponents.kovenant.jvm.asDispatcher
|
||||
import org.session.libsignal.utilities.logging.Log
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeoutException
|
||||
|
||||
fun Kovenant.createContext(): Context {
|
||||
return createContext {
|
||||
callbackContext.dispatcher = Executors.newSingleThreadExecutor().asDispatcher()
|
||||
workerContext.dispatcher = ThreadUtils.executorPool.asDispatcher()
|
||||
multipleCompletion = { v1, v2 ->
|
||||
Log.d("Loki", "Promise resolved more than once (first with $v1, then with $v2); ignoring $v2.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun <V, E : Throwable> Promise<V, E>.get(defaultValue: V): V {
|
||||
return try {
|
||||
get()
|
||||
|
@ -3,7 +3,6 @@ package org.session.libsignal.utilities
|
||||
import java.util.concurrent.*
|
||||
|
||||
object ThreadUtils {
|
||||
|
||||
val executorPool = Executors.newCachedThreadPool()
|
||||
|
||||
@JvmStatic
|
||||
@ -17,10 +16,8 @@ object ThreadUtils {
|
||||
|
||||
@JvmStatic
|
||||
fun newDynamicSingleThreadedExecutor(): ExecutorService {
|
||||
val executor = ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
|
||||
LinkedBlockingQueue())
|
||||
val executor = ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, LinkedBlockingQueue())
|
||||
executor.allowCoreThreadTimeOut(true)
|
||||
return executor
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user