AndroidContact.kt 51.1 KB
Newer Older
Ricki Hirner's avatar
Ricki Hirner committed
1
/*
Ricki Hirner's avatar
Ricki Hirner committed
2
 * Copyright © Ricki Hirner (bitfire web engineering).
Ricki Hirner's avatar
Ricki Hirner committed
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
 * 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.ContentProviderOperation
import android.content.ContentUris
import android.content.ContentValues
import android.content.EntityIterator
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.RemoteException
import android.provider.ContactsContract
import android.provider.ContactsContract.CommonDataKinds
import android.provider.ContactsContract.CommonDataKinds.*
import android.provider.ContactsContract.CommonDataKinds.Email
import android.provider.ContactsContract.CommonDataKinds.Nickname
import android.provider.ContactsContract.CommonDataKinds.Note
import android.provider.ContactsContract.CommonDataKinds.Organization
import android.provider.ContactsContract.CommonDataKinds.Photo
import android.provider.ContactsContract.CommonDataKinds.StructuredName
import android.provider.ContactsContract.RawContacts
import ezvcard.parameter.*
import ezvcard.property.*
import ezvcard.util.PartialDate
import org.apache.commons.io.IOUtils
import org.apache.commons.lang3.StringUtils
Ricki Hirner's avatar
Ricki Hirner committed
34
import org.apache.commons.lang3.builder.ToStringBuilder
Ricki Hirner's avatar
Ricki Hirner committed
35 36 37 38 39 40 41 42 43 44
import org.apache.commons.lang3.text.WordUtils
import java.io.ByteArrayOutputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.logging.Level

open class AndroidContact(
Ricki Hirner's avatar
Ricki Hirner committed
45
        val addressBook: AndroidAddressBook<out AndroidContact, out AndroidGroup>
Ricki Hirner's avatar
Ricki Hirner committed
46 47 48 49
) {

    companion object {

Ricki Hirner's avatar
Ricki Hirner committed
50 51 52
        const val COLUMN_FILENAME = RawContacts.SOURCE_ID
        const val COLUMN_UID = RawContacts.SYNC1
        const val COLUMN_ETAG = RawContacts.SYNC2
Ricki Hirner's avatar
Ricki Hirner committed
53

Ricki Hirner's avatar
Ricki Hirner committed
54
        fun labelToXName(label: String) = "X-" + label
Ricki Hirner's avatar
Ricki Hirner committed
55
                .replace(" ","_")
Ricki Hirner's avatar
Ricki Hirner committed
56
                .replace(Regex("[^\\p{L}\\p{Nd}\\-_]"), "")
Ricki Hirner's avatar
Ricki Hirner committed
57 58
                .toUpperCase()

Ricki Hirner's avatar
Ricki Hirner committed
59
        fun xNameToLabel(xname: String): String {
Ricki Hirner's avatar
Ricki Hirner committed
60 61 62 63 64 65 66 67
            // "X-MY_PROPERTY"
            var s = xname.toLowerCase()     // 1. ensure lower case -> "x-my_property"
            if (s.startsWith("x-"))         // 2. remove x- from beginning -> "my_property"
                s = s.substring(2)
            s = s.replace('_', ' ')         // 3. replace "_" by " " -> "my property"
            return WordUtils.capitalize(s)  // 4. capitalize -> "My Property"
        }

Ricki Hirner's avatar
Ricki Hirner committed
68
        fun toURIScheme(s: String?) =
Ricki Hirner's avatar
Ricki Hirner committed
69 70 71 72
                // RFC 3986 3.1
                // scheme      = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
                // ALPHA       =  %x41-5A / %x61-7A   ; A-Z / a-z
                // DIGIT       =  %x30-39             ; 0-9
73
                s?.replace(Regex("^[^a-zA-Z]+"), "")?.replace(Regex("[^\\da-zA-Z+-.]"), "")
Ricki Hirner's avatar
Ricki Hirner committed
74 75 76 77

    }

    var id: Long? = null
Ricki Hirner's avatar
Ricki Hirner committed
78 79
        protected set

Ricki Hirner's avatar
Ricki Hirner committed
80
    var fileName: String? = null
Ricki Hirner's avatar
Ricki Hirner committed
81 82
        protected set

Ricki Hirner's avatar
Ricki Hirner committed
83 84
    var eTag: String? = null

Ricki Hirner's avatar
Ricki Hirner committed
85
    protected val photoMaxDimensions: Int by lazy { queryPhotoMaxDimensions() }
Ricki Hirner's avatar
Ricki Hirner committed
86 87


Ricki Hirner's avatar
Ricki Hirner committed
88 89 90 91 92
    constructor(addressBook: AndroidAddressBook<out AndroidContact, out AndroidGroup>, values: ContentValues)
            : this(addressBook) {
        this.id = values.getAsLong(RawContacts._ID)
        this.fileName = values.getAsString(COLUMN_FILENAME)
        this.eTag = values.getAsString(COLUMN_ETAG)
Ricki Hirner's avatar
Ricki Hirner committed
93 94
    }

Ricki Hirner's avatar
Ricki Hirner committed
95 96
    constructor(addressBook: AndroidAddressBook<out AndroidContact, out AndroidGroup>, contact: Contact, fileName: String?, eTag: String?)
            : this(addressBook) {
Ricki Hirner's avatar
Ricki Hirner committed
97 98 99 100 101 102
        this.contact = contact
        this.fileName = fileName
        this.eTag = eTag
    }

    var contact: Contact? = null
Ricki Hirner's avatar
Ricki Hirner committed
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
        /**
         * Fetches contact data from the contacts provider.
         * @throws IllegalArgumentException if contact has not been saved yet
         * @throws FileNotFoundException when the contact is not available (anymore)
         * @throws RemoteException on contact provider errors
         */
        get() {
            field?.let { return field }

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

                if (iter.hasNext()) {
                    val e = iter.next()

                    field = Contact()
                    populateContact(e.entityValues)

                    val subValues = e.subValues
                    for (subValue in subValues) {
                        val values = subValue.values

                        // remove empty values
                        val it = values.keySet().iterator()
                        while (it.hasNext()) {
                            val obj = values[it.next()]
                            if (obj is String && obj.isEmpty())
                                it.remove()
                        }

                        val mimeType = values.getAsString(ContactsContract.RawContactsEntity.MIMETYPE)
                        when (mimeType) {
                            StructuredName.CONTENT_ITEM_TYPE ->
                                populateStructuredName(values)
                            Phone.CONTENT_ITEM_TYPE ->
                                populatePhoneNumber(values)
                            Email.CONTENT_ITEM_TYPE ->
                                populateEmail(values)
                            Photo.CONTENT_ITEM_TYPE ->
                                populatePhoto(values)
                            Organization.CONTENT_ITEM_TYPE ->
                                populateOrganization(values)
                            Im.CONTENT_ITEM_TYPE ->
                                populateIMPP(values)
                            Nickname.CONTENT_ITEM_TYPE ->
                                populateNickname(values)
                            Note.CONTENT_ITEM_TYPE ->
                                populateNote(values)
                            StructuredPostal.CONTENT_ITEM_TYPE ->
                                populateStructuredPostal(values)
                            Website.CONTENT_ITEM_TYPE ->
                                populateWebsite(values)
                            Event.CONTENT_ITEM_TYPE ->
                                populateEvent(values)
                            Relation.CONTENT_ITEM_TYPE ->
                                populateRelation(values)
                            SipAddress.CONTENT_ITEM_TYPE ->
                                populateSipAddress(values)
                            null ->
                                Constants.log.warning("Ignoring raw contact data row without ${ContactsContract.RawContactsEntity.MIMETYPE}")
                            else ->
                                populateData(mimeType, values)
                        }
Ricki Hirner's avatar
Ricki Hirner committed
170 171
                    }

Ricki Hirner's avatar
Ricki Hirner committed
172 173 174 175 176 177
                    return field
                } else
                    throw FileNotFoundException()
            } finally {
                iter?.close()
            }
