Welcome to mirror list, hosted at ThFree Co, Russian Federation.

AndroidContact.kt « vcard4android « bitfire « at « java « main « src - github.com/bitfireAT/vcard4android.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d1f18fd18c13f19754f972cf82ea02b2c713204c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/*
 * Copyright © Ricki Hirner (bitfire web engineering).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 */

package at.bitfire.vcard4android

import android.content.ContentUris
import android.content.ContentValues
import android.content.EntityIterator
import android.database.DatabaseUtils
import android.net.Uri
import android.os.RemoteException
import android.provider.ContactsContract
import android.provider.ContactsContract.RawContacts
import android.provider.ContactsContract.RawContacts.Data
import androidx.annotation.CallSuper
import at.bitfire.vcard4android.datarow.ContactProcessor
import org.apache.commons.lang3.builder.ToStringBuilder
import java.io.FileNotFoundException

open class AndroidContact(
        val addressBook: AndroidAddressBook<out AndroidContact, out AndroidGroup>
) {

    companion object {

        const val COLUMN_FILENAME = RawContacts.SOURCE_ID
        const val COLUMN_UID = RawContacts.SYNC1
        const val COLUMN_ETAG = RawContacts.SYNC2

    }

    var id: Long? = null
        protected set

    var fileName: String? = null
        protected set

    var eTag: String? = null

    val processor = ContactProcessor(addressBook.provider)


    /**
     * Creates a new instance, initialized with some metadata. Usually used to insert a contact to an address book.
     */
    constructor(addressBook: AndroidAddressBook<out AndroidContact, out AndroidGroup>, _contact: Contact, _fileName: String?, _eTag: String?)
            : this(addressBook) {
        fileName = _fileName
        eTag = _eTag
        setContact(_contact)
    }


    /**
     * Creates a new instance, initialized with metadata from the content provider. Usually used when reading a contact from an address book.
     */
    constructor(addressBook: AndroidAddressBook<out AndroidContact, out AndroidGroup>, values: ContentValues) : this(addressBook) {
        initializeFromContentValues(values)
    }

    protected open fun initializeFromContentValues(values: ContentValues) {
        id = values.getAsLong(RawContacts._ID)
        fileName = values.getAsString(COLUMN_FILENAME)
        eTag = values.getAsString(COLUMN_ETAG)
    }


    /**
     * Cached copy of the [Contact]. If this is null, [getContact] must generate the [Contact]
     * from the database and then set this property.
     */
    protected var _contact: Contact? = null

    /**
     * Fetches contact data from the contacts provider.
     *
     * @throws IllegalArgumentException if there's no [id] (usually because the contact has never been saved yet)
     * @throws FileNotFoundException when the contact is not available (anymore)
     * @throws RemoteException on contact provider errors
     */
    fun getContact(): Contact {
        _contact?.let { return it }

        val id = requireNotNull(id)
        var iter: EntityIterator? = null
        try {
            iter = RawContacts.newEntityIterator(addressBook.provider!!.query(
                    addressBook.syncAdapterURI(ContactsContract.RawContactsEntity.CONTENT_URI),
                    null, RawContacts._ID + "=?", arrayOf(id.toString()), null))

            if (iter.hasNext()) {
                val contact = Contact()
                _contact = contact

                // process raw contact itself
                val e = iter.next()
                processor.handleRawContact(e.entityValues, contact)

                // process data rows of raw contact
                for (subValue in e.subValues)
                    processor.handleDataRow(subValue.values, contact)

                return contact

            } else
                // no raw contact with this ID
                throw FileNotFoundException()

        } finally {
            iter?.close()
        }
    }

    fun setContact(newContact: Contact) {
        _contact = newContact
    }


    fun add(): Uri {
        val batch = BatchOperation(addressBook.provider!!)

        val builder = BatchOperation.CpoBuilder.newInsert(addressBook.syncAdapterURI(RawContacts.CONTENT_URI))
        buildContact(builder, false)
        batch.enqueue(builder)

        insertDataRows(batch)

        batch.commit()
        val resultUri = batch.getResult(0)?.uri ?: throw ContactsStorageException("Empty result from content provider when adding contact")
        id = ContentUris.parseId(resultUri)

        return resultUri
    }

    fun update(contact: Contact): Uri {
        setContact(contact)

        val batch = BatchOperation(addressBook.provider!!)
        val uri = rawContactSyncURI()
        val builder = BatchOperation.CpoBuilder.newUpdate(uri)
        buildContact(builder, true)
        batch.enqueue(builder)

        // Delete known data rows before adding the new ones.
        // - We don't delete group memberships because they're managed separately.
        // - We'll only delete rows we have inserted so that unknown rows like
        //   vnd.android.cursor.item/important_people (= contact is in Samsung "edge panel") remain untouched.
        val typesToRemove = processor.builderMimeTypes()
        val sqlTypesToRemove = typesToRemove.map { mimeType ->
            DatabaseUtils.sqlEscapeString(mimeType)
        }.joinToString(",")
        batch.enqueue(BatchOperation.CpoBuilder
                .newDelete(dataSyncURI())
                .withSelection(Data.RAW_CONTACT_ID + "=? AND ${Data.MIMETYPE} IN ($sqlTypesToRemove)", arrayOf(id!!.toString())))

        insertDataRows(batch)
        batch.commit()

        return uri
    }

    /**
     * Deletes an existing contact from the contacts provider.
     *
     * @return number of affected rows
     *
     * @throws RemoteException on contacts provider errors
     */
    fun delete() = addressBook.provider!!.delete(rawContactSyncURI(), null, null)


    @CallSuper
    protected open fun buildContact(builder: BatchOperation.CpoBuilder, update: Boolean) {
        if (!update)
            builder	.withValue(RawContacts.ACCOUNT_NAME, addressBook.account.name)
                    .withValue(RawContacts.ACCOUNT_TYPE, addressBook.account.type)

        builder .withValue(RawContacts.DIRTY, 0)
                .withValue(RawContacts.DELETED, 0)
                .withValue(COLUMN_FILENAME, fileName)
                .withValue(COLUMN_ETAG, eTag)
                .withValue(COLUMN_UID, getContact().uid)

        if (addressBook.readOnly)
            builder.withValue(RawContacts.RAW_CONTACT_IS_READ_ONLY, 1)
    }


    /**
     * Inserts the data rows for a given raw contact.
     *
     * @param  batch    batch operation used to insert the data rows
     *
     * @throws RemoteException on contact provider errors
     */
    protected fun insertDataRows(batch: BatchOperation) {
        val contact = getContact()
        processor.insertDataRows(dataSyncURI(), id, contact, batch)
    }


    // helpers

    protected fun insertDataBuilder(rawContactKeyName: String): BatchOperation.CpoBuilder {
        val builder = BatchOperation.CpoBuilder.newInsert(dataSyncURI())
        if (id == null)
            builder.withValueBackReference(rawContactKeyName, 0)
        else
            builder.withValue(rawContactKeyName, id)

        if (addressBook.readOnly)
            builder.withValue(Data.IS_READ_ONLY, 1)

        return builder
    }

    protected fun rawContactSyncURI(): Uri {
        val id = requireNotNull(id)
        return addressBook.syncAdapterURI(ContentUris.withAppendedId(RawContacts.CONTENT_URI, id))
    }

    protected fun dataSyncURI() = addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI)

    override fun toString() = ToStringBuilder.reflectionToString(this)!!

}