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

AndroidGroup.kt « vcard4android « bitfire « at « java « main « src - github.com/bitfireAT/vcard4android.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4461053c0210c198fd5ec4c9eadd2f343a3e9f9b (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
/*
 * 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.net.Uri
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 androidx.annotation.CallSuper
import org.apache.commons.lang3.builder.ToStringBuilder
import java.io.FileNotFoundException

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

    companion object {
        const val COLUMN_FILENAME = Groups.SOURCE_ID
        const val COLUMN_UID = Groups.SYNC1
        const val COLUMN_ETAG = Groups.SYNC2
    }

    var id: Long? = null

    var fileName: String? = null
    var eTag: String? = null

	constructor(addressBook: AndroidAddressBook<out AndroidContact, out AndroidGroup>, values: ContentValues): this(addressBook) {
        id = values.getAsLong(Groups._ID)
        fileName = values.getAsString(COLUMN_FILENAME)
        eTag = values.getAsString(COLUMN_ETAG)
	}

    constructor(addressBook: AndroidAddressBook<out AndroidContact, out AndroidGroup>, contact: Contact, fileName: String?  = null, eTag: String? = null): this(addressBook) {
		_contact = contact
        this.fileName = fileName
        this.eTag = 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 group data from the content provider.
     *
     * @throws IllegalArgumentException if group has not been saved yet
     * @throws FileNotFoundException when the group is not available (anymore)
     * @throws RemoteException on contact provider errors
     */
     fun getContact(): Contact {
        _contact?.let { return it }

        val id = requireNotNull(id)
        val contact = Contact()
        addressBook.provider!!.query(addressBook.syncAdapterURI(ContentUris.withAppendedId(Groups.CONTENT_URI, id)),
                arrayOf(COLUMN_UID, Groups.TITLE, Groups.NOTES), null, null, null)?.use { cursor ->
            if (!cursor.moveToNext())
                throw FileNotFoundException("Contact group not found")

            contact.group = true
            contact.uid = cursor.getString(0)
            contact.displayName = cursor.getString(1)
            contact.note = cursor.getString(2)
        }

        // get all contacts which are member of the group
        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 { membershipCursor ->
            while (membershipCursor.moveToNext()) {
                val contactId = membershipCursor.getLong(0)
                Constants.log.fine("Member ID: $contactId")

                // get UID from the member
                addressBook.provider.query(addressBook.syncAdapterURI(ContentUris.withAppendedId(RawContacts.CONTENT_URI, contactId)),
                        arrayOf(AndroidContact.COLUMN_UID), null, null, null)?.use { rawContactCursor ->
                    if (rawContactCursor.moveToNext()) {
                        val uid = rawContactCursor.getString(0)
                        if (!uid.isNullOrBlank()) {
                            Constants.log.fine("Found member of group: $uid")
                            // add UID to contact members (vCard MEMBERS field)
                            contact.members += uid
                        } else
                            Constants.log.severe("Couldn't add member $contactId to group contact because it doesn't have an UID (yet)")
                    }
                }
            }
        }

        _contact = contact
        return contact
    }


    @CallSuper
    protected open fun contentValues(): ContentValues {
        val values = ContentValues()
        values.put(COLUMN_FILENAME, fileName)
        values.put(COLUMN_ETAG, eTag)

        val contact = getContact()
        values.put(COLUMN_UID, contact.uid)
        values.put(Groups.TITLE, contact.displayName)
        values.put(Groups.NOTES, contact.note)
        return values
    }

    /**
     * Creates a group with data taken from the constructor.
     * @return number of affected rows
     * @throws RemoteException on contact provider errors
     * @throws ContactsStorageException when the group can't be added
     */
    fun add(): Uri {
        val values = contentValues()
		values.put(Groups.ACCOUNT_TYPE, addressBook.account.type)
		values.put(Groups.ACCOUNT_NAME, addressBook.account.name)
        values.put(Groups.SHOULD_SYNC, 1)
        // read-only: values.put(Groups.GROUP_VISIBLE, 1);
        val uri = addressBook.provider!!.insert(addressBook.syncAdapterURI(Groups.CONTENT_URI), values)
                ?: throw ContactsStorageException("Empty result from content provider when adding group")
        id = ContentUris.parseId(uri)
        return uri
	}

    /**
     * Updates a group from a [Contact], which represents a vCard received from the
     * CardDAV server.
     * @param data data object to take group title, members etc. from
     * @return number of affected rows
     * @throws RemoteException on contact provider errors
     */
    fun update(data: Contact): Uri {
        _contact = data
        return update(contentValues())
    }

    fun update(values: ContentValues): Uri {
        val uri = groupSyncURI()
        addressBook.provider!!.update(uri, values, null, null)
        return uri
    }

    fun delete() = addressBook.provider!!.delete(groupSyncURI(), null, null)


    // helpers

    private fun groupSyncURI(): Uri {
        val id = requireNotNull(id)
        return addressBook.syncAdapterURI(ContentUris.withAppendedId(Groups.CONTENT_URI, id))
    }

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

}