Ricki Hirner's avatar
Ricki Hirner committed
178 179
        }

Ricki Hirner's avatar
Ricki Hirner committed
180
    protected open fun populateContact(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
181 182 183 184 185 186
        fileName = row.getAsString(COLUMN_FILENAME)
        eTag = row.getAsString(COLUMN_ETAG)

        contact!!.uid = row.getAsString(COLUMN_UID)
    }

Ricki Hirner's avatar
Ricki Hirner committed
187
    protected open fun populateStructuredName(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201
        val contact = requireNotNull(contact)
        contact.displayName = row.getAsString(StructuredName.DISPLAY_NAME)

        contact.prefix = row.getAsString(StructuredName.PREFIX)
        contact.givenName = row.getAsString(StructuredName.GIVEN_NAME)
        contact.middleName = row.getAsString(StructuredName.MIDDLE_NAME)
        contact.familyName = row.getAsString(StructuredName.FAMILY_NAME)
        contact.suffix = row.getAsString(StructuredName.SUFFIX)

        contact.phoneticGivenName = row.getAsString(StructuredName.PHONETIC_GIVEN_NAME)
        contact.phoneticMiddleName = row.getAsString(StructuredName.PHONETIC_MIDDLE_NAME)
        contact.phoneticFamilyName = row.getAsString(StructuredName.PHONETIC_FAMILY_NAME)
    }

Ricki Hirner's avatar
Ricki Hirner committed
202
    protected open fun populatePhoneNumber(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        val number = Telephone(row.getAsString(Phone.NUMBER))
        val labeledNumber = LabeledProperty(number)

        when (row.getAsInteger(Phone.TYPE)) {
            Phone.TYPE_HOME ->
                number.types += TelephoneType.HOME
            Phone.TYPE_MOBILE ->
                number.types += TelephoneType.CELL
            Phone.TYPE_WORK ->
                number.types += TelephoneType.WORK
            Phone.TYPE_FAX_WORK -> {
                number.types += TelephoneType.FAX
                number.types += TelephoneType.WORK
            }
            Phone.TYPE_FAX_HOME -> {
                number.types += TelephoneType.FAX
                number.types += TelephoneType.HOME
            }
            Phone.TYPE_PAGER ->
                number.types += TelephoneType.PAGER
            Phone.TYPE_CALLBACK ->
                number.types += Contact.PHONE_TYPE_CALLBACK
            Phone.TYPE_CAR ->
                number.types += TelephoneType.CAR
            Phone.TYPE_COMPANY_MAIN ->
                number.types += Contact.PHONE_TYPE_COMPANY_MAIN
            Phone.TYPE_ISDN ->
                number.types += TelephoneType.ISDN
            Phone.TYPE_MAIN ->
                number.types += TelephoneType.VOICE
            Phone.TYPE_OTHER_FAX ->
                number.types += TelephoneType.FAX
            Phone.TYPE_RADIO ->
                number.types += Contact.PHONE_TYPE_RADIO
            Phone.TYPE_TELEX ->
                number.types += TelephoneType.TEXTPHONE
            Phone.TYPE_TTY_TDD ->
                number.types += TelephoneType.TEXT
            Phone.TYPE_WORK_MOBILE -> {
                number.types += TelephoneType.CELL
                number.types += TelephoneType.WORK
            }
            Phone.TYPE_WORK_PAGER -> {
                number.types += TelephoneType.PAGER
                number.types += TelephoneType.WORK
            }
            Phone.TYPE_ASSISTANT ->
                number.types += Contact.PHONE_TYPE_ASSISTANT
            Phone.TYPE_MMS ->
                number.types += Contact.PHONE_TYPE_MMS
            Phone.TYPE_CUSTOM -> {
                    row.getAsString(CommonDataKinds.Phone.LABEL)?.let {
                        labeledNumber.label = it
                        number.types += TelephoneType.get(labelToXName(it))
                    }
                }
        }
        if (row.getAsInteger(CommonDataKinds.Phone.IS_PRIMARY) != 0)
            number.pref = 1

        contact!!.phoneNumbers += labeledNumber
    }

Ricki Hirner's avatar
Ricki Hirner committed
266
    protected open fun populateEmail(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        val email = ezvcard.property.Email(row.getAsString(Email.ADDRESS))
        val labeledEmail = LabeledProperty(email)

        when (row.getAsInteger(Email.TYPE)) {
            Email.TYPE_HOME ->
                email.types += EmailType.HOME
            Email.TYPE_WORK ->
                email.types += EmailType.WORK
            Email.TYPE_MOBILE ->
                email.types += Contact.EMAIL_TYPE_MOBILE
            Email.TYPE_CUSTOM ->
                row.getAsString(Email.LABEL)?.let {
                    labeledEmail.label = it
                    email.types += EmailType.get(labelToXName(it))
                }
        }
        if (row.getAsInteger(Email.IS_PRIMARY) != 0)
            email.pref = 1

        contact!!.emails += labeledEmail
    }

