LocalGroup.kt 8.97 KB
Newer Older
1
/*
Ricki Hirner's avatar
Ricki Hirner committed
2
 * Copyright © Ricki Hirner (bitfire web engineering).
3 4 5 6 7 8 9 10 11 12 13
 * 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.davdroid.resource

import android.content.ContentProviderOperation
import android.content.ContentUris
import android.content.ContentValues
14
import android.net.Uri
15 16 17 18 19 20 21 22 23 24 25 26
import android.os.Build
import android.os.Parcel
import android.os.RemoteException
import android.provider.ContactsContract
import android.provider.ContactsContract.CommonDataKinds.GroupMembership
import android.provider.ContactsContract.Groups
import android.provider.ContactsContract.RawContacts
import android.provider.ContactsContract.RawContacts.Data
import at.bitfire.dav4android.Constants
import at.bitfire.vcard4android.*
import java.util.*

27
class LocalGroup: AndroidGroup, LocalAddress {
28 29 30

    companion object {

31 32
        const val COLUMN_FLAGS = Groups.SYNC4

33
        /** marshaled list of member UIDs, as sent by server */
34
        const val COLUMN_PENDING_MEMBERS = Groups.SYNC3
35 36 37 38 39 40 41

        /**
         * Processes all groups with non-null {@link #COLUMN_PENDING_MEMBERS}: the pending memberships
         * are (if possible) applied, keeping cached memberships in sync.
         * @param addressBook    address book to take groups from
         */
        fun applyPendingMemberships(addressBook: LocalAddressBook) {
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
            addressBook.provider!!.query(
                    addressBook.groupsSyncUri(),
                    arrayOf(Groups._ID, COLUMN_PENDING_MEMBERS),
                    "$COLUMN_PENDING_MEMBERS IS NOT NULL", null,
                    null
            )?.use { cursor ->
                val batch = BatchOperation(addressBook.provider)
                while (cursor.moveToNext()) {
                    val id = cursor.getLong(0)
                    Constants.log.fine("Assigning members to group $id")

                    // required for workaround for Android 7 which sets DIRTY flag when only meta-data is changed
                    val changeContactIDs = HashSet<Long>()

                    // delete all memberships and cached memberships for this group
                    for (contact in addressBook.getByGroupMembership(id)) {
                        contact.removeGroupMemberships(batch)
                        changeContactIDs.add(contact.id!!)
                    }

                    // extract list of member UIDs
                    val members = LinkedList<String>()
                    val raw = cursor.getBlob(1)
                    val parcel = Parcel.obtain()
                    try {
                        parcel.unmarshall(raw, 0, raw.size)
                        parcel.setDataPosition(0)
                        parcel.readStringList(members)
                    } finally {
                        parcel.recycle()
                    }

                    // insert memberships
                    for (uid in members) {
                        Constants.log.fine("Assigning member: $uid")
                        addressBook.findContactByUID(uid)?.let { member ->
                            member.addToGroup(batch, id)
                            changeContactIDs.add(member.id!!)
                        } ?: Constants.log.warning("Group member not found: $uid")
81
                    }
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
                        // workaround for Android 7 which sets DIRTY flag when only meta-data is changed
                        changeContactIDs
                                .map { addressBook.findContactByID(it) }
                                .forEach { it.updateHashCode(batch) }

                    // remove pending memberships
                    batch.enqueue(BatchOperation.Operation(
                            ContentProviderOperation.newUpdate(addressBook.syncAdapterURI(ContentUris.withAppendedId(Groups.CONTENT_URI, id)))
                                    .withValue(COLUMN_PENDING_MEMBERS, null)
                                    .withYieldAllowed(true)
                            ))

                    batch.commit()
97 98 99 100 101 102 103
                }
            }
        }

    }


104 105
    override var flags: Int = 0
        private set
106 107


108
    constructor(addressBook: AndroidAddressBook<out AndroidContact, LocalGroup>, values: ContentValues):
109 110 111
        super(addressBook, values) {
        flags = values.getAsInteger(COLUMN_FLAGS) ?: 0
    }
112

113 114 115 116
    constructor(addressBook: AndroidAddressBook<out AndroidContact, LocalGroup>, contact: Contact, fileName: String?, eTag: String?, flags: Int)
        : super(addressBook, contact, fileName, eTag) {
        this.flags = flags
    }
117

