2012-09-08 05:03:23 +02:00
/ * *
2011-12-20 19:20:44 +01:00
* Copyright ( C ) 2011 Whisper Systems
2012-09-08 05:03:23 +02:00
*
2011-12-20 19:20:44 +01:00
* This program is free software : you can redistribute it and / or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
2012-09-08 05:03:23 +02:00
*
2011-12-20 19:20:44 +01:00
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < http : //www.gnu.org/licenses/>.
* /
package org.thoughtcrime.securesms.database ;
2012-09-08 05:03:23 +02:00
import android.content.ContentValues ;
import android.content.Context ;
import android.database.Cursor ;
2014-11-12 20:15:05 +01:00
import android.text.TextUtils ;
2011-12-20 19:20:44 +01:00
2020-02-19 23:08:34 +01:00
import androidx.annotation.NonNull ;
import androidx.annotation.Nullable ;
2019-01-15 09:41:05 +01:00
import com.annimon.stream.Collectors ;
2017-09-30 17:45:45 +02:00
import com.annimon.stream.Stream ;
2017-05-09 00:32:59 +02:00
import com.google.android.mms.pdu_alt.NotificationInd ;
import com.google.android.mms.pdu_alt.PduHeaders ;
2014-03-07 22:05:35 +01:00
2018-01-25 04:17:44 +01:00
import net.sqlcipher.database.SQLiteDatabase ;
2020-08-20 22:50:14 +02:00
import net.sqlcipher.database.SQLiteStatement ;
2018-01-25 04:17:44 +01:00
2018-04-27 02:03:54 +02:00
import org.json.JSONArray ;
import org.json.JSONException ;
import org.json.JSONObject ;
2015-10-13 03:25:05 +02:00
import org.thoughtcrime.securesms.attachments.Attachment ;
2018-04-27 02:03:54 +02:00
import org.thoughtcrime.securesms.attachments.AttachmentId ;
2015-10-13 03:25:05 +02:00
import org.thoughtcrime.securesms.attachments.DatabaseAttachment ;
2017-01-21 00:26:17 +01:00
import org.thoughtcrime.securesms.attachments.MmsNotificationAttachment ;
2018-04-27 02:03:54 +02:00
import org.thoughtcrime.securesms.contactshare.Contact ;
2015-01-15 22:35:35 +01:00
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatch ;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatchList ;
2015-10-13 03:25:05 +02:00
import org.thoughtcrime.securesms.database.documents.NetworkFailure ;
import org.thoughtcrime.securesms.database.documents.NetworkFailureList ;
2018-01-25 04:17:44 +01:00
import org.thoughtcrime.securesms.database.helpers.SQLCipherOpenHelper ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord ;
2020-08-05 22:45:52 +02:00
import org.thoughtcrime.securesms.database.model.Mention ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
import org.thoughtcrime.securesms.database.model.MessageRecord ;
import org.thoughtcrime.securesms.database.model.NotificationMmsMessageRecord ;
2018-02-07 23:01:37 +01:00
import org.thoughtcrime.securesms.database.model.Quote ;
2019-12-03 22:57:21 +01:00
import org.thoughtcrime.securesms.database.model.ReactionRecord ;
2020-08-20 22:50:14 +02:00
import org.thoughtcrime.securesms.database.model.SmsMessageRecord ;
2020-08-05 22:45:52 +02:00
import org.thoughtcrime.securesms.database.model.databaseprotos.BodyRangeList ;
2019-10-15 21:47:54 +02:00
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies ;
2014-11-25 07:50:32 +01:00
import org.thoughtcrime.securesms.jobs.TrimThreadJob ;
2019-01-15 09:41:05 +01:00
import org.thoughtcrime.securesms.linkpreview.LinkPreview ;
2018-05-22 11:13:10 +02:00
import org.thoughtcrime.securesms.logging.Log ;
2013-07-19 02:42:45 +02:00
import org.thoughtcrime.securesms.mms.IncomingMediaMessage ;
2020-04-09 23:02:13 +02:00
import org.thoughtcrime.securesms.mms.MessageGroupContext ;
2017-07-26 18:59:15 +02:00
import org.thoughtcrime.securesms.mms.MmsException ;
2016-08-16 05:23:56 +02:00
import org.thoughtcrime.securesms.mms.OutgoingExpirationUpdateMessage ;
2020-05-06 18:42:54 +02:00
import org.thoughtcrime.securesms.mms.OutgoingGroupUpdateMessage ;
2014-11-12 20:15:05 +01:00
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage ;
2015-10-13 03:25:05 +02:00
import org.thoughtcrime.securesms.mms.OutgoingSecureMediaMessage ;
2018-02-07 23:01:37 +01:00
import org.thoughtcrime.securesms.mms.QuoteModel ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
import org.thoughtcrime.securesms.mms.SlideDeck ;
2017-08-01 17:56:00 +02:00
import org.thoughtcrime.securesms.recipients.Recipient ;
2019-08-07 20:22:51 +02:00
import org.thoughtcrime.securesms.recipients.RecipientId ;
2019-08-01 01:33:56 +02:00
import org.thoughtcrime.securesms.revealable.ViewOnceExpirationInfo ;
import org.thoughtcrime.securesms.revealable.ViewOnceUtil ;
2020-08-20 22:50:14 +02:00
import org.thoughtcrime.securesms.sms.IncomingTextMessage ;
import org.thoughtcrime.securesms.sms.OutgoingTextMessage ;
2020-08-05 22:45:52 +02:00
import org.thoughtcrime.securesms.util.CursorUtil ;
2015-01-15 22:35:35 +01:00
import org.thoughtcrime.securesms.util.JsonUtils ;
2020-08-13 20:37:15 +02:00
import org.thoughtcrime.securesms.util.SqlUtil ;
2017-09-16 07:38:53 +02:00
import org.thoughtcrime.securesms.util.TextSecurePreferences ;
2014-11-12 20:15:05 +01:00
import org.thoughtcrime.securesms.util.Util ;
2020-08-20 22:50:14 +02:00
import org.whispersystems.libsignal.util.Pair ;
2016-03-23 18:34:41 +01:00
import org.whispersystems.libsignal.util.guava.Optional ;
2011-12-20 19:20:44 +01:00
2015-01-15 22:35:35 +01:00
import java.io.IOException ;
2017-04-23 01:29:26 +02:00
import java.security.SecureRandom ;
2020-06-07 20:46:03 +02:00
import java.util.Collection ;
2018-04-27 02:03:54 +02:00
import java.util.Collections ;
import java.util.HashMap ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
import java.util.HashSet ;
2015-01-15 22:35:35 +01:00
import java.util.LinkedList ;
2013-09-09 03:19:05 +02:00
import java.util.List ;
2017-10-02 23:54:55 +02:00
import java.util.Map ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
import java.util.Set ;
2018-06-18 21:27:04 +02:00
import static org.thoughtcrime.securesms.contactshare.Contact.Avatar ;
2018-04-27 02:03:54 +02:00
2020-08-20 22:50:14 +02:00
public class MmsDatabase extends MessageDatabase {
2015-01-15 22:35:35 +01:00
private static final String TAG = MmsDatabase . class . getSimpleName ( ) ;
2012-09-08 05:03:23 +02:00
2011-12-20 19:20:44 +01:00
public static final String TABLE_NAME = "mms" ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
static final String DATE_SENT = "date" ;
static final String DATE_RECEIVED = "date_received" ;
2011-12-20 19:20:44 +01:00
public static final String MESSAGE_BOX = "msg_box" ;
2013-05-05 21:51:36 +02:00
static final String CONTENT_LOCATION = "ct_l" ;
static final String EXPIRY = "exp" ;
2011-12-20 19:20:44 +01:00
public static final String MESSAGE_TYPE = "m_type" ;
2013-05-05 21:51:36 +02:00
static final String MESSAGE_SIZE = "m_size" ;
static final String STATUS = "st" ;
static final String TRANSACTION_ID = "tr_id" ;
2013-04-26 20:23:43 +02:00
static final String PART_COUNT = "part_count" ;
2015-01-15 22:35:35 +01:00
static final String NETWORK_FAILURE = "network_failures" ;
2012-09-08 05:03:23 +02:00
2018-02-07 23:01:37 +01:00
static final String QUOTE_ID = "quote_id" ;
static final String QUOTE_AUTHOR = "quote_author" ;
static final String QUOTE_BODY = "quote_body" ;
static final String QUOTE_ATTACHMENT = "quote_attachment" ;
2018-08-11 15:55:52 +02:00
static final String QUOTE_MISSING = "quote_missing" ;
2020-08-05 22:45:52 +02:00
static final String QUOTE_MENTIONS = "quote_mentions" ;
2018-02-07 23:01:37 +01:00
2019-01-15 09:41:05 +01:00
static final String SHARED_CONTACTS = "shared_contacts" ;
static final String LINK_PREVIEWS = "previews" ;
2020-08-05 22:45:52 +02:00
static final String MENTIONS_SELF = "mentions_self" ;
2018-04-27 02:03:54 +02:00
2019-08-01 01:33:56 +02:00
public static final String VIEW_ONCE = "reveal_duration" ;
2019-06-11 08:18:45 +02:00
2019-12-03 22:57:21 +01:00
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY, " +
THREAD_ID + " INTEGER, " +
DATE_SENT + " INTEGER, " +
DATE_RECEIVED + " INTEGER, " +
2020-04-14 01:02:50 +02:00
DATE_SERVER + " INTEGER DEFAULT -1, " +
2019-12-03 22:57:21 +01:00
MESSAGE_BOX + " INTEGER, " +
READ + " INTEGER DEFAULT 0, " +
"m_id" + " TEXT, " +
"sub" + " TEXT, " +
"sub_cs" + " INTEGER, " +
BODY + " TEXT, " +
PART_COUNT + " INTEGER, " +
"ct_t" + " TEXT, " +
CONTENT_LOCATION + " TEXT, " +
RECIPIENT_ID + " INTEGER, " +
ADDRESS_DEVICE_ID + " INTEGER, " +
EXPIRY + " INTEGER, " +
"m_cls" + " TEXT, " +
MESSAGE_TYPE + " INTEGER, " +
"v" + " INTEGER, " +
MESSAGE_SIZE + " INTEGER, " +
"pri" + " INTEGER, " +
"rr" + " INTEGER, " +
"rpt_a" + " INTEGER, " +
"resp_st" + " INTEGER, " +
STATUS + " INTEGER, " +
TRANSACTION_ID + " TEXT, " +
"retr_st" + " INTEGER, " +
"retr_txt" + " TEXT, " +
"retr_txt_cs" + " INTEGER, " +
"read_status" + " INTEGER, " +
"ct_cls" + " INTEGER, " +
"resp_txt" + " TEXT, " +
"d_tm" + " INTEGER, " +
DELIVERY_RECEIPT_COUNT + " INTEGER DEFAULT 0, " +
MISMATCHED_IDENTITIES + " TEXT DEFAULT NULL, " +
NETWORK_FAILURE + " TEXT DEFAULT NULL," +
"d_rpt" + " INTEGER, " +
SUBSCRIPTION_ID + " INTEGER DEFAULT -1, " +
EXPIRES_IN + " INTEGER DEFAULT 0, " +
EXPIRE_STARTED + " INTEGER DEFAULT 0, " +
NOTIFIED + " INTEGER DEFAULT 0, " +
READ_RECEIPT_COUNT + " INTEGER DEFAULT 0, " +
QUOTE_ID + " INTEGER DEFAULT 0, " +
QUOTE_AUTHOR + " TEXT, " +
QUOTE_BODY + " TEXT, " +
QUOTE_ATTACHMENT + " INTEGER DEFAULT -1, " +
QUOTE_MISSING + " INTEGER DEFAULT 0, " +
2020-08-05 22:45:52 +02:00
QUOTE_MENTIONS + " BLOB DEFAULT NULL," +
2019-12-03 22:57:21 +01:00
SHARED_CONTACTS + " TEXT, " +
UNIDENTIFIED + " INTEGER DEFAULT 0, " +
LINK_PREVIEWS + " TEXT, " +
VIEW_ONCE + " INTEGER DEFAULT 0, " +
REACTIONS + " BLOB DEFAULT NULL, " +
REACTIONS_UNREAD + " INTEGER DEFAULT 0, " +
2020-04-15 20:56:58 +02:00
REACTIONS_LAST_SEEN + " INTEGER DEFAULT -1, " +
2020-08-05 22:45:52 +02:00
REMOTE_DELETED + " INTEGER DEFAULT 0, " +
MENTIONS_SELF + " INTEGER DEFAULT 0);" ;
2011-12-20 19:20:44 +01:00
2012-10-30 01:41:06 +01:00
public static final String [ ] CREATE_INDEXS = {
"CREATE INDEX IF NOT EXISTS mms_thread_id_index ON " + TABLE_NAME + " (" + THREAD_ID + ");" ,
"CREATE INDEX IF NOT EXISTS mms_read_index ON " + TABLE_NAME + " (" + READ + ");" ,
2017-03-09 02:38:55 +01:00
"CREATE INDEX IF NOT EXISTS mms_read_and_notified_and_thread_id_index ON " + TABLE_NAME + "(" + READ + "," + NOTIFIED + "," + THREAD_ID + ");" ,
2014-07-26 00:14:29 +02:00
"CREATE INDEX IF NOT EXISTS mms_message_box_index ON " + TABLE_NAME + " (" + MESSAGE_BOX + ");" ,
2015-08-04 22:37:22 +02:00
"CREATE INDEX IF NOT EXISTS mms_date_sent_index ON " + TABLE_NAME + " (" + DATE_SENT + ");" ,
2020-04-14 01:02:50 +02:00
"CREATE INDEX IF NOT EXISTS mms_date_server_index ON " + TABLE_NAME + " (" + DATE_SERVER + ");" ,
2019-04-17 16:21:30 +02:00
"CREATE INDEX IF NOT EXISTS mms_thread_date_index ON " + TABLE_NAME + " (" + THREAD_ID + ", " + DATE_RECEIVED + ");" ,
2019-12-06 01:10:37 +01:00
"CREATE INDEX IF NOT EXISTS mms_reactions_unread_index ON " + TABLE_NAME + " (" + REACTIONS_UNREAD + ");"
2012-10-30 01:41:06 +01:00
} ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
private static final String [ ] MMS_PROJECTION = new String [ ] {
2015-10-24 18:40:04 +02:00
MmsDatabase . TABLE_NAME + "." + ID + " AS " + ID ,
THREAD_ID , DATE_SENT + " AS " + NORMALIZED_DATE_SENT ,
2015-08-04 22:37:22 +02:00
DATE_RECEIVED + " AS " + NORMALIZED_DATE_RECEIVED ,
2020-04-14 01:02:50 +02:00
DATE_SERVER ,
2015-10-13 03:25:05 +02:00
MESSAGE_BOX , READ ,
CONTENT_LOCATION , EXPIRY , MESSAGE_TYPE ,
MESSAGE_SIZE , STATUS , TRANSACTION_ID ,
2019-08-07 20:22:51 +02:00
BODY , PART_COUNT , RECIPIENT_ID , ADDRESS_DEVICE_ID ,
2017-09-30 17:45:45 +02:00
DELIVERY_RECEIPT_COUNT , READ_RECEIPT_COUNT , MISMATCHED_IDENTITIES , NETWORK_FAILURE , SUBSCRIPTION_ID ,
2020-08-05 22:45:52 +02:00
EXPIRES_IN , EXPIRE_STARTED , NOTIFIED , QUOTE_ID , QUOTE_AUTHOR , QUOTE_BODY , QUOTE_ATTACHMENT , QUOTE_MISSING , QUOTE_MENTIONS ,
2019-12-03 22:57:21 +01:00
SHARED_CONTACTS , LINK_PREVIEWS , UNIDENTIFIED , VIEW_ONCE , REACTIONS , REACTIONS_UNREAD , REACTIONS_LAST_SEEN ,
2020-08-05 22:45:52 +02:00
REMOTE_DELETED , MENTIONS_SELF ,
2018-02-07 23:01:37 +01:00
"json_group_array(json_object(" +
"'" + AttachmentDatabase . ROW_ID + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . ROW_ID + ", " +
"'" + AttachmentDatabase . UNIQUE_ID + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . UNIQUE_ID + ", " +
"'" + AttachmentDatabase . MMS_ID + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . MMS_ID + ", " +
"'" + AttachmentDatabase . SIZE + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . SIZE + ", " +
"'" + AttachmentDatabase . FILE_NAME + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . FILE_NAME + ", " +
"'" + AttachmentDatabase . DATA + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . DATA + ", " +
"'" + AttachmentDatabase . CONTENT_TYPE + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . CONTENT_TYPE + ", " +
2020-04-06 02:32:06 +02:00
"'" + AttachmentDatabase . CDN_NUMBER + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . CDN_NUMBER + ", " +
2018-02-07 23:01:37 +01:00
"'" + AttachmentDatabase . CONTENT_LOCATION + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . CONTENT_LOCATION + ", " +
"'" + AttachmentDatabase . FAST_PREFLIGHT_ID + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . FAST_PREFLIGHT_ID + "," +
"'" + AttachmentDatabase . VOICE_NOTE + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . VOICE_NOTE + "," +
2020-07-06 23:13:08 +02:00
"'" + AttachmentDatabase . BORDERLESS + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . BORDERLESS + "," +
2018-02-07 23:01:37 +01:00
"'" + AttachmentDatabase . WIDTH + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . WIDTH + "," +
"'" + AttachmentDatabase . HEIGHT + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . HEIGHT + "," +
"'" + AttachmentDatabase . QUOTE + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . QUOTE + ", " +
"'" + AttachmentDatabase . CONTENT_DISPOSITION + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . CONTENT_DISPOSITION + ", " +
"'" + AttachmentDatabase . NAME + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . NAME + ", " +
2018-11-09 08:33:37 +01:00
"'" + AttachmentDatabase . TRANSFER_STATE + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . TRANSFER_STATE + ", " +
2019-04-17 16:21:30 +02:00
"'" + AttachmentDatabase . CAPTION + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . CAPTION + ", " +
"'" + AttachmentDatabase . STICKER_PACK_ID + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . STICKER_PACK_ID + ", " +
"'" + AttachmentDatabase . STICKER_PACK_KEY + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . STICKER_PACK_KEY + ", " +
2019-10-17 14:26:08 +02:00
"'" + AttachmentDatabase . STICKER_ID + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . STICKER_ID + ", " +
2020-09-03 16:02:33 +02:00
"'" + AttachmentDatabase . STICKER_EMOJI + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . STICKER_EMOJI + ", " +
2020-06-01 23:10:10 +02:00
"'" + AttachmentDatabase . VISUAL_HASH + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . VISUAL_HASH + ", " +
2020-01-08 21:56:51 +01:00
"'" + AttachmentDatabase . TRANSFORM_PROPERTIES + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . TRANSFORM_PROPERTIES + ", " +
2020-03-28 01:36:06 +01:00
"'" + AttachmentDatabase . DISPLAY_ORDER + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . DISPLAY_ORDER + ", " +
"'" + AttachmentDatabase . UPLOAD_TIMESTAMP + "', " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . UPLOAD_TIMESTAMP +
2018-02-07 23:01:37 +01:00
")) AS " + AttachmentDatabase . ATTACHMENT_JSON_ALIAS ,
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
} ;
2015-10-24 18:40:04 +02:00
private static final String RAW_ID_WHERE = TABLE_NAME + "._id = ?" ;
2013-04-26 20:23:43 +02:00
2019-11-12 15:18:57 +01:00
private static final String OUTGOING_INSECURE_MESSAGES_CLAUSE = "(" + MESSAGE_BOX + " & " + Types . BASE_TYPE_MASK + ") = " + Types . BASE_SENT_TYPE + " AND NOT (" + MESSAGE_BOX + " & " + Types . SECURE_MESSAGE_BIT + ")" ;
private static final String OUTGOING_SECURE_MESSAGES_CLAUSE = "(" + MESSAGE_BOX + " & " + Types . BASE_TYPE_MASK + ") = " + Types . BASE_SENT_TYPE + " AND (" + MESSAGE_BOX + " & " + ( Types . SECURE_MESSAGE_BIT | Types . PUSH_MESSAGE_BIT ) + ")" ;
2019-08-07 20:22:51 +02:00
private final EarlyReceiptCache earlyDeliveryReceiptCache = new EarlyReceiptCache ( "MmsDelivery" ) ;
2017-09-16 07:38:53 +02:00
2018-01-25 04:17:44 +01:00
public MmsDatabase ( Context context , SQLCipherOpenHelper databaseHelper ) {
2011-12-20 19:20:44 +01:00
super ( context , databaseHelper ) ;
}
2012-09-08 05:03:23 +02:00
2015-01-15 22:35:35 +01:00
@Override
protected String getTableName ( ) {
return TABLE_NAME ;
}
2019-11-12 15:18:57 +01:00
@Override
protected String getDateSentColumnName ( ) {
return DATE_SENT ;
}
2020-08-04 19:13:59 +02:00
@Override
protected String getDateReceivedColumnName ( ) {
return DATE_RECEIVED ;
}
2019-11-12 15:18:57 +01:00
@Override
protected String getTypeField ( ) {
return MESSAGE_BOX ;
}
2020-08-20 22:50:14 +02:00
@Override
public @Nullable RecipientId getOldestGroupUpdateSender ( long threadId , long minimumDateReceived ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
int getMessageCountForThreadSummary ( long threadId ) {
return getMessageCountForThread ( threadId ) ;
}
@Override
public Cursor getExpirationStartedMessages ( ) {
String where = EXPIRE_STARTED + " > 0" ;
return rawQuery ( where , null ) ;
}
@Override
public SmsMessageRecord getSmsMessage ( long messageId ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public Cursor getMessageCursor ( long messageId ) {
Cursor cursor = internalGetMessage ( messageId ) ;
setNotifyConversationListeners ( cursor , getThreadIdForMessage ( messageId ) ) ;
return cursor ;
}
@Override
public Cursor getVerboseMessageCursor ( long messageId ) {
Cursor cursor = internalGetMessage ( messageId ) ;
setNotifyVerboseConversationListeners ( cursor , getThreadIdForMessage ( messageId ) ) ;
return cursor ;
}
@Override
public boolean hasReceivedAnyCallsSince ( long threadId , long timestamp ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsEndSession ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsPreKeyBundle ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsInvalidVersionKeyExchange ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsSecure ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsPush ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsDecryptFailed ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsDecryptDuplicate ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsNoSession ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsUnsupportedProtocolVersion ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsInvalidMessage ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsLegacyVersion ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markAsMissedCall ( long id ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void markSmsStatus ( long id , int status ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public Pair < Long , Long > updateBundleMessageBody ( long messageId , String body ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public @NonNull Pair < Long , Long > insertReceivedCall ( @NonNull RecipientId address ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public @NonNull Pair < Long , Long > insertOutgoingCall ( @NonNull RecipientId address ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
2020-09-17 08:52:48 +02:00
public @NonNull Pair < Long , Long > insertMissedCall ( @NonNull RecipientId address , long timestamp ) {
2020-08-20 22:50:14 +02:00
throw new UnsupportedOperationException ( ) ;
}
@Override
public Optional < InsertResult > insertMessageInbox ( IncomingTextMessage message , long type ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public Optional < InsertResult > insertMessageInbox ( IncomingTextMessage message ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public long insertMessageOutbox ( long threadId , OutgoingTextMessage message , boolean forceSms , long date , InsertListener insertListener ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
public void insertProfileNameChangeMessages ( @NonNull Recipient recipient , @NonNull String newProfileName , @NonNull String previousProfileName ) {
throw new UnsupportedOperationException ( ) ;
}
@Override
2020-08-24 22:40:47 +02:00
public void endTransaction ( SQLiteDatabase database ) {
database . endTransaction ( ) ;
2020-08-20 22:50:14 +02:00
}
@Override
2020-08-24 22:40:47 +02:00
public SQLiteStatement createInsertStatement ( SQLiteDatabase database ) {
2020-08-20 22:50:14 +02:00
throw new UnsupportedOperationException ( ) ;
}
@Override
public void ensureMigration ( ) {
databaseHelper . getWritableDatabase ( ) ;
}
2020-08-24 22:40:47 +02:00
@Override
2020-02-19 23:08:34 +01:00
public boolean isGroupQuitMessage ( long messageId ) {
SQLiteDatabase db = databaseHelper . getReadableDatabase ( ) ;
String [ ] columns = new String [ ] { ID } ;
String query = ID + " = ? AND " + MESSAGE_BOX + " & ?" ;
long type = Types . getOutgoingEncryptedMessageType ( ) | Types . GROUP_QUIT_BIT ;
String [ ] args = new String [ ] { String . valueOf ( messageId ) , String . valueOf ( type ) } ;
try ( Cursor cursor = db . query ( TABLE_NAME , columns , query , args , null , null , null , null ) ) {
if ( cursor . getCount ( ) = = 1 ) {
return true ;
}
}
return false ;
}
2020-08-24 22:40:47 +02:00
@Override
2020-02-19 23:08:34 +01:00
public long getLatestGroupQuitTimestamp ( long threadId , long quitTimeBarrier ) {
SQLiteDatabase db = databaseHelper . getReadableDatabase ( ) ;
String [ ] columns = new String [ ] { DATE_SENT } ;
String query = THREAD_ID + " = ? AND " + MESSAGE_BOX + " & ? AND " + DATE_SENT + " < ?" ;
long type = Types . getOutgoingEncryptedMessageType ( ) | Types . GROUP_QUIT_BIT ;
String [ ] args = new String [ ] { String . valueOf ( threadId ) , String . valueOf ( type ) , String . valueOf ( quitTimeBarrier ) } ;
String orderBy = DATE_SENT + " DESC" ;
String limit = "1" ;
try ( Cursor cursor = db . query ( TABLE_NAME , columns , query , args , null , null , orderBy , limit ) ) {
if ( cursor . moveToFirst ( ) ) {
return cursor . getLong ( cursor . getColumnIndex ( DATE_SENT ) ) ;
}
}
return - 1 ;
}
2020-08-24 22:40:47 +02:00
@Override
2011-12-20 19:20:44 +01:00
public int getMessageCountForThread ( long threadId ) {
2012-09-08 05:03:23 +02:00
SQLiteDatabase db = databaseHelper . getReadableDatabase ( ) ;
2020-02-21 19:52:27 +01:00
String [ ] cols = new String [ ] { "COUNT(*)" } ;
String query = THREAD_ID + " = ?" ;
String [ ] args = new String [ ] { String . valueOf ( threadId ) } ;
try ( Cursor cursor = db . query ( TABLE_NAME , cols , query , args , null , null , null ) ) {
if ( cursor ! = null & & cursor . moveToFirst ( ) ) {
return cursor . getInt ( 0 ) ;
}
}
return 0 ;
}
2020-08-24 22:40:47 +02:00
@Override
2020-02-21 19:52:27 +01:00
public int getMessageCountForThread ( long threadId , long beforeTime ) {
SQLiteDatabase db = databaseHelper . getReadableDatabase ( ) ;
String [ ] cols = new String [ ] { "COUNT(*)" } ;
String query = THREAD_ID + " = ? AND " + DATE_RECEIVED + " < ?" ;
String [ ] args = new String [ ] { String . valueOf ( threadId ) , String . valueOf ( beforeTime ) } ;
2012-09-08 05:03:23 +02:00
2020-02-21 19:52:27 +01:00
try ( Cursor cursor = db . query ( TABLE_NAME , cols , query , args , null , null , null ) ) {
if ( cursor ! = null & & cursor . moveToFirst ( ) ) {
2011-12-20 19:20:44 +01:00
return cursor . getInt ( 0 ) ;
2020-02-21 19:52:27 +01:00
}
2011-12-20 19:20:44 +01:00
}
return 0 ;
}
2012-09-08 05:03:23 +02:00
2020-08-24 22:40:47 +02:00
@Override
2015-01-15 22:35:35 +01:00
public void addFailures ( long messageId , List < NetworkFailure > failure ) {
try {
addToDocument ( messageId , NETWORK_FAILURE , failure , NetworkFailureList . class ) ;
} catch ( IOException e ) {
Log . w ( TAG , e ) ;
}
}
2020-08-24 22:40:47 +02:00
@Override
2015-01-15 22:35:35 +01:00
public void removeFailure ( long messageId , NetworkFailure failure ) {
try {
removeFromDocument ( messageId , NETWORK_FAILURE , failure , NetworkFailureList . class ) ;
} catch ( IOException e ) {
Log . w ( TAG , e ) ;
}
}
2020-08-24 22:40:47 +02:00
@Override
2020-04-16 22:09:49 +02:00
public boolean incrementReceiptCount ( SyncMessageId messageId , long timestamp , boolean deliveryReceipt ) {
2017-08-01 17:56:00 +02:00
SQLiteDatabase database = databaseHelper . getWritableDatabase ( ) ;
boolean found = false ;
2014-07-26 00:14:29 +02:00
2020-06-09 17:52:58 +02:00
try ( Cursor cursor = database . query ( TABLE_NAME , new String [ ] { ID , THREAD_ID , MESSAGE_BOX , RECIPIENT_ID , DELIVERY_RECEIPT_COUNT , READ_RECEIPT_COUNT } ,
DATE_SENT + " = ?" , new String [ ] { String . valueOf ( messageId . getTimetamp ( ) ) } ,
null , null , null , null ) ) {
2014-07-26 00:14:29 +02:00
while ( cursor . moveToNext ( ) ) {
2014-10-21 06:06:34 +02:00
if ( Types . isOutgoingMessageType ( cursor . getLong ( cursor . getColumnIndexOrThrow ( MESSAGE_BOX ) ) ) ) {
2019-08-07 20:22:51 +02:00
RecipientId theirRecipientId = RecipientId . from ( cursor . getLong ( cursor . getColumnIndexOrThrow ( RECIPIENT_ID ) ) ) ;
RecipientId ourRecipientId = messageId . getRecipientId ( ) ;
String columnName = deliveryReceipt ? DELIVERY_RECEIPT_COUNT : READ_RECEIPT_COUNT ;
2014-10-21 06:06:34 +02:00
2019-08-07 20:22:51 +02:00
if ( ourRecipientId . equals ( theirRecipientId ) | | Recipient . resolved ( theirRecipientId ) . isGroup ( ) ) {
2020-06-09 17:52:58 +02:00
long id = cursor . getLong ( cursor . getColumnIndexOrThrow ( ID ) ) ;
long threadId = cursor . getLong ( cursor . getColumnIndexOrThrow ( THREAD_ID ) ) ;
int status = deliveryReceipt ? GroupReceiptDatabase . STATUS_DELIVERED : GroupReceiptDatabase . STATUS_READ ;
boolean isFirstIncrement = cursor . getLong ( cursor . getColumnIndexOrThrow ( columnName ) ) = = 0 ;
2014-10-21 06:06:34 +02:00
2017-08-01 17:56:00 +02:00
found = true ;
2015-12-09 05:32:54 +01:00
2017-08-01 17:56:00 +02:00
database . execSQL ( "UPDATE " + TABLE_NAME + " SET " +
2017-09-16 07:38:53 +02:00
columnName + " = " + columnName + " + 1 WHERE " + ID + " = ?" ,
2017-08-01 17:56:00 +02:00
new String [ ] { String . valueOf ( id ) } ) ;
2014-10-21 06:06:34 +02:00
2019-08-07 20:22:51 +02:00
DatabaseFactory . getGroupReceiptDatabase ( context ) . update ( ourRecipientId , id , status , timestamp ) ;
2017-08-01 17:56:00 +02:00
DatabaseFactory . getThreadDatabase ( context ) . update ( threadId , false ) ;
2020-06-09 17:52:58 +02:00
if ( isFirstIncrement ) {
notifyConversationListeners ( threadId ) ;
} else {
notifyVerboseConversationListeners ( threadId ) ;
}
2014-07-26 00:14:29 +02:00
}
}
}
2015-12-09 05:32:54 +01:00
2020-04-16 22:09:49 +02:00
if ( ! found & & deliveryReceipt ) {
earlyDeliveryReceiptCache . increment ( messageId . getTimetamp ( ) , messageId . getRecipientId ( ) ) ;
return true ;
2015-12-09 05:32:54 +01:00
}
2020-04-16 22:09:49 +02:00
return found ;
2014-07-26 00:14:29 +02:00
}
}
2020-08-24 22:40:47 +02:00
@Override
2011-12-20 19:20:44 +01:00
public long getThreadIdForMessage ( long id ) {
String sql = "SELECT " + THREAD_ID + " FROM " + TABLE_NAME + " WHERE " + ID + " = ?" ;
String [ ] sqlArgs = new String [ ] { id + "" } ;
SQLiteDatabase db = databaseHelper . getReadableDatabase ( ) ;
2012-09-08 05:03:23 +02:00
2011-12-20 19:20:44 +01:00
Cursor cursor = null ;
2012-09-08 05:03:23 +02:00
2011-12-20 19:20:44 +01:00
try {
cursor = db . rawQuery ( sql , sqlArgs ) ;
if ( cursor ! = null & & cursor . moveToFirst ( ) )
return cursor . getLong ( 0 ) ;
else
return - 1 ;
} finally {
if ( cursor ! = null )
cursor . close ( ) ;
}
}
2012-09-08 05:03:23 +02:00
2019-08-07 20:22:51 +02:00
private long getThreadIdFor ( @NonNull IncomingMediaMessage retrieved ) {
2014-01-14 09:26:43 +01:00
if ( retrieved . getGroupId ( ) ! = null ) {
2019-08-07 20:22:51 +02:00
RecipientId groupRecipientId = DatabaseFactory . getRecipientDatabase ( context ) . getOrInsertFromGroupId ( retrieved . getGroupId ( ) ) ;
Recipient groupRecipients = Recipient . resolved ( groupRecipientId ) ;
2014-02-15 00:59:57 +01:00
return DatabaseFactory . getThreadDatabase ( context ) . getThreadIdFor ( groupRecipients ) ;
2015-10-28 18:24:55 +01:00
} else {
2019-08-07 20:22:51 +02:00
Recipient sender = Recipient . resolved ( retrieved . getFrom ( ) ) ;
2017-08-01 17:56:00 +02:00
return DatabaseFactory . getThreadDatabase ( context ) . getThreadIdFor ( sender ) ;
2015-10-28 18:24:55 +01:00
}
2013-04-26 03:59:49 +02:00
}
2015-03-27 18:26:17 +01:00
private long getThreadIdFor ( @NonNull NotificationInd notification ) {
String fromString = notification . getFrom ( ) ! = null & & notification . getFrom ( ) . getTextString ( ) ! = null
? Util . toIsoString ( notification . getFrom ( ) . getTextString ( ) )
: "" ;
2019-08-07 20:22:51 +02:00
Recipient recipient = Recipient . external ( context , fromString ) ;
2017-08-01 17:56:00 +02:00
return DatabaseFactory . getThreadDatabase ( context ) . getThreadIdFor ( recipient ) ;
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2015-10-24 18:40:04 +02:00
private Cursor rawQuery ( @NonNull String where , @Nullable String [ ] arguments ) {
SQLiteDatabase database = databaseHelper . getReadableDatabase ( ) ;
2015-10-25 02:51:17 +02:00
return database . rawQuery ( "SELECT " + Util . join ( MMS_PROJECTION , "," ) +
2015-10-24 18:40:04 +02:00
" FROM " + MmsDatabase . TABLE_NAME + " LEFT OUTER JOIN " + AttachmentDatabase . TABLE_NAME +
" ON (" + MmsDatabase . TABLE_NAME + "." + MmsDatabase . ID + " = " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . MMS_ID + ")" +
2018-02-07 23:01:37 +01:00
" WHERE " + where + " GROUP BY " + MmsDatabase . TABLE_NAME + "." + MmsDatabase . ID , arguments ) ;
2015-10-24 18:40:04 +02:00
}
2020-06-09 17:52:58 +02:00
private Cursor internalGetMessage ( long messageId ) {
return rawQuery ( RAW_ID_WHERE , new String [ ] { messageId + "" } ) ;
}
2020-07-30 22:02:17 +02:00
@Override
2019-12-03 22:57:21 +01:00
public MessageRecord getMessageRecord ( long messageId ) throws NoSuchMessageException {
try ( Cursor cursor = rawQuery ( RAW_ID_WHERE , new String [ ] { messageId + "" } ) ) {
MessageRecord record = new Reader ( cursor ) . getNext ( ) ;
if ( record = = null ) {
throw new NoSuchMessageException ( "No message for ID: " + messageId ) ;
}
return record ;
}
}
2020-08-24 22:40:47 +02:00
@Override
2020-08-07 21:18:40 +02:00
public Reader getMessages ( Collection < Long > messageIds ) {
String ids = TextUtils . join ( "," , messageIds ) ;
return readerFor ( rawQuery ( MmsDatabase . TABLE_NAME + "." + MmsDatabase . ID + " IN (" + ids + ")" , null ) ) ;
}
2015-12-03 20:47:28 +01:00
private void updateMailboxBitmask ( long id , long maskOff , long maskOn , Optional < Long > threadId ) {
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
SQLiteDatabase db = databaseHelper . getWritableDatabase ( ) ;
db . execSQL ( "UPDATE " + TABLE_NAME +
2015-01-15 22:35:35 +01:00
" SET " + MESSAGE_BOX + " = (" + MESSAGE_BOX + " & " + ( Types . TOTAL_MASK - maskOff ) + " | " + maskOn + " )" +
" WHERE " + ID + " = ?" , new String [ ] { id + "" } ) ;
2015-11-24 16:06:41 +01:00
2015-12-03 20:47:28 +01:00
if ( threadId . isPresent ( ) ) {
DatabaseFactory . getThreadDatabase ( context ) . update ( threadId . get ( ) , false ) ;
}
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2020-08-24 22:40:47 +02:00
@Override
2014-02-16 03:31:25 +01:00
public void markAsOutbox ( long messageId ) {
2015-12-03 20:47:28 +01:00
long threadId = getThreadIdForMessage ( messageId ) ;
updateMailboxBitmask ( messageId , Types . BASE_TYPE_MASK , Types . BASE_OUTBOX_TYPE , Optional . of ( threadId ) ) ;
2014-03-01 23:17:55 +01:00
}
2020-08-24 22:40:47 +02:00
@Override
2014-04-04 01:20:23 +02:00
public void markAsForcedSms ( long messageId ) {
2015-12-03 20:47:28 +01:00
long threadId = getThreadIdForMessage ( messageId ) ;
updateMailboxBitmask ( messageId , Types . PUSH_MESSAGE_BIT , Types . MESSAGE_FORCE_SMS_BIT , Optional . of ( threadId ) ) ;
notifyConversationListeners ( threadId ) ;
2014-03-01 23:17:55 +01:00
}
2020-08-24 22:40:47 +02:00
@Override
2014-04-01 03:47:24 +02:00
public void markAsPendingInsecureSmsFallback ( long messageId ) {
2015-12-03 20:47:28 +01:00
long threadId = getThreadIdForMessage ( messageId ) ;
updateMailboxBitmask ( messageId , Types . BASE_TYPE_MASK , Types . BASE_PENDING_INSECURE_SMS_FALLBACK , Optional . of ( threadId ) ) ;
notifyConversationListeners ( threadId ) ;
2014-02-16 03:31:25 +01:00
}
2020-04-15 20:56:58 +02:00
@Override
2018-10-12 01:45:22 +02:00
public void markAsSending ( long messageId ) {
long threadId = getThreadIdForMessage ( messageId ) ;
updateMailboxBitmask ( messageId , Types . BASE_TYPE_MASK , Types . BASE_SENDING_TYPE , Optional . of ( threadId ) ) ;
notifyConversationListeners ( threadId ) ;
}
2013-10-13 12:53:41 +02:00
2020-08-24 22:40:47 +02:00
@Override
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
public void markAsSentFailed ( long messageId ) {
2015-12-03 20:47:28 +01:00
long threadId = getThreadIdForMessage ( messageId ) ;
updateMailboxBitmask ( messageId , Types . BASE_TYPE_MASK , Types . BASE_SENT_FAILED_TYPE , Optional . of ( threadId ) ) ;
notifyConversationListeners ( threadId ) ;
2011-12-20 19:20:44 +01:00
}
2013-07-17 04:52:02 +02:00
2017-10-02 23:54:55 +02:00
@Override
2016-12-21 18:49:01 +01:00
public void markAsSent ( long messageId , boolean secure ) {
2015-12-03 20:47:28 +01:00
long threadId = getThreadIdForMessage ( messageId ) ;
2016-12-21 18:49:01 +01:00
updateMailboxBitmask ( messageId , Types . BASE_TYPE_MASK , Types . BASE_SENT_TYPE | ( secure ? Types . PUSH_MESSAGE_BIT | Types . SECURE_MESSAGE_BIT : 0 ) , Optional . of ( threadId ) ) ;
2015-12-03 20:47:28 +01:00
notifyConversationListeners ( threadId ) ;
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2020-04-15 20:56:58 +02:00
@Override
public void markAsRemoteDelete ( long messageId ) {
SQLiteDatabase db = databaseHelper . getWritableDatabase ( ) ;
ContentValues values = new ContentValues ( ) ;
values . put ( REMOTE_DELETED , 1 ) ;
values . putNull ( BODY ) ;
values . putNull ( QUOTE_BODY ) ;
values . putNull ( QUOTE_AUTHOR ) ;
values . putNull ( QUOTE_ATTACHMENT ) ;
values . putNull ( QUOTE_ID ) ;
values . putNull ( LINK_PREVIEWS ) ;
values . putNull ( SHARED_CONTACTS ) ;
values . putNull ( REACTIONS ) ;
db . update ( TABLE_NAME , values , ID_WHERE , new String [ ] { String . valueOf ( messageId ) } ) ;
DatabaseFactory . getAttachmentDatabase ( context ) . deleteAttachmentsForMessage ( messageId ) ;
2020-09-30 20:35:02 +02:00
DatabaseFactory . getMentionDatabase ( context ) . deleteMentionsForMessage ( messageId ) ;
2020-04-15 20:56:58 +02:00
long threadId = getThreadIdForMessage ( messageId ) ;
DatabaseFactory . getThreadDatabase ( context ) . update ( threadId , false ) ;
notifyConversationListeners ( threadId ) ;
}
2020-08-24 22:40:47 +02:00
@Override
2011-12-20 19:20:44 +01:00
public void markDownloadState ( long messageId , long state ) {
SQLiteDatabase database = databaseHelper . getWritableDatabase ( ) ;
ContentValues contentValues = new ContentValues ( ) ;
contentValues . put ( STATUS , state ) ;
2012-09-08 05:03:23 +02:00
2013-04-30 20:14:01 +02:00
database . update ( TABLE_NAME , contentValues , ID_WHERE , new String [ ] { messageId + "" } ) ;
2012-09-08 05:03:23 +02:00
notifyConversationListeners ( getThreadIdForMessage ( messageId ) ) ;
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2020-08-20 22:50:14 +02:00
@Override
2014-04-01 03:47:24 +02:00
public void markAsInsecure ( long messageId ) {
2015-12-03 20:47:28 +01:00
updateMailboxBitmask ( messageId , Types . SECURE_MESSAGE_BIT , 0 , Optional . < Long > absent ( ) ) ;
2014-04-01 03:47:24 +02:00
}
2018-10-12 01:45:22 +02:00
@Override
2018-05-22 11:13:10 +02:00
public void markUnidentified ( long messageId , boolean unidentified ) {
ContentValues contentValues = new ContentValues ( ) ;
contentValues . put ( UNIDENTIFIED , unidentified ? 1 : 0 ) ;
SQLiteDatabase db = databaseHelper . getWritableDatabase ( ) ;
db . update ( TABLE_NAME , contentValues , ID_WHERE , new String [ ] { String . valueOf ( messageId ) } ) ;
}
2017-10-02 23:54:55 +02:00
@Override
2020-06-07 20:46:03 +02:00
public void markExpireStarted ( long id ) {
markExpireStarted ( id , System . currentTimeMillis ( ) ) ;
2016-08-16 05:23:56 +02:00
}
2017-10-02 23:54:55 +02:00
@Override
2020-06-07 20:46:03 +02:00
public void markExpireStarted ( long id , long startedTimestamp ) {
markExpireStarted ( Collections . singleton ( id ) , startedTimestamp ) ;
}
2016-08-16 05:23:56 +02:00
2020-06-07 20:46:03 +02:00
@Override
public void markExpireStarted ( Collection < Long > ids , long startedAtTimestamp ) {
SQLiteDatabase db = databaseHelper . getWritableDatabase ( ) ;
long threadId = - 1 ;
2016-08-16 05:23:56 +02:00
2020-06-07 20:46:03 +02:00
db . beginTransaction ( ) ;
try {
2020-06-19 16:17:23 +02:00
String query = ID + " = ? AND (" + EXPIRE_STARTED + " = 0 OR " + EXPIRE_STARTED + " > ?)" ;
2020-06-07 20:46:03 +02:00
for ( long id : ids ) {
ContentValues contentValues = new ContentValues ( ) ;
contentValues . put ( EXPIRE_STARTED , startedAtTimestamp ) ;
2020-06-19 16:17:23 +02:00
db . update ( TABLE_NAME , contentValues , query , new String [ ] { String . valueOf ( id ) , String . valueOf ( startedAtTimestamp ) } ) ;
2020-06-07 20:46:03 +02:00
if ( threadId < 0 ) {
threadId = getThreadIdForMessage ( id ) ;
}
}
db . setTransactionSuccessful ( ) ;
} finally {
db . endTransaction ( ) ;
}
DatabaseFactory . getThreadDatabase ( context ) . update ( threadId , false ) ;
2016-08-16 05:23:56 +02:00
notifyConversationListeners ( threadId ) ;
}
2020-08-24 22:40:47 +02:00
@Override
2017-03-09 02:38:55 +01:00
public void markAsNotified ( long id ) {
SQLiteDatabase database = databaseHelper . getWritableDatabase ( ) ;
ContentValues contentValues = new ContentValues ( ) ;
contentValues . put ( NOTIFIED , 1 ) ;
database . update ( TABLE_NAME , contentValues , ID_WHERE , new String [ ] { String . valueOf ( id ) } ) ;
}
2020-08-20 22:50:14 +02:00
@Override
2020-08-04 19:13:59 +02:00
public List < MarkedMessageInfo > setMessagesReadSince ( long threadId , long sinceTimestamp ) {
if ( sinceTimestamp = = - 1 ) {
return setMessagesRead ( THREAD_ID + " = ? AND " + READ + " = 0" , new String [ ] { String . valueOf ( threadId ) } ) ;
} else {
return setMessagesRead ( THREAD_ID + " = ? AND " + READ + " = 0 AND " + DATE_RECEIVED + " <= ?" , new String [ ] { String . valueOf ( threadId ) , String . valueOf ( sinceTimestamp ) } ) ;
}
2017-10-09 03:09:46 +02:00
}
2020-08-24 22:40:47 +02:00
@Override
2019-11-19 17:01:07 +01:00
public List < MarkedMessageInfo > setEntireThreadRead ( long threadId ) {
return setMessagesRead ( THREAD_ID + " = ?" , new String [ ] { String . valueOf ( threadId ) } ) ;
}
2020-08-24 22:40:47 +02:00
@Override
2017-10-09 03:09:46 +02:00
public List < MarkedMessageInfo > setAllMessagesRead ( ) {
return setMessagesRead ( READ + " = 0" , null ) ;
}
private List < MarkedMessageInfo > setMessagesRead ( String where , String [ ] arguments ) {
SQLiteDatabase database = databaseHelper . getWritableDatabase ( ) ;
List < MarkedMessageInfo > result = new LinkedList < > ( ) ;
Cursor cursor = null ;
2016-02-20 02:07:41 +01:00
database . beginTransaction ( ) ;
try {
2020-02-19 23:08:34 +01:00
cursor = database . query ( TABLE_NAME , new String [ ] { ID , RECIPIENT_ID , DATE_SENT , MESSAGE_BOX , EXPIRES_IN , EXPIRE_STARTED , THREAD_ID } , where , arguments , null , null , null ) ;
2016-02-20 02:07:41 +01:00
while ( cursor ! = null & & cursor . moveToNext ( ) ) {
2020-02-19 23:08:34 +01:00
if ( Types . isSecureType ( cursor . getLong ( cursor . getColumnIndex ( MESSAGE_BOX ) ) ) ) {
long threadId = cursor . getLong ( cursor . getColumnIndex ( THREAD_ID ) ) ;
RecipientId recipientId = RecipientId . from ( cursor . getLong ( cursor . getColumnIndex ( RECIPIENT_ID ) ) ) ;
long dateSent = cursor . getLong ( cursor . getColumnIndex ( DATE_SENT ) ) ;
long messageId = cursor . getLong ( cursor . getColumnIndex ( ID ) ) ;
long expiresIn = cursor . getLong ( cursor . getColumnIndex ( EXPIRES_IN ) ) ;
long expireStarted = cursor . getLong ( cursor . getColumnIndex ( EXPIRE_STARTED ) ) ;
SyncMessageId syncMessageId = new SyncMessageId ( recipientId , dateSent ) ;
ExpirationInfo expirationInfo = new ExpirationInfo ( messageId , expiresIn , expireStarted , true ) ;
result . add ( new MarkedMessageInfo ( threadId , syncMessageId , expirationInfo ) ) ;
2016-02-20 02:07:41 +01:00
}
}
ContentValues contentValues = new ContentValues ( ) ;
contentValues . put ( READ , 1 ) ;
2017-10-09 03:09:46 +02:00
database . update ( TABLE_NAME , contentValues , where , arguments ) ;
2016-02-20 02:07:41 +01:00
database . setTransactionSuccessful ( ) ;
} finally {
if ( cursor ! = null ) cursor . close ( ) ;
database . endTransaction ( ) ;
}
return result ;
}
2020-08-24 22:40:47 +02:00
@Override
2018-06-29 00:51:27 +02:00
public List < Pair < Long , Long > > setTimestampRead ( SyncMessageId messageId , long proposedExpireStarted ) {
2016-10-02 21:08:30 +02:00
SQLiteDatabase database = databaseHelper . getWritableDatabase ( ) ;
List < Pair < Long , Long > > expiring = new LinkedList < > ( ) ;
Cursor cursor = null ;
2016-02-20 02:07:41 +01:00
try {
2019-08-07 20:22:51 +02:00
cursor = database . query ( TABLE_NAME , new String [ ] { ID , THREAD_ID , MESSAGE_BOX , EXPIRES_IN , EXPIRE_STARTED , RECIPIENT_ID } , DATE_SENT + " = ?" , new String [ ] { String . valueOf ( messageId . getTimetamp ( ) ) } , null , null , null , null ) ;
2016-02-20 02:07:41 +01:00
while ( cursor . moveToNext ( ) ) {
2019-08-07 20:22:51 +02:00
RecipientId theirRecipientId = RecipientId . from ( cursor . getLong ( cursor . getColumnIndexOrThrow ( RECIPIENT_ID ) ) ) ;
RecipientId ourRecipientId = messageId . getRecipientId ( ) ;
2016-02-20 02:07:41 +01:00
2019-08-07 20:22:51 +02:00
if ( ourRecipientId . equals ( theirRecipientId ) | | Recipient . resolved ( theirRecipientId ) . isGroup ( ) ) {
2018-06-29 00:51:27 +02:00
long id = cursor . getLong ( cursor . getColumnIndexOrThrow ( ID ) ) ;
long threadId = cursor . getLong ( cursor . getColumnIndexOrThrow ( THREAD_ID ) ) ;
long expiresIn = cursor . getLong ( cursor . getColumnIndexOrThrow ( EXPIRES_IN ) ) ;
long expireStarted = cursor . getLong ( cursor . getColumnIndexOrThrow ( EXPIRE_STARTED ) ) ;
expireStarted = expireStarted > 0 ? Math . min ( proposedExpireStarted , expireStarted ) : proposedExpireStarted ;
2016-02-20 02:07:41 +01:00
2017-08-01 17:56:00 +02:00
ContentValues values = new ContentValues ( ) ;
values . put ( READ , 1 ) ;
2016-10-02 21:08:30 +02:00
2017-08-01 17:56:00 +02:00
if ( expiresIn > 0 ) {
values . put ( EXPIRE_STARTED , expireStarted ) ;
expiring . add ( new Pair < > ( id , expiresIn ) ) ;
}
2016-10-02 21:08:30 +02:00
2017-08-01 17:56:00 +02:00
database . update ( TABLE_NAME , values , ID_WHERE , new String [ ] { String . valueOf ( id ) } ) ;
2012-09-08 05:03:23 +02:00
2017-08-01 17:56:00 +02:00
DatabaseFactory . getThreadDatabase ( context ) . updateReadState ( threadId ) ;
DatabaseFactory . getThreadDatabase ( context ) . setLastSeen ( threadId ) ;
notifyConversationListeners ( threadId ) ;
2016-02-20 02:07:41 +01:00
}
}
} finally {
if ( cursor ! = null )
cursor . close ( ) ;
}
2016-10-02 21:08:30 +02:00
return expiring ;
2011-12-20 19:20:44 +01:00
}
2020-08-24 22:40:47 +02:00
@Override
2020-08-13 20:37:15 +02:00
public @Nullable Pair < RecipientId , Long > getOldestUnreadMentionDetails ( long threadId ) {
SQLiteDatabase database = databaseHelper . getReadableDatabase ( ) ;
String [ ] projection = new String [ ] { RECIPIENT_ID , DATE_RECEIVED } ;
String selection = THREAD_ID + " = ? AND " + READ + " = 0 AND " + MENTIONS_SELF + " = 1" ;
String [ ] args = SqlUtil . buildArgs ( threadId ) ;
try ( Cursor cursor = database . query ( TABLE_NAME , projection , selection , args , null , null , DATE_RECEIVED + " ASC" , "1" ) ) {
if ( cursor ! = null & & cursor . moveToFirst ( ) ) {
return new Pair < > ( RecipientId . from ( CursorUtil . requireString ( cursor , RECIPIENT_ID ) ) , CursorUtil . requireLong ( cursor , DATE_RECEIVED ) ) ;
}
}
return null ;
}
2020-08-24 22:40:47 +02:00
@Override
2020-08-13 20:37:15 +02:00
public int getUnreadMentionCount ( long threadId ) {
SQLiteDatabase database = databaseHelper . getReadableDatabase ( ) ;
String [ ] projection = new String [ ] { "COUNT(*)" } ;
String selection = THREAD_ID + " = ? AND " + READ + " = 0 AND " + MENTIONS_SELF + " = 1" ;
String [ ] args = SqlUtil . buildArgs ( threadId ) ;
try ( Cursor cursor = database . query ( TABLE_NAME , projection , selection , args , null , null , null ) ) {
if ( cursor ! = null & & cursor . moveToFirst ( ) ) {
return cursor . getInt ( 0 ) ;
}
}
return 0 ;
}
2019-03-11 05:15:18 +01:00
/ * *
* Trims data related to expired messages . Only intended to be run after a backup restore .
* /
void trimEntriesForExpiredMessages ( ) {
SQLiteDatabase database = databaseHelper . getWritableDatabase ( ) ;
String trimmedCondition = " NOT IN (SELECT " + MmsDatabase . ID + " FROM " + MmsDatabase . TABLE_NAME + ")" ;
database . delete ( GroupReceiptDatabase . TABLE_NAME , GroupReceiptDatabase . MMS_ID + trimmedCondition , null ) ;
String [ ] columns = new String [ ] { AttachmentDatabase . ROW_ID , AttachmentDatabase . UNIQUE_ID } ;
String where = AttachmentDatabase . MMS_ID + trimmedCondition ;
try ( Cursor cursor = database . query ( AttachmentDatabase . TABLE_NAME , columns , where , null , null , null , null ) ) {
while ( cursor ! = null & & cursor . moveToNext ( ) ) {
DatabaseFactory . getAttachmentDatabase ( context ) . deleteAttachment ( new AttachmentId ( cursor . getLong ( 0 ) , cursor . getLong ( 1 ) ) ) ;
}
}
2020-10-08 15:46:26 +02:00
DatabaseFactory . getMentionDatabase ( context ) . deleteAbandonedMentions ( ) ;
2019-03-11 05:15:18 +01:00
try ( Cursor cursor = database . query ( ThreadDatabase . TABLE_NAME , new String [ ] { ThreadDatabase . ID } , ThreadDatabase . EXPIRES_IN + " > 0" , null , null , null , null ) ) {
while ( cursor ! = null & & cursor . moveToNext ( ) ) {
DatabaseFactory . getThreadDatabase ( context ) . update ( cursor . getLong ( 0 ) , false ) ;
}
}
}
2020-08-24 22:40:47 +02:00
@Override
2017-05-09 00:32:59 +02:00
public Optional < MmsNotificationInfo > getNotification ( long messageId ) {
2015-10-24 18:40:04 +02:00
Cursor cursor = null ;
2014-11-04 00:16:04 +01:00
try {
2015-10-24 18:40:04 +02:00
cursor = rawQuery ( RAW_ID_WHERE , new String [ ] { String . valueOf ( messageId ) } ) ;
2014-11-04 00:16:04 +01:00
if ( cursor ! = null & & cursor . moveToNext ( ) ) {
2019-08-07 20:22:51 +02:00
return Optional . of ( new MmsNotificationInfo ( RecipientId . from ( cursor . getLong ( cursor . getColumnIndexOrThrow ( RECIPIENT_ID ) ) ) ,
2017-09-08 20:19:57 +02:00
cursor . getString ( cursor . getColumnIndexOrThrow ( CONTENT_LOCATION ) ) ,
2017-05-09 00:32:59 +02:00
cursor . getString ( cursor . getColumnIndexOrThrow ( TRANSACTION_ID ) ) ,
cursor . getInt ( cursor . getColumnIndexOrThrow ( SUBSCRIPTION_ID ) ) ) ) ;
2014-11-04 00:16:04 +01:00
} else {
return Optional . absent ( ) ;
}
} finally {
if ( cursor ! = null )
cursor . close ( ) ;
}
}
2020-08-24 22:40:47 +02:00
@Override
2018-01-25 04:17:44 +01:00
public OutgoingMediaMessage getOutgoingMessage ( long messageId )
2014-11-08 20:35:58 +01:00
throws MmsException , NoSuchMessageException
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
{
2015-10-13 03:25:05 +02:00
AttachmentDatabase attachmentDatabase = DatabaseFactory . getAttachmentDatabase ( context ) ;
2020-08-05 22:45:52 +02:00
MentionDatabase mentionDatabase = DatabaseFactory . getMentionDatabase ( context ) ;
2015-10-13 03:25:05 +02:00
Cursor cursor = null ;
2012-09-08 05:03:23 +02:00
2011-12-20 19:20:44 +01:00
try {
2015-10-24 18:40:04 +02:00
cursor = rawQuery ( RAW_ID_WHERE , new String [ ] { String . valueOf ( messageId ) } ) ;
2012-09-08 05:03:23 +02:00
2014-11-08 20:35:58 +01:00
if ( cursor ! = null & & cursor . moveToNext ( ) ) {
2018-02-07 23:01:37 +01:00
List < DatabaseAttachment > associatedAttachments = attachmentDatabase . getAttachmentsForMessage ( messageId ) ;
2020-08-05 22:45:52 +02:00
List < Mention > mentions = mentionDatabase . getMentionsForMessage ( messageId ) ;
2018-02-07 23:01:37 +01:00
2018-04-27 02:03:54 +02:00
long outboxType = cursor . getLong ( cursor . getColumnIndexOrThrow ( MESSAGE_BOX ) ) ;
String body = cursor . getString ( cursor . getColumnIndexOrThrow ( BODY ) ) ;
long timestamp = cursor . getLong ( cursor . getColumnIndexOrThrow ( NORMALIZED_DATE_SENT ) ) ;
int subscriptionId = cursor . getInt ( cursor . getColumnIndexOrThrow ( SUBSCRIPTION_ID ) ) ;
long expiresIn = cursor . getLong ( cursor . getColumnIndexOrThrow ( EXPIRES_IN ) ) ;
2019-08-01 01:33:56 +02:00
boolean viewOnce = cursor . getLong ( cursor . getColumnIndexOrThrow ( VIEW_ONCE ) ) = = 1 ;
2019-08-07 20:22:51 +02:00
long recipientId = cursor . getLong ( cursor . getColumnIndexOrThrow ( RECIPIENT_ID ) ) ;
2018-04-27 02:03:54 +02:00
long threadId = cursor . getLong ( cursor . getColumnIndexOrThrow ( THREAD_ID ) ) ;
int distributionType = DatabaseFactory . getThreadDatabase ( context ) . getDistributionType ( threadId ) ;
2018-05-22 11:13:10 +02:00
String mismatchDocument = cursor . getString ( cursor . getColumnIndexOrThrow ( MmsDatabase . MISMATCHED_IDENTITIES ) ) ;
String networkDocument = cursor . getString ( cursor . getColumnIndexOrThrow ( MmsDatabase . NETWORK_FAILURE ) ) ;
2018-04-27 02:03:54 +02:00
2019-01-15 09:41:05 +01:00
long quoteId = cursor . getLong ( cursor . getColumnIndexOrThrow ( QUOTE_ID ) ) ;
2019-10-16 05:10:15 +02:00
long quoteAuthor = cursor . getLong ( cursor . getColumnIndexOrThrow ( QUOTE_AUTHOR ) ) ;
2019-01-15 09:41:05 +01:00
String quoteText = cursor . getString ( cursor . getColumnIndexOrThrow ( QUOTE_BODY ) ) ;
boolean quoteMissing = cursor . getInt ( cursor . getColumnIndexOrThrow ( QUOTE_MISSING ) ) = = 1 ;
List < Attachment > quoteAttachments = Stream . of ( associatedAttachments ) . filter ( Attachment : : isQuote ) . map ( a - > ( Attachment ) a ) . toList ( ) ;
2020-08-20 22:50:14 +02:00
List < Mention > quoteMentions = parseQuoteMentions ( context , cursor ) ;
2019-01-15 09:41:05 +01:00
List < Contact > contacts = getSharedContacts ( cursor , associatedAttachments ) ;
Set < Attachment > contactAttachments = new HashSet < > ( Stream . of ( contacts ) . map ( Contact : : getAvatarAttachment ) . filter ( a - > a ! = null ) . toList ( ) ) ;
List < LinkPreview > previews = getLinkPreviews ( cursor , associatedAttachments ) ;
Set < Attachment > previewAttachments = Stream . of ( previews ) . filter ( lp - > lp . getThumbnail ( ) . isPresent ( ) ) . map ( lp - > lp . getThumbnail ( ) . get ( ) ) . collect ( Collectors . toSet ( ) ) ;
List < Attachment > attachments = Stream . of ( associatedAttachments ) . filterNot ( Attachment : : isQuote )
. filterNot ( contactAttachments : : contains )
. filterNot ( previewAttachments : : contains )
2020-01-08 21:56:51 +01:00
. sorted ( new DatabaseAttachment . DisplayOrderComparator ( ) )
2019-01-15 09:41:05 +01:00
. map ( a - > ( Attachment ) a ) . toList ( ) ;
2017-08-01 17:56:00 +02:00
2019-08-07 20:22:51 +02:00
Recipient recipient = Recipient . resolved ( RecipientId . from ( recipientId ) ) ;
2018-05-22 11:13:10 +02:00
List < NetworkFailure > networkFailures = new LinkedList < > ( ) ;
List < IdentityKeyMismatch > mismatches = new LinkedList < > ( ) ;
QuoteModel quote = null ;
2018-02-07 23:01:37 +01:00
2019-10-16 05:10:15 +02:00
if ( quoteId > 0 & & quoteAuthor > 0 & & ( ! TextUtils . isEmpty ( quoteText ) | | ! quoteAttachments . isEmpty ( ) ) ) {
2020-08-05 22:45:52 +02:00
quote = new QuoteModel ( quoteId , RecipientId . from ( quoteAuthor ) , quoteText , quoteMissing , quoteAttachments , quoteMentions ) ;
2018-02-07 23:01:37 +01:00
}
2015-10-13 03:25:05 +02:00
2018-05-22 11:13:10 +02:00
if ( ! TextUtils . isEmpty ( mismatchDocument ) ) {
try {
mismatches = JsonUtils . fromJson ( mismatchDocument , IdentityKeyMismatchList . class ) . getList ( ) ;
} catch ( IOException e ) {
Log . w ( TAG , e ) ;
}
}
if ( ! TextUtils . isEmpty ( networkDocument ) ) {
try {
networkFailures = JsonUtils . fromJson ( networkDocument , NetworkFailureList . class ) . getList ( ) ;
} catch ( IOException e ) {
Log . w ( TAG , e ) ;
}
}
2015-10-13 03:25:05 +02:00
if ( body ! = null & & ( Types . isGroupQuit ( outboxType ) | | Types . isGroupUpdate ( outboxType ) ) ) {
2020-08-05 22:45:52 +02:00
return new OutgoingGroupUpdateMessage ( recipient , new MessageGroupContext ( body , Types . isGroupV2 ( outboxType ) ) , attachments , timestamp , 0 , false , quote , contacts , previews , mentions ) ;
2016-08-16 05:23:56 +02:00
} else if ( Types . isExpirationTimerUpdate ( outboxType ) ) {
2017-08-01 17:56:00 +02:00
return new OutgoingExpirationUpdateMessage ( recipient , timestamp , expiresIn ) ;
2015-10-13 03:25:05 +02:00
}
2013-05-05 21:51:36 +02:00
2020-08-05 22:45:52 +02:00
OutgoingMediaMessage message = new OutgoingMediaMessage ( recipient , body , attachments , timestamp , subscriptionId , expiresIn , viewOnce , distributionType , quote , contacts , previews , mentions , networkFailures , mismatches ) ;
2017-08-01 17:56:00 +02:00
2015-10-13 03:25:05 +02:00
if ( Types . isSecureType ( outboxType ) ) {
return new OutgoingSecureMediaMessage ( message ) ;
2013-05-05 21:51:36 +02:00
}
2015-10-13 03:25:05 +02:00
return message ;
2011-12-20 19:20:44 +01:00
}
2014-11-08 20:35:58 +01:00
throw new NoSuchMessageException ( "No record found for id: " + messageId ) ;
2015-10-13 03:25:05 +02:00
} catch ( IOException e ) {
throw new MmsException ( e ) ;
2011-12-20 19:20:44 +01:00
} finally {
if ( cursor ! = null )
cursor . close ( ) ;
2012-09-08 05:03:23 +02:00
}
2011-12-20 19:20:44 +01:00
}
2020-08-20 22:50:14 +02:00
private static List < Contact > getSharedContacts ( @NonNull Cursor cursor , @NonNull List < DatabaseAttachment > attachments ) {
2018-04-27 02:03:54 +02:00
String serializedContacts = cursor . getString ( cursor . getColumnIndexOrThrow ( SHARED_CONTACTS ) ) ;
if ( TextUtils . isEmpty ( serializedContacts ) ) {
return Collections . emptyList ( ) ;
}
Map < AttachmentId , DatabaseAttachment > attachmentIdMap = new HashMap < > ( ) ;
for ( DatabaseAttachment attachment : attachments ) {
attachmentIdMap . put ( attachment . getAttachmentId ( ) , attachment ) ;
}
try {
List < Contact > contacts = new LinkedList < > ( ) ;
JSONArray jsonContacts = new JSONArray ( serializedContacts ) ;
for ( int i = 0 ; i < jsonContacts . length ( ) ; i + + ) {
2019-01-15 09:41:05 +01:00
Contact contact = Contact . deserialize ( jsonContacts . getJSONObject ( i ) . toString ( ) ) ;
2018-04-27 02:03:54 +02:00
if ( contact . getAvatar ( ) ! = null & & contact . getAvatar ( ) . getAttachmentId ( ) ! = null ) {
DatabaseAttachment attachment = attachmentIdMap . get ( contact . getAvatar ( ) . getAttachmentId ( ) ) ;
Avatar updatedAvatar = new Avatar ( contact . getAvatar ( ) . getAttachmentId ( ) ,
attachment ,
contact . getAvatar ( ) . isProfile ( ) ) ;
contacts . add ( new Contact ( contact , updatedAvatar ) ) ;
} else {
contacts . add ( contact ) ;
}
}
return contacts ;
} catch ( JSONException | IOException e ) {
Log . w ( TAG , "Failed to parse shared contacts." , e ) ;
}
return Collections . emptyList ( ) ;
}
2020-08-20 22:50:14 +02:00
private static List < LinkPreview > getLinkPreviews ( @NonNull Cursor cursor , @NonNull List < DatabaseAttachment > attachments ) {
2019-01-15 09:41:05 +01:00
String serializedPreviews = cursor . getString ( cursor . getColumnIndexOrThrow ( LINK_PREVIEWS ) ) ;
if ( TextUtils . isEmpty ( serializedPreviews ) ) {
return Collections . emptyList ( ) ;
}
Map < AttachmentId , DatabaseAttachment > attachmentIdMap = new HashMap < > ( ) ;
for ( DatabaseAttachment attachment : attachments ) {
attachmentIdMap . put ( attachment . getAttachmentId ( ) , attachment ) ;
}
try {
List < LinkPreview > previews = new LinkedList < > ( ) ;
JSONArray jsonPreviews = new JSONArray ( serializedPreviews ) ;
for ( int i = 0 ; i < jsonPreviews . length ( ) ; i + + ) {
LinkPreview preview = LinkPreview . deserialize ( jsonPreviews . getJSONObject ( i ) . toString ( ) ) ;
if ( preview . getAttachmentId ( ) ! = null ) {
DatabaseAttachment attachment = attachmentIdMap . get ( preview . getAttachmentId ( ) ) ;
if ( attachment ! = null ) {
2020-08-26 22:03:52 +02:00
previews . add ( new LinkPreview ( preview . getUrl ( ) , preview . getTitle ( ) , preview . getDescription ( ) , preview . getDate ( ) , attachment ) ) ;
2019-01-15 09:41:05 +01:00
}
} else {
previews . add ( preview ) ;
}
}
return previews ;
} catch ( JSONException | IOException e ) {
Log . w ( TAG , "Failed to parse shared contacts." , e ) ;
}
return Collections . emptyList ( ) ;
}
2018-01-25 04:17:44 +01:00
private Optional < InsertResult > insertMessageInbox ( IncomingMediaMessage retrieved ,
2017-01-22 22:52:36 +01:00
String contentLocation ,
long threadId , long mailbox )
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
throws MmsException
{
2013-07-19 02:42:45 +02:00
if ( threadId = = - 1 | | retrieved . isGroupMessage ( ) ) {
2019-08-07 20:22:51 +02:00
threadId = getThreadIdFor ( retrieved ) ;
2013-04-26 03:59:49 +02:00
}
2015-10-13 03:25:05 +02:00
ContentValues contentValues = new ContentValues ( ) ;
contentValues . put ( DATE_SENT , retrieved . getSentTimeMillis ( ) ) ;
2020-04-14 01:02:50 +02:00
contentValues . put ( DATE_SERVER , retrieved . getServerTimeMillis ( ) ) ;
2019-08-07 20:22:51 +02:00
contentValues . put ( RECIPIENT_ID , retrieved . getFrom ( ) . serialize ( ) ) ;
2015-10-13 03:25:05 +02:00
2011-12-20 19:20:44 +01:00
contentValues . put ( MESSAGE_BOX , mailbox ) ;
2015-10-13 03:25:05 +02:00
contentValues . put ( MESSAGE_TYPE , PduHeaders . MESSAGE_TYPE_RETRIEVE_CONF ) ;
2011-12-20 19:20:44 +01:00
contentValues . put ( THREAD_ID , threadId ) ;
contentValues . put ( CONTENT_LOCATION , contentLocation ) ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
contentValues . put ( STATUS , Status . DOWNLOAD_INITIALIZED ) ;
2020-05-11 05:15:13 +02:00
contentValues . put ( DATE_RECEIVED , retrieved . isPushMessage ( ) ? System . currentTimeMillis ( ) : generatePduCompatTimestamp ( ) ) ;
2015-10-24 18:40:04 +02:00
contentValues . put ( PART_COUNT , retrieved . getAttachments ( ) . size ( ) ) ;
2016-02-06 01:10:33 +01:00
contentValues . put ( SUBSCRIPTION_ID , retrieved . getSubscriptionId ( ) ) ;
2016-08-16 05:23:56 +02:00
contentValues . put ( EXPIRES_IN , retrieved . getExpiresIn ( ) ) ;
2019-08-01 01:33:56 +02:00
contentValues . put ( VIEW_ONCE , retrieved . isViewOnce ( ) ? 1 : 0 ) ;
2016-10-10 19:00:11 +02:00
contentValues . put ( READ , retrieved . isExpirationUpdate ( ) ? 1 : 0 ) ;
2018-05-22 11:13:10 +02:00
contentValues . put ( UNIDENTIFIED , retrieved . isUnidentified ( ) ) ;
2013-01-06 22:13:14 +01:00
2013-07-19 02:42:45 +02:00
if ( ! contentValues . containsKey ( DATE_SENT ) ) {
2013-01-06 22:13:14 +01:00
contentValues . put ( DATE_SENT , contentValues . getAsLong ( DATE_RECEIVED ) ) ;
2013-07-19 02:42:45 +02:00
}
2012-09-08 05:03:23 +02:00
2018-02-07 23:01:37 +01:00
List < Attachment > quoteAttachments = new LinkedList < > ( ) ;
if ( retrieved . getQuote ( ) ! = null ) {
contentValues . put ( QUOTE_ID , retrieved . getQuote ( ) . getId ( ) ) ;
2020-08-05 22:45:52 +02:00
contentValues . put ( QUOTE_BODY , retrieved . getQuote ( ) . getText ( ) . toString ( ) ) ;
2018-02-07 23:01:37 +01:00
contentValues . put ( QUOTE_AUTHOR , retrieved . getQuote ( ) . getAuthor ( ) . serialize ( ) ) ;
2018-08-11 15:55:52 +02:00
contentValues . put ( QUOTE_MISSING , retrieved . getQuote ( ) . isOriginalMissing ( ) ? 1 : 0 ) ;
2018-02-07 23:01:37 +01:00
2020-08-05 22:45:52 +02:00
BodyRangeList mentionsList = MentionUtil . mentionsToBodyRangeList ( retrieved . getQuote ( ) . getMentions ( ) ) ;
if ( mentionsList ! = null ) {
contentValues . put ( QUOTE_MENTIONS , mentionsList . toByteArray ( ) ) ;
}
2018-02-07 23:01:37 +01:00
quoteAttachments = retrieved . getQuote ( ) . getAttachments ( ) ;
}
2017-01-22 22:52:36 +01:00
if ( retrieved . isPushMessage ( ) & & isDuplicate ( retrieved , threadId ) ) {
Log . w ( TAG , "Ignoring duplicate media message (" + retrieved . getSentTimeMillis ( ) + ")" ) ;
return Optional . absent ( ) ;
}
2020-08-05 22:45:52 +02:00
long messageId = insertMediaMessage ( threadId , retrieved . getBody ( ) , retrieved . getAttachments ( ) , quoteAttachments , retrieved . getSharedContacts ( ) , retrieved . getLinkPreviews ( ) , retrieved . getMentions ( ) , contentValues , null ) ;
2013-12-07 20:00:20 +01:00
2016-08-16 05:23:56 +02:00
if ( ! Types . isExpirationTimerUpdate ( mailbox ) ) {
2017-11-14 03:01:05 +01:00
DatabaseFactory . getThreadDatabase ( context ) . incrementUnread ( threadId , 1 ) ;
2016-08-16 05:23:56 +02:00
DatabaseFactory . getThreadDatabase ( context ) . update ( threadId , true ) ;
}
2013-05-05 22:14:23 +02:00
notifyConversationListeners ( threadId ) ;
2019-10-15 21:47:54 +02:00
ApplicationDependencies . getJobManager ( ) . add ( new TrimThreadJob ( threadId ) ) ;
2013-04-26 20:23:43 +02:00
2017-01-22 22:52:36 +01:00
return Optional . of ( new InsertResult ( messageId , threadId ) ) ;
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2020-08-24 22:40:47 +02:00
@Override
2018-01-25 04:17:44 +01:00
public Optional < InsertResult > insertMessageInbox ( IncomingMediaMessage retrieved ,
2017-01-22 22:52:36 +01:00
String contentLocation , long threadId )
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
throws MmsException
{
2015-07-07 02:36:49 +02:00
long type = Types . BASE_INBOX_TYPE ;
2012-09-08 05:03:23 +02:00
2015-07-07 02:36:49 +02:00
if ( retrieved . isPushMessage ( ) ) {
type | = Types . PUSH_MESSAGE_BIT ;
}
2016-08-16 05:23:56 +02:00
if ( retrieved . isExpirationUpdate ( ) ) {
type | = Types . EXPIRATION_TIMER_UPDATE_BIT ;
}
2018-01-25 04:17:44 +01:00
return insertMessageInbox ( retrieved , contentLocation , threadId , type ) ;
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2020-08-24 22:40:47 +02:00
@Override
2018-01-25 04:17:44 +01:00
public Optional < InsertResult > insertSecureDecryptedMessageInbox ( IncomingMediaMessage retrieved , long threadId )
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
throws MmsException
{
2015-07-07 02:36:49 +02:00
long type = Types . BASE_INBOX_TYPE | Types . SECURE_MESSAGE_BIT ;
if ( retrieved . isPushMessage ( ) ) {
type | = Types . PUSH_MESSAGE_BIT ;
}
2016-08-16 05:23:56 +02:00
if ( retrieved . isExpirationUpdate ( ) ) {
type | = Types . EXPIRATION_TIMER_UPDATE_BIT ;
}
2018-01-25 04:17:44 +01:00
return insertMessageInbox ( retrieved , "" , threadId , type ) ;
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2016-02-06 01:10:33 +01:00
public Pair < Long , Long > insertMessageInbox ( @NonNull NotificationInd notification , int subscriptionId ) {
2017-08-01 17:56:00 +02:00
SQLiteDatabase db = databaseHelper . getWritableDatabase ( ) ;
2015-10-13 03:25:05 +02:00
long threadId = getThreadIdFor ( notification ) ;
ContentValues contentValues = new ContentValues ( ) ;
ContentValuesBuilder contentBuilder = new ContentValuesBuilder ( contentValues ) ;
2018-08-02 15:25:33 +02:00
Log . i ( TAG , "Message received type: " + notification . getMessageType ( ) ) ;
2015-03-27 18:26:17 +01:00
2017-05-09 00:32:59 +02:00
contentBuilder . add ( CONTENT_LOCATION , notification . getContentLocation ( ) ) ;
contentBuilder . add ( DATE_SENT , System . currentTimeMillis ( ) ) ;
contentBuilder . add ( EXPIRY , notification . getExpiry ( ) ) ;
contentBuilder . add ( MESSAGE_SIZE , notification . getMessageSize ( ) ) ;
contentBuilder . add ( TRANSACTION_ID , notification . getTransactionId ( ) ) ;
contentBuilder . add ( MESSAGE_TYPE , notification . getMessageType ( ) ) ;
2015-10-13 03:25:05 +02:00
2017-05-09 00:32:59 +02:00
if ( notification . getFrom ( ) ! = null ) {
2019-08-07 20:22:51 +02:00
Recipient recipient = Recipient . external ( context , Util . toIsoString ( notification . getFrom ( ) . getTextString ( ) ) ) ;
contentValues . put ( RECIPIENT_ID , recipient . getId ( ) . serialize ( ) ) ;
2019-10-15 16:07:20 +02:00
} else {
contentValues . put ( RECIPIENT_ID , RecipientId . UNKNOWN . serialize ( ) ) ;
2015-10-13 03:25:05 +02:00
}
2015-03-27 18:26:17 +01:00
contentValues . put ( MESSAGE_BOX , Types . BASE_INBOX_TYPE ) ;
contentValues . put ( THREAD_ID , threadId ) ;
contentValues . put ( STATUS , Status . DOWNLOAD_INITIALIZED ) ;
2015-08-04 22:37:22 +02:00
contentValues . put ( DATE_RECEIVED , generatePduCompatTimestamp ( ) ) ;
2015-03-27 18:26:17 +01:00
contentValues . put ( READ , Util . isDefaultSmsProvider ( context ) ? 0 : 1 ) ;
2016-02-06 01:10:33 +01:00
contentValues . put ( SUBSCRIPTION_ID , subscriptionId ) ;
2015-03-27 18:26:17 +01:00
if ( ! contentValues . containsKey ( DATE_SENT ) )
contentValues . put ( DATE_SENT , contentValues . getAsLong ( DATE_RECEIVED ) ) ;
long messageId = db . insert ( TABLE_NAME , null , contentValues ) ;
2017-01-29 22:16:10 +01:00
2015-03-27 18:26:17 +01:00
return new Pair < > ( messageId , threadId ) ;
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2020-08-24 22:40:47 +02:00
@Override
2013-04-26 20:23:43 +02:00
public void markIncomingNotificationReceived ( long threadId ) {
notifyConversationListeners ( threadId ) ;
2015-11-24 00:07:41 +01:00
DatabaseFactory . getThreadDatabase ( context ) . update ( threadId , true ) ;
2013-12-07 20:00:20 +01:00
2014-01-07 03:52:18 +01:00
if ( org . thoughtcrime . securesms . util . Util . isDefaultSmsProvider ( context ) ) {
2017-11-14 03:01:05 +01:00
DatabaseFactory . getThreadDatabase ( context ) . incrementUnread ( threadId , 1 ) ;
2013-12-07 20:00:20 +01:00
}
2019-10-15 21:47:54 +02:00
ApplicationDependencies . getJobManager ( ) . add ( new TrimThreadJob ( threadId ) ) ;
2013-04-26 20:23:43 +02:00
}
2020-08-24 22:40:47 +02:00
@Override
2018-01-25 04:17:44 +01:00
public long insertMessageOutbox ( @NonNull OutgoingMediaMessage message ,
2020-08-24 22:40:47 +02:00
long threadId ,
boolean forceSms ,
2017-10-02 23:54:55 +02:00
@Nullable SmsDatabase . InsertListener insertListener )
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
throws MmsException
2019-05-29 23:21:00 +02:00
{
return insertMessageOutbox ( message , threadId , forceSms , GroupReceiptDatabase . STATUS_UNDELIVERED , insertListener ) ;
}
2020-08-24 22:40:47 +02:00
@Override
2019-05-29 23:21:00 +02:00
public long insertMessageOutbox ( @NonNull OutgoingMediaMessage message ,
long threadId , boolean forceSms , int defaultReceiptStatus ,
@Nullable SmsDatabase . InsertListener insertListener )
throws MmsException
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
{
2016-12-21 18:49:01 +01:00
long type = Types . BASE_SENDING_TYPE ;
2015-07-07 02:36:49 +02:00
2016-12-21 18:49:01 +01:00
if ( message . isSecure ( ) ) type | = ( Types . SECURE_MESSAGE_BIT | Types . PUSH_MESSAGE_BIT ) ;
2014-06-12 00:31:59 +02:00
if ( forceSms ) type | = Types . MESSAGE_FORCE_SMS_BIT ;
2012-09-08 05:03:23 +02:00
2014-02-20 06:06:54 +01:00
if ( message . isGroup ( ) ) {
2020-05-06 18:42:54 +02:00
OutgoingGroupUpdateMessage outgoingGroupUpdateMessage = ( OutgoingGroupUpdateMessage ) message ;
if ( outgoingGroupUpdateMessage . isV2Group ( ) ) {
2020-05-19 20:41:48 +02:00
type | = Types . GROUP_V2_BIT | Types . GROUP_UPDATE_BIT ;
2020-04-09 23:02:13 +02:00
} else {
2020-05-06 18:42:54 +02:00
MessageGroupContext . GroupV1Properties properties = outgoingGroupUpdateMessage . requireGroupV1Properties ( ) ;
2020-04-09 23:02:13 +02:00
if ( properties . isUpdate ( ) ) type | = Types . GROUP_UPDATE_BIT ;
else if ( properties . isQuit ( ) ) type | = Types . GROUP_QUIT_BIT ;
}
2014-02-20 06:06:54 +01:00
}
2016-08-16 05:23:56 +02:00
if ( message . isExpirationUpdate ( ) ) {
type | = Types . EXPIRATION_TIMER_UPDATE_BIT ;
}
2019-08-07 20:22:51 +02:00
Map < RecipientId , Long > earlyDeliveryReceipts = earlyDeliveryReceiptCache . remove ( message . getSentTimeMillis ( ) ) ;
2017-10-02 23:54:55 +02:00
2015-10-13 03:25:05 +02:00
ContentValues contentValues = new ContentValues ( ) ;
contentValues . put ( DATE_SENT , message . getSentTimeMillis ( ) ) ;
contentValues . put ( MESSAGE_TYPE , PduHeaders . MESSAGE_TYPE_SEND_REQ ) ;
2014-02-20 06:06:54 +01:00
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
contentValues . put ( MESSAGE_BOX , type ) ;
2011-12-20 19:20:44 +01:00
contentValues . put ( THREAD_ID , threadId ) ;
contentValues . put ( READ , 1 ) ;
2015-10-16 19:07:50 +02:00
contentValues . put ( DATE_RECEIVED , System . currentTimeMillis ( ) ) ;
2016-02-06 01:10:33 +01:00
contentValues . put ( SUBSCRIPTION_ID , message . getSubscriptionId ( ) ) ;
2016-08-16 05:23:56 +02:00
contentValues . put ( EXPIRES_IN , message . getExpiresIn ( ) ) ;
2019-08-01 01:33:56 +02:00
contentValues . put ( VIEW_ONCE , message . isViewOnce ( ) ) ;
2019-08-07 20:22:51 +02:00
contentValues . put ( RECIPIENT_ID , message . getRecipient ( ) . getId ( ) . serialize ( ) ) ;
2017-10-02 23:54:55 +02:00
contentValues . put ( DELIVERY_RECEIPT_COUNT , Stream . of ( earlyDeliveryReceipts . values ( ) ) . mapToLong ( Long : : longValue ) . sum ( ) ) ;
2015-12-09 05:32:54 +01:00
2018-02-07 23:01:37 +01:00
List < Attachment > quoteAttachments = new LinkedList < > ( ) ;
if ( message . getOutgoingQuote ( ) ! = null ) {
2020-08-05 22:45:52 +02:00
MentionUtil . UpdatedBodyAndMentions updated = MentionUtil . updateBodyAndMentionsWithPlaceholders ( message . getOutgoingQuote ( ) . getText ( ) , message . getOutgoingQuote ( ) . getMentions ( ) ) ;
2018-02-07 23:01:37 +01:00
contentValues . put ( QUOTE_ID , message . getOutgoingQuote ( ) . getId ( ) ) ;
contentValues . put ( QUOTE_AUTHOR , message . getOutgoingQuote ( ) . getAuthor ( ) . serialize ( ) ) ;
2020-08-05 22:45:52 +02:00
contentValues . put ( QUOTE_BODY , updated . getBodyAsString ( ) ) ;
2018-08-11 15:55:52 +02:00
contentValues . put ( QUOTE_MISSING , message . getOutgoingQuote ( ) . isOriginalMissing ( ) ? 1 : 0 ) ;
2018-02-07 23:01:37 +01:00
2020-08-05 22:45:52 +02:00
BodyRangeList mentionsList = MentionUtil . mentionsToBodyRangeList ( updated . getMentions ( ) ) ;
if ( mentionsList ! = null ) {
contentValues . put ( QUOTE_MENTIONS , mentionsList . toByteArray ( ) ) ;
}
2018-02-07 23:01:37 +01:00
quoteAttachments . addAll ( message . getOutgoingQuote ( ) . getAttachments ( ) ) ;
}
2020-08-05 22:45:52 +02:00
MentionUtil . UpdatedBodyAndMentions updatedBodyAndMentions = MentionUtil . updateBodyAndMentionsWithPlaceholders ( message . getBody ( ) , message . getMentions ( ) ) ;
long messageId = insertMediaMessage ( threadId , updatedBodyAndMentions . getBodyAsString ( ) , message . getAttachments ( ) , quoteAttachments , message . getSharedContacts ( ) , message . getLinkPreviews ( ) , updatedBodyAndMentions . getMentions ( ) , contentValues , insertListener ) ;
2017-04-23 01:29:26 +02:00
2019-09-07 05:40:06 +02:00
if ( message . getRecipient ( ) . isGroup ( ) ) {
2020-05-06 18:42:54 +02:00
OutgoingGroupUpdateMessage outgoingGroupUpdateMessage = ( message instanceof OutgoingGroupUpdateMessage ) ? ( OutgoingGroupUpdateMessage ) message : null ;
2020-04-09 23:02:13 +02:00
2020-05-19 20:41:48 +02:00
GroupReceiptDatabase receiptDatabase = DatabaseFactory . getGroupReceiptDatabase ( context ) ;
Set < RecipientId > members = new HashSet < > ( ) ;
2020-04-09 23:02:13 +02:00
2020-05-06 18:42:54 +02:00
if ( outgoingGroupUpdateMessage ! = null & & outgoingGroupUpdateMessage . isV2Group ( ) ) {
MessageGroupContext . GroupV2Properties groupV2Properties = outgoingGroupUpdateMessage . requireGroupV2Properties ( ) ;
2020-05-19 20:41:48 +02:00
members . addAll ( Stream . of ( groupV2Properties . getAllActivePendingAndRemovedMembers ( ) )
. distinct ( )
. map ( uuid - > RecipientId . from ( uuid , null ) )
. toList ( ) ) ;
2020-04-09 23:02:13 +02:00
members . remove ( Recipient . self ( ) . getId ( ) ) ;
} else {
members . addAll ( Stream . of ( DatabaseFactory . getGroupDatabase ( context ) . getGroupMembers ( message . getRecipient ( ) . requireGroupId ( ) , GroupDatabase . MemberSet . FULL_MEMBERS_EXCLUDING_SELF ) ) . map ( Recipient : : getId ) . toList ( ) ) ;
}
2017-09-30 17:45:45 +02:00
2020-04-09 23:02:13 +02:00
receiptDatabase . insert ( members , messageId , defaultReceiptStatus , message . getSentTimeMillis ( ) ) ;
2017-10-02 23:54:55 +02:00
2019-08-07 20:22:51 +02:00
for ( RecipientId recipientId : earlyDeliveryReceipts . keySet ( ) ) receiptDatabase . update ( recipientId , messageId , GroupReceiptDatabase . STATUS_DELIVERED , - 1 ) ;
2017-09-30 17:45:45 +02:00
}
2017-02-26 19:49:48 +01:00
DatabaseFactory . getThreadDatabase ( context ) . setLastSeen ( threadId ) ;
2017-08-19 02:28:56 +02:00
DatabaseFactory . getThreadDatabase ( context ) . setHasSent ( threadId , true ) ;
2019-10-15 21:47:54 +02:00
ApplicationDependencies . getJobManager ( ) . add ( new TrimThreadJob ( threadId ) ) ;
2013-01-10 06:06:56 +01:00
2011-12-20 19:20:44 +01:00
return messageId ;
}
2012-09-08 05:03:23 +02:00
2020-08-05 22:45:52 +02:00
private long insertMediaMessage ( long threadId ,
@Nullable String body ,
2015-10-13 03:25:05 +02:00
@NonNull List < Attachment > attachments ,
2018-02-07 23:01:37 +01:00
@NonNull List < Attachment > quoteAttachments ,
2018-04-27 02:03:54 +02:00
@NonNull List < Contact > sharedContacts ,
2019-01-15 09:41:05 +01:00
@NonNull List < LinkPreview > linkPreviews ,
2020-08-05 22:45:52 +02:00
@NonNull List < Mention > mentions ,
2017-05-25 17:40:43 +02:00
@NonNull ContentValues contentValues ,
@Nullable SmsDatabase . InsertListener insertListener )
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
throws MmsException
{
2020-08-05 22:45:52 +02:00
SQLiteDatabase db = databaseHelper . getWritableDatabase ( ) ;
AttachmentDatabase partsDatabase = DatabaseFactory . getAttachmentDatabase ( context ) ;
MentionDatabase mentionDatabase = DatabaseFactory . getMentionDatabase ( context ) ;
boolean mentionsSelf = Stream . of ( mentions ) . filter ( m - > Recipient . resolved ( m . getRecipientId ( ) ) . isLocalNumber ( ) ) . findFirst ( ) . isPresent ( ) ;
2013-04-26 20:23:43 +02:00
2018-04-27 02:03:54 +02:00
List < Attachment > allAttachments = new LinkedList < > ( ) ;
List < Attachment > contactAttachments = Stream . of ( sharedContacts ) . map ( Contact : : getAvatarAttachment ) . filter ( a - > a ! = null ) . toList ( ) ;
2019-01-15 09:41:05 +01:00
List < Attachment > previewAttachments = Stream . of ( linkPreviews ) . filter ( lp - > lp . getThumbnail ( ) . isPresent ( ) ) . map ( lp - > lp . getThumbnail ( ) . get ( ) ) . toList ( ) ;
2018-04-27 02:03:54 +02:00
allAttachments . addAll ( attachments ) ;
allAttachments . addAll ( contactAttachments ) ;
2019-01-15 09:41:05 +01:00
allAttachments . addAll ( previewAttachments ) ;
2018-04-27 02:03:54 +02:00
2018-01-25 04:17:44 +01:00
contentValues . put ( BODY , body ) ;
2018-04-27 02:03:54 +02:00
contentValues . put ( PART_COUNT , allAttachments . size ( ) ) ;
2020-08-05 22:45:52 +02:00
contentValues . put ( MENTIONS_SELF , mentionsSelf ? 1 : 0 ) ;
2013-04-26 20:23:43 +02:00
2015-04-28 07:16:37 +02:00
db . beginTransaction ( ) ;
try {
long messageId = db . insert ( TABLE_NAME , null , contentValues ) ;
2011-12-20 19:20:44 +01:00
2020-08-05 22:45:52 +02:00
mentionDatabase . insert ( threadId , messageId , mentions ) ;
2018-04-27 02:03:54 +02:00
Map < Attachment , AttachmentId > insertedAttachments = partsDatabase . insertAttachmentsForMessage ( messageId , allAttachments , quoteAttachments ) ;
2019-01-15 09:41:05 +01:00
String serializedContacts = getSerializedSharedContacts ( insertedAttachments , sharedContacts ) ;
String serializedPreviews = getSerializedLinkPreviews ( insertedAttachments , linkPreviews ) ;
2018-04-27 02:03:54 +02:00
if ( ! TextUtils . isEmpty ( serializedContacts ) ) {
ContentValues contactValues = new ContentValues ( ) ;
contactValues . put ( SHARED_CONTACTS , serializedContacts ) ;
SQLiteDatabase database = databaseHelper . getReadableDatabase ( ) ;
int rows = database . update ( TABLE_NAME , contactValues , ID + " = ?" , new String [ ] { String . valueOf ( messageId ) } ) ;
if ( rows < = 0 ) {
Log . w ( TAG , "Failed to update message with shared contact data." ) ;
}
}
2011-12-20 19:20:44 +01:00
2019-01-15 09:41:05 +01:00
if ( ! TextUtils . isEmpty ( serializedPreviews ) ) {
ContentValues contactValues = new ContentValues ( ) ;
contactValues . put ( LINK_PREVIEWS , serializedPreviews ) ;
SQLiteDatabase database = databaseHelper . getReadableDatabase ( ) ;
int rows = database . update ( TABLE_NAME , contactValues , ID + " = ?" , new String [ ] { String . valueOf ( messageId ) } ) ;
if ( rows < = 0 ) {
Log . w ( TAG , "Failed to update message with link preview data." ) ;
}
}
2015-04-28 07:16:37 +02:00
db . setTransactionSuccessful ( ) ;
return messageId ;
} finally {
db . endTransaction ( ) ;
2011-12-20 19:20:44 +01:00
2017-05-25 17:40:43 +02:00
if ( insertListener ! = null ) {
insertListener . onComplete ( ) ;
}
2015-10-16 22:59:40 +02:00
notifyConversationListeners ( contentValues . getAsLong ( THREAD_ID ) ) ;
2015-11-24 00:07:41 +01:00
DatabaseFactory . getThreadDatabase ( context ) . update ( contentValues . getAsLong ( THREAD_ID ) , true ) ;
2015-10-16 22:59:40 +02:00
}
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2020-08-20 22:50:14 +02:00
@Override
public boolean deleteMessage ( long messageId ) {
2015-10-13 03:25:05 +02:00
long threadId = getThreadIdForMessage ( messageId ) ;
AttachmentDatabase attachmentDatabase = DatabaseFactory . getAttachmentDatabase ( context ) ;
attachmentDatabase . deleteAttachmentsForMessage ( messageId ) ;
2012-09-08 05:03:23 +02:00
2017-09-30 17:45:45 +02:00
GroupReceiptDatabase groupReceiptDatabase = DatabaseFactory . getGroupReceiptDatabase ( context ) ;
groupReceiptDatabase . deleteRowsForMessage ( messageId ) ;
2020-09-30 20:35:02 +02:00
MentionDatabase mentionDatabase = DatabaseFactory . getMentionDatabase ( context ) ;
mentionDatabase . deleteMentionsForMessage ( messageId ) ;
2011-12-20 19:20:44 +01:00
SQLiteDatabase database = databaseHelper . getWritableDatabase ( ) ;
database . delete ( TABLE_NAME , ID_WHERE , new String [ ] { messageId + "" } ) ;
2015-11-24 00:07:41 +01:00
boolean threadDeleted = DatabaseFactory . getThreadDatabase ( context ) . update ( threadId , false ) ;
2011-12-20 19:20:44 +01:00
notifyConversationListeners ( threadId ) ;
2019-04-17 16:21:30 +02:00
notifyStickerListeners ( ) ;
notifyStickerPackListeners ( ) ;
2015-03-31 22:36:04 +02:00
return threadDeleted ;
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2020-08-24 22:40:47 +02:00
@Override
2011-12-20 19:20:44 +01:00
public void deleteThread ( long threadId ) {
2015-10-13 03:25:05 +02:00
Set < Long > singleThreadSet = new HashSet < > ( ) ;
2011-12-20 19:20:44 +01:00
singleThreadSet . add ( threadId ) ;
deleteThreads ( singleThreadSet ) ;
}
2012-09-08 05:03:23 +02:00
2019-01-15 09:41:05 +01:00
private @Nullable String getSerializedSharedContacts ( @NonNull Map < Attachment , AttachmentId > insertedAttachmentIds , @NonNull List < Contact > contacts ) {
2018-04-27 02:03:54 +02:00
if ( contacts . isEmpty ( ) ) return null ;
JSONArray sharedContactJson = new JSONArray ( ) ;
for ( Contact contact : contacts ) {
try {
AttachmentId attachmentId = null ;
if ( contact . getAvatarAttachment ( ) ! = null ) {
attachmentId = insertedAttachmentIds . get ( contact . getAvatarAttachment ( ) ) ;
}
Avatar updatedAvatar = new Avatar ( attachmentId ,
contact . getAvatarAttachment ( ) ,
contact . getAvatar ( ) ! = null & & contact . getAvatar ( ) . isProfile ( ) ) ;
Contact updatedContact = new Contact ( contact , updatedAvatar ) ;
sharedContactJson . put ( new JSONObject ( updatedContact . serialize ( ) ) ) ;
} catch ( JSONException | IOException e ) {
Log . w ( TAG , "Failed to serialize shared contact. Skipping it." , e ) ;
}
}
return sharedContactJson . toString ( ) ;
}
2019-01-15 09:41:05 +01:00
private @Nullable String getSerializedLinkPreviews ( @NonNull Map < Attachment , AttachmentId > insertedAttachmentIds , @NonNull List < LinkPreview > previews ) {
if ( previews . isEmpty ( ) ) return null ;
JSONArray linkPreviewJson = new JSONArray ( ) ;
for ( LinkPreview preview : previews ) {
try {
AttachmentId attachmentId = null ;
if ( preview . getThumbnail ( ) . isPresent ( ) ) {
attachmentId = insertedAttachmentIds . get ( preview . getThumbnail ( ) . get ( ) ) ;
}
2020-08-26 22:03:52 +02:00
LinkPreview updatedPreview = new LinkPreview ( preview . getUrl ( ) , preview . getTitle ( ) , preview . getDescription ( ) , preview . getDate ( ) , attachmentId ) ;
2019-01-15 09:41:05 +01:00
linkPreviewJson . put ( new JSONObject ( updatedPreview . serialize ( ) ) ) ;
} catch ( JSONException | IOException e ) {
Log . w ( TAG , "Failed to serialize shared contact. Skipping it." , e ) ;
}
}
return linkPreviewJson . toString ( ) ;
}
2017-01-22 22:52:36 +01:00
private boolean isDuplicate ( IncomingMediaMessage message , long threadId ) {
SQLiteDatabase database = databaseHelper . getReadableDatabase ( ) ;
2019-08-07 20:22:51 +02:00
Cursor cursor = database . query ( TABLE_NAME , null , DATE_SENT + " = ? AND " + RECIPIENT_ID + " = ? AND " + THREAD_ID + " = ?" ,
2017-08-01 17:56:00 +02:00
new String [ ] { String . valueOf ( message . getSentTimeMillis ( ) ) , message . getFrom ( ) . serialize ( ) , String . valueOf ( threadId ) } ,
2017-01-22 22:52:36 +01:00
null , null , null , "1" ) ;
try {
return cursor ! = null & & cursor . moveToFirst ( ) ;
} finally {
if ( cursor ! = null ) cursor . close ( ) ;
}
}
2020-08-24 22:40:47 +02:00
@Override
2018-11-14 20:39:23 +01:00
public boolean isSent ( long messageId ) {
SQLiteDatabase database = databaseHelper . getReadableDatabase ( ) ;
try ( Cursor cursor = database . query ( TABLE_NAME , new String [ ] { MESSAGE_BOX } , ID + " = ?" , new String [ ] { String . valueOf ( messageId ) } , null , null , null ) ) {
if ( cursor ! = null & & cursor . moveToNext ( ) ) {
long type = cursor . getLong ( cursor . getColumnIndexOrThrow ( MESSAGE_BOX ) ) ;
return Types . isSentType ( type ) ;
}
}
return false ;
}
2020-08-20 22:50:14 +02:00
@Override
2020-08-24 22:40:47 +02:00
void deleteThreads ( @NonNull Set < Long > threadIds ) {
2011-12-20 19:20:44 +01:00
SQLiteDatabase db = databaseHelper . getWritableDatabase ( ) ;
String where = "" ;
Cursor cursor = null ;
2012-09-08 05:03:23 +02:00
2011-12-20 19:20:44 +01:00
for ( long threadId : threadIds ) {
where + = THREAD_ID + " = '" + threadId + "' OR " ;
}
2012-09-08 05:03:23 +02:00
2011-12-20 19:20:44 +01:00
where = where . substring ( 0 , where . length ( ) - 4 ) ;
2012-09-08 05:03:23 +02:00
2011-12-20 19:20:44 +01:00
try {
cursor = db . query ( TABLE_NAME , new String [ ] { ID } , where , null , null , null , null ) ;
2012-09-08 05:03:23 +02:00
2011-12-20 19:20:44 +01:00
while ( cursor ! = null & & cursor . moveToNext ( ) ) {
2020-08-20 22:50:14 +02:00
deleteMessage ( cursor . getLong ( 0 ) ) ;
2011-12-20 19:20:44 +01:00
}
2012-09-08 05:03:23 +02:00
2011-12-20 19:20:44 +01:00
} finally {
if ( cursor ! = null )
cursor . close ( ) ;
2012-09-08 05:03:23 +02:00
}
2011-12-20 19:20:44 +01:00
}
2020-08-20 22:50:14 +02:00
@Override
void deleteMessagesInThreadBeforeDate ( long threadId , long date ) {
2020-09-03 23:52:44 +02:00
SQLiteDatabase db = databaseHelper . getWritableDatabase ( ) ;
String where = THREAD_ID + " = ? AND " + DATE_RECEIVED + " < " + date ;
2013-01-10 06:06:56 +01:00
2020-09-03 23:52:44 +02:00
db . delete ( TABLE_NAME , where , SqlUtil . buildArgs ( threadId ) ) ;
}
2013-01-10 06:06:56 +01:00
2020-09-03 23:52:44 +02:00
@Override
void deleteAbandonedMessages ( ) {
SQLiteDatabase db = databaseHelper . getWritableDatabase ( ) ;
String where = THREAD_ID + " NOT IN (SELECT _id FROM " + ThreadDatabase . TABLE_NAME + ")" ;
2013-01-10 06:06:56 +01:00
2020-09-03 23:52:44 +02:00
db . delete ( TABLE_NAME , where , null ) ;
2013-01-10 06:06:56 +01:00
}
2020-08-20 22:50:14 +02:00
@Override
2011-12-20 19:20:44 +01:00
public void deleteAllThreads ( ) {
2015-10-13 03:25:05 +02:00
DatabaseFactory . getAttachmentDatabase ( context ) . deleteAllAttachments ( ) ;
2017-09-30 17:45:45 +02:00
DatabaseFactory . getGroupReceiptDatabase ( context ) . deleteAllRows ( ) ;
2020-09-30 20:35:02 +02:00
DatabaseFactory . getMentionDatabase ( context ) . deleteAllMentions ( ) ;
2012-09-08 05:03:23 +02:00
2011-12-20 19:20:44 +01:00
SQLiteDatabase database = databaseHelper . getWritableDatabase ( ) ;
database . delete ( TABLE_NAME , null , null ) ;
}
2012-09-08 05:03:23 +02:00
2020-08-24 22:40:47 +02:00
@Override
2020-08-20 22:50:14 +02:00
public @Nullable ViewOnceExpirationInfo getNearestExpiringViewOnceMessage ( ) {
2019-06-11 08:18:45 +02:00
SQLiteDatabase db = databaseHelper . getReadableDatabase ( ) ;
2019-08-01 01:33:56 +02:00
ViewOnceExpirationInfo info = null ;
2019-06-11 08:18:45 +02:00
long nearestExpiration = Long . MAX_VALUE ;
String query = "SELECT " +
TABLE_NAME + "." + ID + ", " +
2019-08-01 01:33:56 +02:00
VIEW_ONCE + ", " +
2019-06-11 08:18:45 +02:00
DATE_RECEIVED + " " +
"FROM " + TABLE_NAME + " INNER JOIN " + AttachmentDatabase . TABLE_NAME + " " +
"ON " + TABLE_NAME + "." + ID + " = " + AttachmentDatabase . TABLE_NAME + "." + AttachmentDatabase . MMS_ID + " " +
"WHERE " +
2019-08-01 01:33:56 +02:00
VIEW_ONCE + " > 0 AND " +
2019-06-11 08:18:45 +02:00
"(" + AttachmentDatabase . DATA + " NOT NULL OR " + AttachmentDatabase . TRANSFER_STATE + " != ?)" ;
String [ ] args = new String [ ] { String . valueOf ( AttachmentDatabase . TRANSFER_PROGRESS_DONE ) } ;
try ( Cursor cursor = db . rawQuery ( query , args ) ) {
while ( cursor ! = null & & cursor . moveToNext ( ) ) {
long id = cursor . getLong ( cursor . getColumnIndexOrThrow ( ID ) ) ;
long dateReceived = cursor . getLong ( cursor . getColumnIndexOrThrow ( DATE_RECEIVED ) ) ;
2019-08-01 01:33:56 +02:00
long expiresAt = dateReceived + ViewOnceUtil . MAX_LIFESPAN ;
2019-06-11 08:18:45 +02:00
if ( info = = null | | expiresAt < nearestExpiration ) {
2019-08-01 01:33:56 +02:00
info = new ViewOnceExpirationInfo ( id , dateReceived ) ;
2019-06-11 08:18:45 +02:00
nearestExpiration = expiresAt ;
}
}
}
return info ;
}
2020-08-20 22:50:14 +02:00
private static @NonNull List < Mention > parseQuoteMentions ( @NonNull Context context , Cursor cursor ) {
2020-08-05 22:45:52 +02:00
byte [ ] raw = cursor . getBlob ( cursor . getColumnIndexOrThrow ( QUOTE_MENTIONS ) ) ;
return MentionUtil . bodyRangeListToMentions ( context , raw ) ;
}
2020-08-20 22:50:14 +02:00
@Override
public SQLiteDatabase beginTransaction ( ) {
2019-04-17 16:21:30 +02:00
databaseHelper . getWritableDatabase ( ) . beginTransaction ( ) ;
2020-08-20 22:50:14 +02:00
return databaseHelper . getWritableDatabase ( ) ;
2019-04-17 16:21:30 +02:00
}
2020-08-24 22:40:47 +02:00
@Override
2019-04-17 16:21:30 +02:00
public void setTransactionSuccessful ( ) {
databaseHelper . getWritableDatabase ( ) . setTransactionSuccessful ( ) ;
}
2020-08-24 22:40:47 +02:00
@Override
2019-04-17 16:21:30 +02:00
public void endTransaction ( ) {
databaseHelper . getWritableDatabase ( ) . endTransaction ( ) ;
}
2020-08-20 22:50:14 +02:00
public static Reader readerFor ( Cursor cursor ) {
2018-01-25 04:17:44 +01:00
return new Reader ( cursor ) ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
}
2012-09-08 05:03:23 +02:00
2020-08-24 22:40:47 +02:00
public static OutgoingMessageReader readerFor ( OutgoingMediaMessage message , long threadId ) {
2017-04-23 01:29:26 +02:00
return new OutgoingMessageReader ( message , threadId ) ;
}
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
public static class Status {
2011-12-20 19:20:44 +01:00
public static final int DOWNLOAD_INITIALIZED = 1 ;
public static final int DOWNLOAD_NO_CONNECTIVITY = 2 ;
public static final int DOWNLOAD_CONNECTING = 3 ;
2012-10-01 04:56:29 +02:00
public static final int DOWNLOAD_SOFT_FAILURE = 4 ;
public static final int DOWNLOAD_HARD_FAILURE = 5 ;
2013-09-16 09:55:01 +02:00
public static final int DOWNLOAD_APN_UNAVAILABLE = 6 ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
}
2012-09-08 05:03:23 +02:00
2020-08-24 22:40:47 +02:00
public static class OutgoingMessageReader {
2017-04-23 01:29:26 +02:00
2020-08-24 22:40:47 +02:00
private final Context context ;
2017-04-23 01:29:26 +02:00
private final OutgoingMediaMessage message ;
private final long id ;
private final long threadId ;
public OutgoingMessageReader ( OutgoingMediaMessage message , long threadId ) {
2020-08-24 22:40:47 +02:00
this . context = ApplicationDependencies . getApplication ( ) ;
2019-03-15 23:31:52 +01:00
this . message = message ;
this . id = new SecureRandom ( ) . nextLong ( ) ;
this . threadId = threadId ;
2017-04-23 01:29:26 +02:00
}
public MessageRecord getCurrent ( ) {
SlideDeck slideDeck = new SlideDeck ( context , message . getAttachments ( ) ) ;
2020-08-05 22:45:52 +02:00
CharSequence quoteText = message . getOutgoingQuote ( ) ! = null ? message . getOutgoingQuote ( ) . getText ( ) : null ;
List < Mention > quoteMentions = message . getOutgoingQuote ( ) ! = null ? message . getOutgoingQuote ( ) . getMentions ( ) : Collections . emptyList ( ) ;
if ( quoteText ! = null & & ! quoteMentions . isEmpty ( ) ) {
MentionUtil . UpdatedBodyAndMentions updated = MentionUtil . updateBodyAndMentionsWithDisplayNames ( context , quoteText , quoteMentions ) ;
quoteText = updated . getBody ( ) ;
quoteMentions = updated . getMentions ( ) ;
}
2020-04-14 01:02:50 +02:00
return new MediaMmsMessageRecord ( id ,
message . getRecipient ( ) ,
message . getRecipient ( ) ,
1 ,
System . currentTimeMillis ( ) ,
System . currentTimeMillis ( ) ,
- 1 ,
0 ,
threadId , message . getBody ( ) ,
slideDeck ,
slideDeck . getSlides ( ) . size ( ) ,
2017-04-23 01:29:26 +02:00
message . isSecure ( ) ? MmsSmsColumns . Types . getOutgoingEncryptedMessageType ( ) : MmsSmsColumns . Types . getOutgoingSmsMessageType ( ) ,
2020-04-14 01:02:50 +02:00
new LinkedList < > ( ) ,
new LinkedList < > ( ) ,
2017-04-23 01:29:26 +02:00
message . getSubscriptionId ( ) ,
message . getExpiresIn ( ) ,
2019-06-11 08:18:45 +02:00
System . currentTimeMillis ( ) ,
2019-08-01 01:33:56 +02:00
message . isViewOnce ( ) ,
2019-06-11 08:18:45 +02:00
0 ,
2018-02-07 23:01:37 +01:00
message . getOutgoingQuote ( ) ! = null ?
new Quote ( message . getOutgoingQuote ( ) . getId ( ) ,
message . getOutgoingQuote ( ) . getAuthor ( ) ,
2020-08-05 22:45:52 +02:00
quoteText ,
2018-08-11 15:55:52 +02:00
message . getOutgoingQuote ( ) . isOriginalMissing ( ) ,
2020-08-05 22:45:52 +02:00
new SlideDeck ( context , message . getOutgoingQuote ( ) . getAttachments ( ) ) ,
quoteMentions ) :
2018-04-27 02:03:54 +02:00
null ,
2020-04-14 01:02:50 +02:00
message . getSharedContacts ( ) ,
message . getLinkPreviews ( ) ,
false ,
2020-04-15 20:56:58 +02:00
Collections . emptyList ( ) ,
2020-08-05 22:45:52 +02:00
false ,
2020-04-15 20:56:58 +02:00
false ) ;
2017-04-23 01:29:26 +02:00
}
}
2020-08-24 22:40:47 +02:00
public static class Reader implements MessageDatabase . Reader {
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
2020-08-20 22:50:14 +02:00
private final Cursor cursor ;
private final Context context ;
2013-04-26 20:23:43 +02:00
2018-01-25 04:17:44 +01:00
public Reader ( Cursor cursor ) {
2020-08-20 22:50:14 +02:00
this . cursor = cursor ;
this . context = ApplicationDependencies . getApplication ( ) ;
2011-12-20 19:20:44 +01:00
}
2020-08-24 22:40:47 +02:00
@Override
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
public MessageRecord getNext ( ) {
if ( cursor = = null | | ! cursor . moveToNext ( ) )
return null ;
return getCurrent ( ) ;
2011-12-20 19:20:44 +01:00
}
2020-08-24 22:40:47 +02:00
@Override
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
public MessageRecord getCurrent ( ) {
long mmsType = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . MESSAGE_TYPE ) ) ;
2012-09-08 05:03:23 +02:00
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
if ( mmsType = = PduHeaders . MESSAGE_TYPE_NOTIFICATION_IND ) {
return getNotificationMmsMessageRecord ( cursor ) ;
} else {
return getMediaMmsMessageRecord ( cursor ) ;
2011-12-20 19:20:44 +01:00
}
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
}
2012-09-08 05:03:23 +02:00
2013-05-05 21:51:36 +02:00
private NotificationMmsMessageRecord getNotificationMmsMessageRecord ( Cursor cursor ) {
2017-09-16 07:38:53 +02:00
long id = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . ID ) ) ;
long dateSent = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . NORMALIZED_DATE_SENT ) ) ;
long dateReceived = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . NORMALIZED_DATE_RECEIVED ) ) ;
long threadId = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . THREAD_ID ) ) ;
long mailbox = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . MESSAGE_BOX ) ) ;
2019-08-07 20:22:51 +02:00
long recipientId = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . RECIPIENT_ID ) ) ;
2017-09-16 07:38:53 +02:00
int addressDeviceId = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . ADDRESS_DEVICE_ID ) ) ;
2019-08-07 20:22:51 +02:00
Recipient recipient = Recipient . live ( RecipientId . from ( recipientId ) ) . get ( ) ;
2017-09-16 07:38:53 +02:00
String contentLocation = cursor . getString ( cursor . getColumnIndexOrThrow ( MmsDatabase . CONTENT_LOCATION ) ) ;
String transactionId = cursor . getString ( cursor . getColumnIndexOrThrow ( MmsDatabase . TRANSACTION_ID ) ) ;
long messageSize = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . MESSAGE_SIZE ) ) ;
long expiry = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . EXPIRY ) ) ;
int status = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . STATUS ) ) ;
int deliveryReceiptCount = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . DELIVERY_RECEIPT_COUNT ) ) ;
int readReceiptCount = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . READ_RECEIPT_COUNT ) ) ;
int subscriptionId = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . SUBSCRIPTION_ID ) ) ;
if ( ! TextSecurePreferences . isReadReceiptsEnabled ( context ) ) {
readReceiptCount = 0 ;
}
2013-05-05 21:51:36 +02:00
byte [ ] contentLocationBytes = null ;
byte [ ] transactionIdBytes = null ;
2014-11-12 20:15:05 +01:00
if ( ! TextUtils . isEmpty ( contentLocation ) )
2013-07-10 04:48:33 +02:00
contentLocationBytes = org . thoughtcrime . securesms . util . Util . toIsoBytes ( contentLocation ) ;
2013-05-05 21:51:36 +02:00
2014-11-12 20:15:05 +01:00
if ( ! TextUtils . isEmpty ( transactionId ) )
2013-07-10 04:48:33 +02:00
transactionIdBytes = org . thoughtcrime . securesms . util . Util . toIsoBytes ( transactionId ) ;
2013-05-05 21:51:36 +02:00
2017-01-21 00:26:17 +01:00
SlideDeck slideDeck = new SlideDeck ( context , new MmsNotificationAttachment ( status , messageSize ) ) ;
2013-05-05 21:51:36 +02:00
2019-03-13 22:28:16 +01:00
return new NotificationMmsMessageRecord ( id , recipient , recipient ,
2017-09-16 07:38:53 +02:00
addressDeviceId , dateSent , dateReceived , deliveryReceiptCount , threadId ,
2014-02-03 04:38:06 +01:00
contentLocationBytes , messageSize , expiry , status ,
2017-09-16 07:38:53 +02:00
transactionIdBytes , mailbox , subscriptionId , slideDeck ,
readReceiptCount ) ;
2013-05-05 21:51:36 +02:00
}
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
private MediaMmsMessageRecord getMediaMmsMessageRecord ( Cursor cursor ) {
2020-04-14 01:02:50 +02:00
long id = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . ID ) ) ;
long dateSent = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . NORMALIZED_DATE_SENT ) ) ;
2019-12-03 22:57:21 +01:00
long dateReceived = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . NORMALIZED_DATE_RECEIVED ) ) ;
2020-04-14 01:02:50 +02:00
long dateServer = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . DATE_SERVER ) ) ;
long box = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . MESSAGE_BOX ) ) ;
long threadId = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . THREAD_ID ) ) ;
long recipientId = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . RECIPIENT_ID ) ) ;
int addressDeviceId = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . ADDRESS_DEVICE_ID ) ) ;
2019-12-03 22:57:21 +01:00
int deliveryReceiptCount = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . DELIVERY_RECEIPT_COUNT ) ) ;
2020-04-14 01:02:50 +02:00
int readReceiptCount = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . READ_RECEIPT_COUNT ) ) ;
String body = cursor . getString ( cursor . getColumnIndexOrThrow ( MmsDatabase . BODY ) ) ;
int partCount = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . PART_COUNT ) ) ;
2019-12-03 22:57:21 +01:00
String mismatchDocument = cursor . getString ( cursor . getColumnIndexOrThrow ( MmsDatabase . MISMATCHED_IDENTITIES ) ) ;
2020-04-14 01:02:50 +02:00
String networkDocument = cursor . getString ( cursor . getColumnIndexOrThrow ( MmsDatabase . NETWORK_FAILURE ) ) ;
int subscriptionId = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . SUBSCRIPTION_ID ) ) ;
long expiresIn = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . EXPIRES_IN ) ) ;
long expireStarted = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . EXPIRE_STARTED ) ) ;
2019-12-03 22:57:21 +01:00
boolean unidentified = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . UNIDENTIFIED ) ) = = 1 ;
boolean isViewOnce = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . VIEW_ONCE ) ) = = 1 ;
2020-04-15 20:56:58 +02:00
boolean remoteDelete = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . REMOTE_DELETED ) ) = = 1 ;
2019-12-03 22:57:21 +01:00
List < ReactionRecord > reactions = parseReactions ( cursor ) ;
2020-08-05 22:45:52 +02:00
boolean mentionsSelf = CursorUtil . requireBoolean ( cursor , MENTIONS_SELF ) ;
2017-09-16 07:38:53 +02:00
if ( ! TextSecurePreferences . isReadReceiptsEnabled ( context ) ) {
readReceiptCount = 0 ;
}
2015-01-15 22:35:35 +01:00
2019-08-07 20:22:51 +02:00
Recipient recipient = Recipient . live ( RecipientId . from ( recipientId ) ) . get ( ) ;
2018-04-27 02:03:54 +02:00
List < IdentityKeyMismatch > mismatches = getMismatchedIdentities ( mismatchDocument ) ;
List < NetworkFailure > networkFailures = getFailures ( networkDocument ) ;
List < DatabaseAttachment > attachments = DatabaseFactory . getAttachmentDatabase ( context ) . getAttachment ( cursor ) ;
List < Contact > contacts = getSharedContacts ( cursor , attachments ) ;
2020-01-08 21:56:51 +01:00
Set < Attachment > contactAttachments = Stream . of ( contacts ) . map ( Contact : : getAvatarAttachment ) . withoutNulls ( ) . collect ( Collectors . toSet ( ) ) ;
2019-01-15 09:41:05 +01:00
List < LinkPreview > previews = getLinkPreviews ( cursor , attachments ) ;
Set < Attachment > previewAttachments = Stream . of ( previews ) . filter ( lp - > lp . getThumbnail ( ) . isPresent ( ) ) . map ( lp - > lp . getThumbnail ( ) . get ( ) ) . collect ( Collectors . toSet ( ) ) ;
SlideDeck slideDeck = getSlideDeck ( Stream . of ( attachments ) . filterNot ( contactAttachments : : contains ) . filterNot ( previewAttachments : : contains ) . toList ( ) ) ;
2018-04-27 02:03:54 +02:00
Quote quote = getQuote ( cursor ) ;
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
2019-03-13 22:28:16 +01:00
return new MediaMmsMessageRecord ( id , recipient , recipient ,
2020-04-14 01:02:50 +02:00
addressDeviceId , dateSent , dateReceived , dateServer , deliveryReceiptCount ,
2016-02-06 01:10:33 +01:00
threadId , body , slideDeck , partCount , box , mismatches ,
2017-09-16 07:38:53 +02:00
networkFailures , subscriptionId , expiresIn , expireStarted ,
2020-04-15 20:56:58 +02:00
isViewOnce , readReceiptCount , quote , contacts , previews , unidentified , reactions ,
2020-08-05 22:45:52 +02:00
remoteDelete , mentionsSelf ) ;
2013-04-26 20:23:43 +02:00
}
2015-01-15 22:35:35 +01:00
private List < IdentityKeyMismatch > getMismatchedIdentities ( String document ) {
if ( ! TextUtils . isEmpty ( document ) ) {
try {
return JsonUtils . fromJson ( document , IdentityKeyMismatchList . class ) . getList ( ) ;
} catch ( IOException e ) {
Log . w ( TAG , e ) ;
}
}
return new LinkedList < > ( ) ;
}
private List < NetworkFailure > getFailures ( String document ) {
if ( ! TextUtils . isEmpty ( document ) ) {
try {
return JsonUtils . fromJson ( document , NetworkFailureList . class ) . getList ( ) ;
} catch ( IOException ioe ) {
Log . w ( TAG , ioe ) ;
}
}
return new LinkedList < > ( ) ;
}
2018-04-27 02:03:54 +02:00
private SlideDeck getSlideDeck ( @NonNull List < DatabaseAttachment > attachments ) {
2020-01-08 21:56:51 +01:00
List < DatabaseAttachment > messageAttachments = Stream . of ( attachments )
. filterNot ( Attachment : : isQuote )
. sorted ( new DatabaseAttachment . DisplayOrderComparator ( ) )
. toList ( ) ;
2019-04-17 16:21:30 +02:00
return new SlideDeck ( context , messageAttachments ) ;
2018-02-07 23:01:37 +01:00
}
private @Nullable Quote getQuote ( @NonNull Cursor cursor ) {
long quoteId = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . QUOTE_ID ) ) ;
2019-10-16 05:10:15 +02:00
long quoteAuthor = cursor . getLong ( cursor . getColumnIndexOrThrow ( MmsDatabase . QUOTE_AUTHOR ) ) ;
2020-08-05 22:45:52 +02:00
CharSequence quoteText = cursor . getString ( cursor . getColumnIndexOrThrow ( MmsDatabase . QUOTE_BODY ) ) ;
2018-08-11 15:55:52 +02:00
boolean quoteMissing = cursor . getInt ( cursor . getColumnIndexOrThrow ( MmsDatabase . QUOTE_MISSING ) ) = = 1 ;
2020-08-20 22:50:14 +02:00
List < Mention > quoteMentions = parseQuoteMentions ( context , cursor ) ;
2018-02-07 23:01:37 +01:00
List < DatabaseAttachment > attachments = DatabaseFactory . getAttachmentDatabase ( context ) . getAttachment ( cursor ) ;
List < ? extends Attachment > quoteAttachments = Stream . of ( attachments ) . filter ( Attachment : : isQuote ) . toList ( ) ;
SlideDeck quoteDeck = new SlideDeck ( context , quoteAttachments ) ;
2019-10-16 05:10:15 +02:00
if ( quoteId > 0 & & quoteAuthor > 0 ) {
2020-08-05 22:45:52 +02:00
if ( quoteText ! = null & & ! quoteMentions . isEmpty ( ) ) {
MentionUtil . UpdatedBodyAndMentions updated = MentionUtil . updateBodyAndMentionsWithDisplayNames ( context , quoteText , quoteMentions ) ;
quoteText = updated . getBody ( ) ;
quoteMentions = updated . getMentions ( ) ;
}
return new Quote ( quoteId , RecipientId . from ( quoteAuthor ) , quoteText , quoteMissing , quoteDeck , quoteMentions ) ;
2018-02-07 23:01:37 +01:00
} else {
return null ;
}
2013-05-06 21:22:03 +02:00
}
2018-06-28 21:07:20 +02:00
@Override
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
public void close ( ) {
2018-06-28 21:07:20 +02:00
if ( cursor ! = null ) {
cursor . close ( ) ;
}
2011-12-20 19:20:44 +01:00
}
}
Major storage layer refactoring to set the stage for clean GCM.
1) We now try to hand out cursors at a minimum. There has always been
a fairly clean insertion layer that handles encrypting message bodies,
but the process of decrypting message bodies has always been less than
ideal. Here we introduce a "Reader" interface that will decrypt message
bodies when appropriate and return objects that encapsulate record state.
No more MessageDisplayHelper. The MmsSmsDatabase interface is also more
sane.
2) We finally rid ourselves of the technical debt associated with TextSecure's
initial usage of the default SMS DB. In that world, we weren't able to use
anything other than the default "Inbox, Outbox, Sent" types to describe a
message, and had to overload the message content itself with a set of
local "prefixes" to describe what it was (encrypted, asymetric encrypted,
remote encrypted, a key exchange, procssed key exchange), and so on.
This includes a major schema update that transforms the "type" field into
a bitmask that describes everything that used to be encoded in a prefix,
and prefixes have been completely eliminated from the system.
No more Prefix.java
3) Refactoring of the MultipartMessageHandler code. It's less of a mess, and
hopefully more clear as to what's going on.
The next step is to remove what we can from SmsTransportDetails and genericize
that interface for a GCM equivalent.
2013-04-20 21:22:04 +02:00
2015-08-04 22:37:22 +02:00
private long generatePduCompatTimestamp ( ) {
final long time = System . currentTimeMillis ( ) ;
return time - ( time % 1000 ) ;
}
2011-12-20 19:20:44 +01:00
}