Ricki Hirner's avatar
Ricki Hirner committed
289
    protected open fun populatePhoto(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
290 291 292 293 294 295
        val contact = requireNotNull(contact)
        if (row.containsKey(Photo.PHOTO_FILE_ID)) {
            val photoUri = Uri.withAppendedPath(
                    rawContactSyncURI(),
                    RawContacts.DisplayPhoto.CONTENT_DIRECTORY)
            try {
296 297
                addressBook.provider!!.openAssetFile(photoUri, "r")?.let { afd ->
                    afd.createInputStream().use { contact.photo = IOUtils.toByteArray(it) }
Ricki Hirner's avatar
Ricki Hirner committed
298 299 300 301 302 303 304 305
                }
            } catch(e: IOException) {
                Constants.log.log(Level.WARNING, "Couldn't read local contact photo file", e)
            }
        } else
            contact.photo = row.getAsByteArray(Photo.PHOTO)
    }

Ricki Hirner's avatar
Ricki Hirner committed
306
    protected open fun populateOrganization(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
307 308 309 310
        val contact = requireNotNull(contact)
        
        val company = row.getAsString(Organization.COMPANY)
        val department = row.getAsString(Organization.DEPARTMENT)
311
        if (company != null || department != null) {
Ricki Hirner's avatar
Ricki Hirner committed
312
            val org = ezvcard.property.Organization()
313 314
            company?.let { org.values += it }
            department?.let { org.values += it }
Ricki Hirner's avatar
Ricki Hirner committed
315 316 317
            contact.organization = org
        }

318 319
        row.getAsString(Organization.TITLE)?.let { contact.jobTitle = it }
        row.getAsString(Organization.JOB_DESCRIPTION)?.let { contact.jobDescription = it }
Ricki Hirner's avatar
Ricki Hirner committed
320 321
    }

Ricki Hirner's avatar
Ricki Hirner committed
322
    protected open fun populateIMPP(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
323
        val handle = row.getAsString(Im.DATA)
324
        if (handle == null) {
Ricki Hirner's avatar
Ricki Hirner committed
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
            Constants.log.warning("Ignoring instant messenger record without handle")
            return
        }

        var impp: Impp? = null
        when (row.getAsInteger(Im.PROTOCOL)) {
            Im.PROTOCOL_AIM ->
                impp = Impp.aim(handle)
            Im.PROTOCOL_MSN ->
                impp = Impp.msn(handle)
            Im.PROTOCOL_YAHOO ->
                impp = Impp.yahoo(handle)
            Im.PROTOCOL_SKYPE ->
                impp = Impp.skype(handle)
            Im.PROTOCOL_QQ ->
                impp = Impp("qq", handle)
            Im.PROTOCOL_GOOGLE_TALK ->
                impp = Impp("google-talk", handle)
            Im.PROTOCOL_ICQ ->
                impp = Impp.icq(handle)
            Im.PROTOCOL_JABBER ->
                impp = Impp.xmpp(handle)
            Im.PROTOCOL_NETMEETING ->
                impp = Impp("netmeeting", handle)
            Im.PROTOCOL_CUSTOM ->
                try {
                    impp = Impp(toURIScheme(row.getAsString(Im.CUSTOM_PROTOCOL)), handle)
                } catch(e: IllegalArgumentException) {
                    Constants.log.warning("Messenger type/value can't be expressed as URI; ignoring")
                }
        }

        impp?.let { impp ->
            val labeledImpp = LabeledProperty(impp)

            when (row.getAsInteger(Im.TYPE)) {
                Im.TYPE_HOME ->
                    impp.types += ImppType.HOME
                Im.TYPE_WORK ->
                    impp.types += ImppType.WORK
                Im.TYPE_CUSTOM ->
                    row.getAsString(Im.LABEL)?.let {
                        labeledImpp.label = it
                        impp.types.add(ImppType.get(labelToXName(it)))
                    }
            }

            contact!!.impps += labeledImpp
        }
    }

Ricki Hirner's avatar
Ricki Hirner committed
376
    protected open fun populateNickname(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
        row.getAsString(Nickname.NAME)?.let { name ->
            val nick = ezvcard.property.Nickname()
            nick.values += name

            when (row.getAsInteger(Nickname.TYPE)) {
                Nickname.TYPE_MAIDEN_NAME ->
                    nick.type = Contact.NICKNAME_TYPE_MAIDEN_NAME
                Nickname.TYPE_SHORT_NAME ->
                    nick.type = Contact.NICKNAME_TYPE_SHORT_NAME
                Nickname.TYPE_INITIALS ->
                    nick.type = Contact.NICKNAME_TYPE_INITIALS
                Nickname.TYPE_OTHER_NAME ->
                    nick.type = Contact.NICKNAME_TYPE_OTHER_NAME
                Nickname.TYPE_CUSTOM ->
                    row.getAsString(Nickname.LABEL)?.let { nick.type = labelToXName(it) }
            }

            contact!!.nickName = nick
        }
    }

Ricki Hirner's avatar
Ricki Hirner committed
398
    protected open fun populateNote(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
399 400 401
        contact!!.note = row.getAsString(Note.NOTE)
    }

Ricki Hirner's avatar
Ricki Hirner committed
402
    protected open fun populateStructuredPostal(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
        val address = Address()
        val labeledAddress = LabeledProperty(address)

        address.label = row.getAsString(StructuredPostal.FORMATTED_ADDRESS)
        when (row.getAsInteger(StructuredPostal.TYPE)) {
            StructuredPostal.TYPE_HOME ->
                address.types += AddressType.HOME
            StructuredPostal.TYPE_WORK ->
                address.types += AddressType.WORK
            StructuredPostal.TYPE_CUSTOM -> {
                row.getAsString(StructuredPostal.LABEL)?.let {
                    labeledAddress.label = it
                    address.types += AddressType.get(labelToXName(it))
                }
            }
        }
        address.streetAddress = row.getAsString(StructuredPostal.STREET)
        address.poBox = row.getAsString(StructuredPostal.POBOX)
        address.extendedAddress = row.getAsString(StructuredPostal.NEIGHBORHOOD)
        address.locality = row.getAsString(StructuredPostal.CITY)
        address.region = row.getAsString(StructuredPostal.REGION)
        address.postalCode = row.getAsString(StructuredPostal.POSTCODE)
        address.country = row.getAsString(StructuredPostal.COUNTRY)
        contact!!.addresses += labeledAddress
    }

Ricki Hirner's avatar
Ricki Hirner committed
429
    protected open fun populateWebsite(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
        val url = Url(row.getAsString(Website.URL))
        val labeledUrl = LabeledProperty(url)

        when (row.getAsInteger(Website.TYPE)) {
            Website.TYPE_HOMEPAGE ->
                url.type = Contact.URL_TYPE_HOMEPAGE
            Website.TYPE_BLOG ->
                url.type = Contact.URL_TYPE_BLOG
            Website.TYPE_PROFILE ->
                url.type = Contact.URL_TYPE_PROFILE
            Website.TYPE_HOME ->
                url.type = "home"
            Website.TYPE_WORK ->
                url.type = "work"
            Website.TYPE_FTP ->
                url.type = Contact.URL_TYPE_FTP
            Website.TYPE_CUSTOM ->
                row.getAsString(Website.LABEL)?.let {
                    url.type = labelToXName(it)
                    labeledUrl.label = it
                }
        }
        contact!!.urls += labeledUrl
    }