118 119 120 121 122

    override fun contentValues(): ContentValues  {
        val values = super.contentValues()

        val members = Parcel.obtain()
123
        try {
124 125 126 127
            members.writeStringList(contact!!.members)
            values.put(COLUMN_PENDING_MEMBERS, members.marshall())
        } finally {
            members.recycle()
128
        }
129 130 131 132 133 134 135 136 137 138 139 140 141 142
        return values
    }


    override fun assignNameAndUID() {
        val uid = UUID.randomUUID().toString()
        val newFileName = "$uid.vcf"

        val values = ContentValues(2)
        values.put(COLUMN_FILENAME, newFileName)
        values.put(COLUMN_UID, uid)
        update(values)

        fileName = newFileName
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
    override fun clearDirty(eTag: String?) {
        val id = requireNotNull(id)

        val values = ContentValues(2)
        values.put(Groups.DIRTY, 0)
        values.put(COLUMN_ETAG, eTag)
        this.eTag = eTag
        update(values)

        // update cached group memberships
        val batch = BatchOperation(addressBook.provider!!)

        // delete cached group memberships
        batch.enqueue(BatchOperation.Operation(
                ContentProviderOperation.newDelete(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI))
                        .withSelection(
                                CachedGroupMembership.MIMETYPE + "=? AND " + CachedGroupMembership.GROUP_ID + "=?",
                                arrayOf(CachedGroupMembership.CONTENT_ITEM_TYPE, id.toString())
                        )
        ))

        // insert updated cached group memberships
        for (member in getMembers())
            batch.enqueue(BatchOperation.Operation(
                    ContentProviderOperation.newInsert(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI))
                            .withValue(CachedGroupMembership.MIMETYPE, CachedGroupMembership.CONTENT_ITEM_TYPE)
                            .withValue(CachedGroupMembership.RAW_CONTACT_ID, member)
                            .withValue(CachedGroupMembership.GROUP_ID, id)
                            .withYieldAllowed(true)
            ))

        batch.commit()
    }

    /**
     * Marks all members of the current group as dirty.
     */
    fun markMembersDirty() {
        val batch = BatchOperation(addressBook.provider!!)

        for (member in getMembers())
            batch.enqueue(BatchOperation.Operation(
                    ContentProviderOperation.newUpdate(addressBook.syncAdapterURI(ContentUris.withAppendedId(RawContacts.CONTENT_URI, member)))
                            .withValue(RawContacts.DIRTY, 1)
                            .withYieldAllowed(true)
            ))

        batch.commit()
    }

195 196 197 198 199 200 201 202 203 204 205 206 207 208
    override fun resetDeleted() {
        val values = ContentValues(1)
        values.put(Groups.DELETED, 0)
        addressBook.provider!!.update(groupSyncUri(), values, null, null)
    }

    override fun updateFlags(flags: Int) {
        val values = ContentValues(1)
        values.put(LocalGroup.COLUMN_FLAGS, flags)
        addressBook.provider!!.update(groupSyncUri(), values, null, null)

        this.flags = flags
    }

209 210 211

    // helpers

212 213 214 215 216
    private fun groupSyncUri(): Uri {
        val id = requireNotNull(id)
        return ContentUris.withAppendedId(addressBook.groupsSyncUri(), id)
    }

217 218 219
    /**
     * Lists all members of this group.
     * @return list of all members' raw contact IDs
220
     * @throws RemoteException on contact provider errors
221 222 223 224
     */
    internal fun getMembers(): List<Long> {
        val id = requireNotNull(id)
        val members = LinkedList<Long>()
225 226 227 228 229 230 231 232 233
        addressBook.provider!!.query(
                addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI),
                arrayOf(Data.RAW_CONTACT_ID),
                "${GroupMembership.MIMETYPE}=? AND ${GroupMembership.GROUP_ROW_ID}=?",
                arrayOf(GroupMembership.CONTENT_ITEM_TYPE, id.toString()),
                null
        )?.use { cursor ->
            while (cursor.moveToNext())
                members.add(cursor.getLong(0))
234 235 236 237 238 239 240 241
        }
        return members
    }


    // factory

    object Factory: AndroidGroupFactory<LocalGroup> {
242 243
        override fun fromProvider(addressBook: AndroidAddressBook<out AndroidContact, LocalGroup>, values: ContentValues) =
                LocalGroup(addressBook, values)
244 245 246
    }

}