Ricki Hirner's avatar
Ricki Hirner committed
455
    protected open fun populateEvent(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
        val dateStr = row.getAsString(CommonDataKinds.Event.START_DATE)
        var full: Date? = null
        var partial: PartialDate? = null
        val fullFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
        try {
            full = fullFormat.parse(dateStr)
        } catch(e: ParseException) {
            try {
                partial = PartialDate.parse(dateStr)
            } catch (e: IllegalArgumentException) {
                Constants.log.log(Level.WARNING, "Couldn't parse birthday/anniversary date from database", e)
            }
        }

        if (full != null || partial != null)
            when (row.getAsInteger(Event.TYPE)) {
                Event.TYPE_ANNIVERSARY ->
                    contact!!.anniversary = if (full != null) Anniversary(full) else Anniversary(partial)
                Event.TYPE_BIRTHDAY ->
                    contact!!.birthDay = if (full != null) Birthday(full) else Birthday(partial)
            }
    }

Ricki Hirner's avatar
Ricki Hirner committed
479
    protected open fun populateRelation(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
        row.getAsString(Relation.NAME)?.let { name ->
            val related = Related()
            related.text = name

            when (row.getAsInteger(Relation.TYPE)) {
                Relation.TYPE_ASSISTANT,
                Relation.TYPE_MANAGER ->
                    related.types += RelatedType.CO_WORKER
                Relation.TYPE_BROTHER,
                Relation.TYPE_SISTER ->
                    related.types += RelatedType.SIBLING
                Relation.TYPE_CHILD ->
                    related.types += RelatedType.CHILD
                Relation.TYPE_FRIEND ->
                    related.types += RelatedType.FRIEND
                Relation.TYPE_FATHER,
                Relation.TYPE_MOTHER,
                Relation.TYPE_PARENT ->
                    related.types += RelatedType.PARENT
                Relation.TYPE_DOMESTIC_PARTNER,
                Relation.TYPE_PARTNER,
                Relation.TYPE_SPOUSE ->
                    related.types += RelatedType.SPOUSE
                Relation.TYPE_RELATIVE ->
                    related.types += RelatedType.KIN
                Relation.TYPE_CUSTOM ->
                    row.getAsString(Relation.LABEL)?.split(",")?.forEach {
                        related.types += RelatedType.get(it.trim())
                    }
            }

            contact!!.relations += related
        }
    }

Ricki Hirner's avatar
Ricki Hirner committed
515
    protected open fun populateSipAddress(row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
        try {
            val impp = Impp("sip:" + row.getAsString(SipAddress.SIP_ADDRESS))
            val labeledImpp = LabeledProperty(impp)

            when (row.getAsInteger(SipAddress.TYPE)) {
                SipAddress.TYPE_HOME ->
                    impp.types += ImppType.HOME
                SipAddress.TYPE_WORK ->
                    impp.types += ImppType.WORK
                SipAddress.TYPE_CUSTOM ->
                    row.getAsString(SipAddress.LABEL)?.let {
                        labeledImpp.label = it
                        impp.types += ImppType.get(labelToXName(it))
                    }
            }
            contact!!.impps.add(labeledImpp)
        } catch(e: IllegalArgumentException) {
            Constants.log.warning("Ignoring invalid locally stored SIP address")
        }
    }

    /**
     * Override this to handle custom data rows, for example to add additional
     * information to [contact].
     * @param mimeType    MIME type of the row
     * @param row         values of the row
     */
Ricki Hirner's avatar
Ricki Hirner committed
543
    protected open fun populateData(mimeType: String, row: ContentValues) {
Ricki Hirner's avatar
Ricki Hirner committed
544 545 546 547
    }


    fun create(): Uri {
548
        val batch = BatchOperation(addressBook.provider!!)
Ricki Hirner's avatar
Ricki Hirner committed
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568

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

        insertDataRows(batch)

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

        // we need a raw contact ID to insert the photo
        insertPhoto(contact!!.photo)

        return result.uri
    }

    fun update(contact: Contact): Int {
        this.contact = contact

569
        val batch = BatchOperation(addressBook.provider!!)
Ricki Hirner's avatar
Ricki Hirner committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588

        val builder = ContentProviderOperation.newUpdate(rawContactSyncURI())
        buildContact(builder, true)
        batch.enqueue(BatchOperation.Operation(builder))

        // delete known data rows before adding the new ones; don't delete group memberships!
        batch.enqueue(BatchOperation.Operation(
                ContentProviderOperation.newDelete(dataSyncURI())
                .withSelection(RawContacts.Data.RAW_CONTACT_ID + "=? AND " + RawContacts.Data.MIMETYPE + " NOT IN (?,?)",
                        arrayOf(id.toString(), GroupMembership.CONTENT_ITEM_TYPE, CachedGroupMembership.CONTENT_ITEM_TYPE))
        ))
        insertDataRows(batch)
        val results = batch.commit()

        insertPhoto(contact.photo)

        return results
    }

Ricki Hirner's avatar
Ricki Hirner committed
589
    fun delete() = addressBook.provider!!.delete(rawContactSyncURI(), null, null)
Ricki Hirner's avatar
Ricki Hirner committed
590 591


Ricki Hirner's avatar
Ricki Hirner committed
592
    protected open fun buildContact(builder: ContentProviderOperation.Builder, update: Boolean) {
Ricki Hirner's avatar
Ricki Hirner committed
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
        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, contact!!.uid)

        Constants.log.log(Level.FINER, "Built RawContact data row", builder.build())
    }


    /**
     * Inserts the data rows for a given raw contact.
     * Override this (and call [super]!) to add custom data rows,
     * for example generated from some properties of [contact].
     * @param  batch    batch operation used to insert the data rows
Ricki Hirner's avatar
Ricki Hirner committed
612
     * @throws RemoteException on contact provider errors
Ricki Hirner's avatar
Ricki Hirner committed
613
     */
Ricki Hirner's avatar
Ricki Hirner committed
614
    protected open fun insertDataRows(batch: BatchOperation) {
Ricki Hirner's avatar
Ricki Hirner committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
        val contact = requireNotNull(contact)

        insertStructuredName(batch)
        insertNickname(batch)
        insertOrganization(batch)

        contact.phoneNumbers.forEach { insertPhoneNumber(batch, it) }
        contact.emails.forEach { insertEmail(batch, it) }
        contact.impps.forEach { insertIMPP(batch, it) }     // handles SIP addresses, too
        contact.addresses.forEach { insertStructuredPostal(batch, it) }

        insertNote(batch)
        contact.urls.forEach { insertWebsite(batch, it) }
        contact.relations.forEach { insertRelation(batch, it) }

        contact.anniversary?.let { insertEvent(batch, Event.TYPE_ANNIVERSARY, it) }
        contact.birthDay?.let { insertEvent(batch, Event.TYPE_BIRTHDAY, it) }
    }

Ricki Hirner's avatar
Ricki Hirner committed
634
    protected open fun insertStructuredName(batch: BatchOperation) {
Ricki Hirner's avatar
Ricki Hirner committed
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
        val contact = requireNotNull(contact)
        if     (contact.displayName == null &&
                contact.prefix == null &&
                contact.givenName == null && contact.middleName == null && contact.familyName == null &&
                contact.suffix == null &&
                contact.phoneticGivenName == null && contact.phoneticMiddleName == null && contact.phoneticFamilyName == null)
            return

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, StructuredName.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(StructuredName.RAW_CONTACT_ID, id)
        }
        builder .withValue(RawContacts.Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(StructuredName.DISPLAY_NAME, contact.displayName)
                .withValue(StructuredName.PREFIX, contact.prefix)
                .withValue(StructuredName.GIVEN_NAME, contact.givenName)
                .withValue(StructuredName.MIDDLE_NAME, contact.middleName)
                .withValue(StructuredName.FAMILY_NAME, contact.familyName)
                .withValue(StructuredName.SUFFIX, contact.suffix)
                .withValue(StructuredName.PHONETIC_GIVEN_NAME, contact.phoneticGivenName)
                .withValue(StructuredName.PHONETIC_MIDDLE_NAME, contact.phoneticMiddleName)
                .withValue(StructuredName.PHONETIC_FAMILY_NAME, contact.phoneticFamilyName)
        Constants.log.log(Level.FINER, "Built StructuredName data row", builder.build())
        batch.enqueue(op)
    }

Ricki Hirner's avatar
Ricki Hirner committed
665
    protected open fun insertPhoneNumber(batch: BatchOperation, labeledNumber: LabeledProperty<Telephone>) {
Ricki Hirner's avatar
Ricki Hirner committed
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
        val number = labeledNumber.property

        val types = number.types

        // preferred number?
        var pref: Int? = null
        try {
            pref = number.pref
        } catch(e: IllegalStateException) {
            Constants.log.log(Level.FINER, "Can't understand phone number PREF", e)
        }
        var is_primary = pref != null
        if (types.contains(TelephoneType.PREF)) {
            is_primary = true
            types -= TelephoneType.PREF
        }

        var typeCode: Int = Phone.TYPE_OTHER
        var typeLabel: String? = null
        if (labeledNumber.label != null) {
            typeCode = Phone.TYPE_CUSTOM
            typeLabel = labeledNumber.label
        } else {
            when {
                // 1 Android type <-> 2 VCard types: fax, cell, pager
                types.contains(TelephoneType.FAX) ->
                    typeCode = when {
                        types.contains(TelephoneType.HOME) -> Phone.TYPE_FAX_HOME
                        types.contains(TelephoneType.WORK) -> Phone.TYPE_FAX_WORK
                        else                               -> Phone.TYPE_OTHER_FAX
                    }
                types.contains(TelephoneType.CELL) ->
                    typeCode = if (types.contains(TelephoneType.WORK))
                        Phone.TYPE_WORK_MOBILE
                    else
                        Phone.TYPE_MOBILE
                types.contains(TelephoneType.PAGER) ->
                    typeCode = if (types.contains(TelephoneType.WORK))
                        Phone.TYPE_WORK_PAGER
                    else
                        Phone.TYPE_PAGER

                // types with 1:1 translation
                types.contains(TelephoneType.HOME) ->
                    typeCode = Phone.TYPE_HOME
                types.contains(TelephoneType.WORK) ->
                    typeCode = Phone.TYPE_WORK
                types.contains(Contact.PHONE_TYPE_CALLBACK) ->
                    typeCode = Phone.TYPE_CALLBACK
                types.contains(TelephoneType.CAR) ->
                    typeCode = Phone.TYPE_CAR
                types.contains(Contact.PHONE_TYPE_COMPANY_MAIN) ->
                    typeCode = Phone.TYPE_COMPANY_MAIN
                types.contains(TelephoneType.ISDN) ->
                    typeCode = Phone.TYPE_ISDN
                types.contains(Contact.PHONE_TYPE_RADIO) ->
                    typeCode = Phone.TYPE_RADIO
                types.contains(Contact.PHONE_TYPE_ASSISTANT) ->
                    typeCode = Phone.TYPE_ASSISTANT
                types.contains(Contact.PHONE_TYPE_MMS) ->
                    typeCode = Phone.TYPE_MMS

                types.contains(TelephoneType.VOICE) ||
                types.contains(TelephoneType.TEXT) -> {}

                types.isNotEmpty() -> {
                    val type = types.first()
                    typeCode = Phone.TYPE_CUSTOM
                    typeLabel = xNameToLabel(type.value)
                }
            }
        }

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, Phone.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(Phone.RAW_CONTACT_ID, id)
        }
        builder	.withValue(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
                .withValue(Phone.NUMBER, number.text)
                .withValue(Phone.TYPE, typeCode)
                .withValue(Phone.LABEL, typeLabel)
                .withValue(Phone.IS_PRIMARY, if (is_primary) 1 else 0)
                .withValue(Phone.IS_SUPER_PRIMARY, if (is_primary) 1 else 0)
        Constants.log.log(Level.FINER, "Built Phone data row", builder.build())
        batch.enqueue(op)
    }

Ricki Hirner's avatar
Ricki Hirner committed
757
    protected open fun insertEmail(batch: BatchOperation, labeledEmail: LabeledProperty<ezvcard.property.Email>) {
Ricki Hirner's avatar
Ricki Hirner committed
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
        val email = labeledEmail.property

        val types = email.types

        // preferred email address?
        var pref: Int? = null
        try {
            pref = email.pref
        } catch(e: IllegalStateException) {
            Constants.log.log(Level.FINER, "Can't understand email PREF", e)
        }
        var is_primary = pref != null
        if (types.contains(EmailType.PREF)) {
            is_primary = true
            types -= EmailType.PREF
        }

        var typeCode: Int = 0
        var typeLabel: String? = null
        if (labeledEmail.label != null) {
            typeCode = Email.TYPE_CUSTOM
            typeLabel = labeledEmail.label
        } else {
            for (type in types)
                when (type) {
                    EmailType.HOME -> typeCode = Email.TYPE_HOME
                    EmailType.WORK -> typeCode = Email.TYPE_WORK
                    Contact.EMAIL_TYPE_MOBILE -> typeCode = Email.TYPE_MOBILE
                }
            if (typeCode == 0) {
                if (email.types.isEmpty())
                    typeCode = Email.TYPE_OTHER
                else {
                    typeCode = Email.TYPE_CUSTOM
                    typeLabel = xNameToLabel(types.first().value)
                }
            }
        }

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, Email.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(Email.RAW_CONTACT_ID, id)
        }
        builder	.withValue(Email.MIMETYPE, Email.CONTENT_ITEM_TYPE)
                .withValue(Email.ADDRESS, email.value)
                .withValue(Email.TYPE, typeCode)
                .withValue(Email.LABEL, typeLabel)
                .withValue(Email.IS_PRIMARY, if (is_primary) 1 else 0)
                .withValue(Phone.IS_SUPER_PRIMARY, if (is_primary) 1 else 0)
        Constants.log.log(Level.FINER, "Built Email data row", builder.build())
        batch.enqueue(op)
    }

Ricki Hirner's avatar
Ricki Hirner committed
815
    protected open fun insertOrganization(batch: BatchOperation) {
Ricki Hirner's avatar
Ricki Hirner committed
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
        val contact = requireNotNull(contact)
        if (contact.organization == null && contact.jobTitle == null && contact.jobDescription == null)
            return

        var company: String? = null
        var department: String? = null
        val organization = contact.organization
        organization?.let {
            val org = it.values.iterator()
            if (org.hasNext())
                company = org.next()
            if (org.hasNext())
                department = org.next()
        }

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, Organization.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(Organization.RAW_CONTACT_ID, id)
        }
        builder .withValue(Organization.MIMETYPE, Organization.CONTENT_ITEM_TYPE)
                .withValue(Organization.COMPANY, company)
                .withValue(Organization.DEPARTMENT, department)
                .withValue(Organization.TITLE, contact.jobTitle)
                .withValue(Organization.JOB_DESCRIPTION, contact.jobDescription)
        Constants.log.log(Level.FINER, "Built Organization data row", builder.build())
        batch.enqueue(op)
    }

Ricki Hirner's avatar
Ricki Hirner committed
848
    protected open fun insertIMPP(batch: BatchOperation, labeledImpp: LabeledProperty<Impp>) {
Ricki Hirner's avatar
Ricki Hirner committed
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
        val impp = labeledImpp.property

        var typeCode: Int = Im.TYPE_OTHER
        var typeLabel: String? = null

        if (labeledImpp.label != null) {
            typeCode = Im.TYPE_CUSTOM
            typeLabel = labeledImpp.label
        } else {
            for (type in impp.types)
                when (type) {
                    ImppType.HOME,
                    ImppType.PERSONAL -> typeCode = Im.TYPE_HOME
                    ImppType.WORK,
                    ImppType.BUSINESS -> typeCode = Im.TYPE_WORK
                }
            if (typeCode == Im.TYPE_OTHER && impp.types.isNotEmpty()) {
                typeCode = Im.TYPE_CUSTOM
                typeLabel = xNameToLabel(impp.types.first().value)
            }
        }

        val protocol = impp.protocol
        if (protocol == null) {
            Constants.log.warning("Ignoring IMPP address without protocol")
            return
        }

        var protocolCode = 0
        var protocolLabel: String? = null

        // SIP addresses are IMPP entries in the VCard but locally stored in SipAddress rather than Im
        var sipAddress = false

        when {
            impp.isAim -> protocolCode = Im.PROTOCOL_AIM
            impp.isMsn -> protocolCode = Im.PROTOCOL_MSN
            impp.isYahoo -> protocolCode = Im.PROTOCOL_YAHOO
            impp.isSkype -> protocolCode = Im.PROTOCOL_SKYPE
            protocol.equals("qq", true) -> protocolCode = Im.PROTOCOL_QQ
            protocol.equals("google-talk", true) -> protocolCode = Im.PROTOCOL_GOOGLE_TALK
            impp.isIcq -> protocolCode = Im.PROTOCOL_ICQ
            impp.isXmpp || protocol.equals("jabber", true) -> protocolCode = Im.PROTOCOL_JABBER
            protocol.equals("netmeeting", true) -> protocolCode = Im.PROTOCOL_NETMEETING
            protocol.equals("sip", true) -> sipAddress = true
            else -> {
                protocolCode = Im.PROTOCOL_CUSTOM
                protocolLabel = protocol
            }
        }

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, Im.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(Im.RAW_CONTACT_ID, id)
        }
        if (sipAddress) {
            // save as SIP address
            builder .withValue(SipAddress.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE)
                    .withValue(SipAddress.DATA, impp.handle)
                    .withValue(SipAddress.TYPE, typeCode)
                    .withValue(SipAddress.LABEL, typeLabel)
            Constants.log.log(Level.FINER, "Built SipAddress data row", builder.build())
        } else {
            // save as IM address
            builder	.withValue(Im.MIMETYPE, Im.CONTENT_ITEM_TYPE)
                    .withValue(Im.DATA, impp.handle)
                    .withValue(Im.TYPE, typeCode)
                    .withValue(Im.LABEL, typeLabel)
                    .withValue(Im.PROTOCOL, protocolCode)
                    .withValue(Im.CUSTOM_PROTOCOL, protocolLabel)
            Constants.log.log(Level.FINER, "Built Im data row", builder.build())
        }
        batch.enqueue(op)
    }

Ricki Hirner's avatar
Ricki Hirner committed
928
    protected open fun insertNickname(batch: BatchOperation) {
Ricki Hirner's avatar
Ricki Hirner committed
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
        val nick = contact!!.nickName
        if (nick == null || nick.values.isEmpty())
            return

        val typeCode: Int
        var typeLabel: String? = null

        val type = nick.type
        typeCode = when (type) {
            Contact.NICKNAME_TYPE_MAIDEN_NAME -> Nickname.TYPE_MAIDEN_NAME
            Contact.NICKNAME_TYPE_SHORT_NAME ->  Nickname.TYPE_SHORT_NAME
            Contact.NICKNAME_TYPE_INITIALS ->    Nickname.TYPE_INITIALS
            Contact.NICKNAME_TYPE_OTHER_NAME ->  Nickname.TYPE_OTHER_NAME
            null                             ->  Nickname.TYPE_DEFAULT
            else -> {
                typeLabel = xNameToLabel(type)
                Nickname.TYPE_CUSTOM
            }
        }

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, Nickname.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(Nickname.RAW_CONTACT_ID, id)
        }
        builder .withValue(Nickname.MIMETYPE, Nickname.CONTENT_ITEM_TYPE)
                .withValue(Nickname.NAME, nick.values.first())
                .withValue(Nickname.TYPE, typeCode)
                .withValue(Nickname.LABEL, typeLabel)
        Constants.log.log(Level.FINER, "Built Nickname data row", builder.build())
        batch.enqueue(op)
    }

Ricki Hirner's avatar
Ricki Hirner committed
965
    protected open fun insertNote(batch: BatchOperation) {
Ricki Hirner's avatar
Ricki Hirner committed
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
        val contact = requireNotNull(contact)
        if (contact.note.isNullOrEmpty())
            return

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, Note.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(Note.RAW_CONTACT_ID, id)
        }
        builder .withValue(Note.MIMETYPE, Note.CONTENT_ITEM_TYPE)
                .withValue(Note.NOTE, contact.note)
        Constants.log.log(Level.FINER, "Built Note data row", builder.build())
        batch.enqueue(op)
    }

Ricki Hirner's avatar
Ricki Hirner committed
984
    protected open fun insertStructuredPostal(batch: BatchOperation, labeledAddress: LabeledProperty<Address>) {
Ricki Hirner's avatar
Ricki Hirner committed
985 986 987 988 989 990 991 992 993 994 995 996
        val address = labeledAddress.property

        var formattedAddress = address.label
        if (formattedAddress.isNullOrEmpty()) {
            /*	no formatted address from server, built it like this:
             *
             *  street po.box (extended)
             *	postcode city
             *	region
             *	COUNTRY
             */

997 998
            val lineStreet = arrayOf(address.streetAddress, address.poBox, address.extendedAddress).filterNot { it.isNullOrEmpty() }.joinToString(" ")
            val lineLocality = arrayOf(address.postalCode, address.locality).filterNot { it.isNullOrEmpty() }.joinToString(" ")
Ricki Hirner's avatar
Ricki Hirner committed
999 1000

            val lines = LinkedList<String>()
Ricki Hirner's avatar
Ricki Hirner committed
1001
            if (!lineStreet.isEmpty())
Ricki Hirner's avatar
Ricki Hirner committed
1002
                lines += lineStreet
Ricki Hirner's avatar
Ricki Hirner committed
1003
            if (!lineLocality.isEmpty())
Ricki Hirner's avatar
Ricki Hirner committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
                lines += lineLocality
            if (!address.region.isNullOrEmpty())
                lines += address.region
            if (!address.country.isNullOrEmpty())
                lines += address.country.toUpperCase()

            formattedAddress = lines.joinToString("\n")
        }

        var typeCode = StructuredPostal.TYPE_OTHER
        var typeLabel: String? = null
        if (labeledAddress.label != null) {
            typeCode = StructuredPostal.TYPE_CUSTOM
            typeLabel = labeledAddress.label
        } else {
            for (type in address.types)
                when (type) {
                    AddressType.HOME -> typeCode = StructuredPostal.TYPE_HOME
                    AddressType.WORK -> typeCode = StructuredPostal.TYPE_WORK
                }
            if (typeCode == StructuredPostal.TYPE_OTHER && address.types.isNotEmpty()) {
                typeCode = StructuredPostal.TYPE_CUSTOM
                typeLabel = xNameToLabel(address.types.first().value)
            }
        }

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, StructuredPostal.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(StructuredPostal.RAW_CONTACT_ID, id)
        }
        builder .withValue(StructuredPostal.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE)
                .withValue(StructuredPostal.FORMATTED_ADDRESS, formattedAddress)
                .withValue(StructuredPostal.TYPE, typeCode)
                .withValue(StructuredPostal.LABEL, typeLabel)
                .withValue(StructuredPostal.STREET, address.streetAddress)
                .withValue(StructuredPostal.POBOX, address.poBox)
                .withValue(StructuredPostal.NEIGHBORHOOD, address.extendedAddress)
                .withValue(StructuredPostal.CITY, address.locality)
                .withValue(StructuredPostal.REGION, address.region)
                .withValue(StructuredPostal.POSTCODE, address.postalCode)
                .withValue(StructuredPostal.COUNTRY, address.country)
        Constants.log.log(Level.FINER, "Built StructuredPostal data row", builder.build())
        batch.enqueue(op)
    }

Ricki Hirner's avatar
Ricki Hirner committed
1053
    protected open fun insertWebsite(batch: BatchOperation, labeledUrl: LabeledProperty<Url>) {
Ricki Hirner's avatar
Ricki Hirner committed
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        val url = labeledUrl.property

        val typeCode: Int
        var typeLabel: String? = null
        if (labeledUrl.label != null) {
            typeCode = Website.TYPE_CUSTOM
            typeLabel = labeledUrl.label
        } else {
            val type = url.type
            typeCode = when (type) {
                Contact.URL_TYPE_HOMEPAGE -> Website.TYPE_HOMEPAGE
                Contact.URL_TYPE_BLOG ->     Website.TYPE_BLOG
                Contact.URL_TYPE_PROFILE ->  Website.TYPE_PROFILE
                "home" ->                    Website.TYPE_HOME
                "work" ->                    Website.TYPE_WORK
                Contact.URL_TYPE_FTP ->      Website.TYPE_FTP
                null ->                      Website.TYPE_OTHER
                else -> {
                    typeLabel = xNameToLabel(type)
                    Website.TYPE_CUSTOM
                }
            }
        }

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, Website.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(Website.RAW_CONTACT_ID, id)
        }
        builder .withValue(Website.MIMETYPE, Website.CONTENT_ITEM_TYPE)
                .withValue(Website.URL, url.value)
                .withValue(Website.TYPE, typeCode)
                .withValue(Website.LABEL, typeLabel)
        Constants.log.log(Level.FINER, "Built Website data row", builder.build())
        batch.enqueue(op)
    }

Ricki Hirner's avatar
Ricki Hirner committed
1094
    protected open fun insertEvent(batch: BatchOperation, type: Int, dateOrTime: DateOrTimeProperty) {
Ricki Hirner's avatar
Ricki Hirner committed
1095
        val dateStr: String
Ricki Hirner's avatar
Ricki Hirner committed
1096
        dateStr = when {
Ricki Hirner's avatar
Ricki Hirner committed
1097 1098
            dateOrTime.date != null -> {
                val format = SimpleDateFormat("yyyy-MM-dd", Locale.US)
Ricki Hirner's avatar
Ricki Hirner committed
1099
                format.format(dateOrTime.date)
Ricki Hirner's avatar
Ricki Hirner committed
1100 1101
            }
            dateOrTime.partialDate != null ->
Ricki Hirner's avatar
Ricki Hirner committed
1102
                dateOrTime.partialDate.toString()
Ricki Hirner's avatar
Ricki Hirner committed
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
            else -> {
                Constants.log.log(Level.WARNING, "Ignoring date/time without (partial) date", dateOrTime)
                return
            }
        }

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, Event.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(Event.RAW_CONTACT_ID, id)
        }
        builder .withValue(Event.MIMETYPE, Event.CONTENT_ITEM_TYPE)
                .withValue(Event.TYPE, type)
                .withValue(Event.START_DATE, dateStr)
        batch.enqueue(op)
        Constants.log.log(Level.FINER, "Built Event data row", builder.build())
    }

Ricki Hirner's avatar
Ricki Hirner committed
1124
    protected open fun insertRelation(batch: BatchOperation, related: Related) {
Ricki Hirner's avatar
Ricki Hirner committed
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
        if (related.text.isNullOrEmpty())
            return

        var typeCode = Relation.TYPE_CUSTOM

        val labels = LinkedList<String>()
        for (type in related.types)
            when (type) {
                RelatedType.CHILD  -> typeCode = Relation.TYPE_CHILD
                RelatedType.SPOUSE -> typeCode = Relation.TYPE_PARTNER
                RelatedType.FRIEND -> typeCode = Relation.TYPE_FRIEND
                RelatedType.KIN    -> typeCode = Relation.TYPE_RELATIVE
                RelatedType.PARENT -> typeCode = Relation.TYPE_PARENT
                else               -> labels += type.value
            }

        val op: BatchOperation.Operation
        val builder = ContentProviderOperation.newInsert(dataSyncURI())
        if (id == null)
            op = BatchOperation.Operation(builder, Relation.RAW_CONTACT_ID, 0)
        else {
            op = BatchOperation.Operation(builder)
            builder.withValue(Relation.RAW_CONTACT_ID, id)
        }
        builder .withValue(Relation.MIMETYPE, Relation.CONTENT_ITEM_TYPE)
                .withValue(Relation.NAME, related.text)
                .withValue(Relation.TYPE, typeCode)
                .withValue(Relation.LABEL, StringUtils.trimToNull(labels.joinToString(", ")))
        Constants.log.log(Level.FINER, "Built Relation data row", builder.build())
        batch.enqueue(op)
    }

Ricki Hirner's avatar
Ricki Hirner committed
1157
    protected open fun insertPhoto(orig: ByteArray?) {
Ricki Hirner's avatar
Ricki Hirner committed
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
        if (orig == null)
            return

        // The following approach would be correct, but it doesn't work:
        // the ContactsProvider handler will process the image in background and update
        // the raw contact with the new photo ID when it's finished, setting it to dirty again!
        // See https://code.google.com/p/android/issues/detail?id=226875

        /*Uri photoUri = addressBook.syncAdapterURI(Uri.withAppendedPath(
                ContentUris.withAppendedId(RawContacts.CONTENT_URI, id),
                RawContacts.DisplayPhoto.CONTENT_DIRECTORY));
        Constants.log.debug("Setting local photo " + photoUri);
        try {
            @Cleanup AssetFileDescriptor fd = addressBook.provider.openAssetFile(photoUri, "w");
            @Cleanup OutputStream stream = fd.createOutputStream();
            if (stream != null)
                stream.write(photo);
            else
                Constants.log.warn("Couldn't create local contact photo file");
        } catch (IOException|RemoteException e) {
            Constants.log.warn("Couldn't write local contact photo file", e);
        }*/

        fun processPhoto(): ByteArray? {
            Constants.log.fine("Processing photo")
            var bitmap = BitmapFactory.decodeByteArray(orig, 0, orig.size)
            if (bitmap == null) {
                Constants.log.warning("Image decoding failed")
                return null
            }

            val width = bitmap.width
            val height = bitmap.height
            val max = photoMaxDimensions.toFloat()

            if (width > max || height > max) {
                val scaleWidth = max/width
                val scaleHeight = max/height
                val scale = Math.min(scaleWidth, scaleHeight)
                val newWidth = (width * scale).toInt()
                val newHeight = (height * scale).toInt()

                Constants.log.fine("Resizing image from ${width}x$height to ${newWidth}x$newHeight")
                bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)

                val baos = ByteArrayOutputStream()
                if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 97, baos)) {
                    Constants.log.warning("Couldn't generate contact image in JPEG format")
                    return orig
                }
                return baos.toByteArray()
            }

            return orig
        }

        // We have to write the photo directly into the PHOTO BLOB, which causes
        // a TransactionTooLargeException for photos > 1 MB, so let's scale them down
        processPhoto()?.let { photo ->
            Constants.log.fine("Inserting photo BLOB for raw contact $id")

            val values = ContentValues(3)
            values.put(RawContacts.Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE)
            values.put(Photo.RAW_CONTACT_ID, id)
            values.put(Photo.PHOTO, photo)
            try {
1224
                addressBook.provider!!.insert(dataSyncURI(), values)
Ricki Hirner's avatar
Ricki Hirner committed
1225 1226 1227 1228 1229 1230 1231
            } catch(e: RemoteException) {
                Constants.log.log(Level.WARNING, "Couldn't insert contact photo", e)
            }
        }
    }


Ricki Hirner's avatar
Ricki Hirner committed
1232 1233
    // helpers

Ricki Hirner's avatar
Ricki Hirner committed
1234
    protected open fun queryPhotoMaxDimensions(): Int {
Ricki Hirner's avatar
Ricki Hirner committed
1235
        try {
1236
            addressBook.provider?.query(ContactsContract.DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI,
Ricki Hirner's avatar
Ricki Hirner committed
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
                    arrayOf(ContactsContract.DisplayPhoto.DISPLAY_MAX_DIM), null, null, null)?.use { cursor ->
                cursor.moveToFirst()
                return cursor.getInt(0)
            }
        } catch(e: RemoteException) {
            Constants.log.log(Level.SEVERE, "Couldn't get max photo dimensions, assuming 720x720 px", e)
        }
        return 720
    }

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

Ricki Hirner's avatar
Ricki Hirner committed
1252 1253 1254
    protected fun dataSyncURI() = addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI)

    override fun toString() = ToStringBuilder.reflectionToString(this)!!
Ricki Hirner's avatar
Ricki Hirner committed
1255 1256

}