summaryrefslogtreecommitdiff
path: root/app/src/main/java/sh/lajo/buddy/ContactsObserver.kt
blob: 50b7a48676c7e3402c6b3b71997fc660154b0165 (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
package sh.lajo.buddy

import android.Manifest
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.database.ContentObserver
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.ContactsContract
import android.util.Log
import androidx.core.content.ContextCompat

class ContactsObserver(
    private val context: Context,
    private val contentResolver: ContentResolver
) : ContentObserver(Handler(Looper.getMainLooper())) {

    companion object {
        private const val TAG = "ContactsObserver"
    }

    private var lastContactCount = -1

    init {
        // Initialize the contact count
        lastContactCount = getContactCount()
    }

    override fun onChange(selfChange: Boolean) {
        onChange(selfChange, null)
    }

    override fun onChange(selfChange: Boolean, uri: Uri?) {

        // Check if we have READ_CONTACTS permission
        if (ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.READ_CONTACTS
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            Log.w(TAG, "No READ_CONTACTS permission, skipping contact change")
            return
        }

        Log.d(TAG, "Contact change detected, URI: $uri")

        // Get current contact count
        val currentCount = getContactCount()

        // If count increased, a contact was likely added
        if (lastContactCount >= 0 && currentCount > lastContactCount) {
            Log.d(TAG, "Contact added detected (count: $lastContactCount -> $currentCount)")
            // Find and send the new contact(s)
            findAndSendNewContacts()
        }

        lastContactCount = currentCount
    }

    private fun getContactCount(): Int {
        try {
            val cursor = contentResolver.query(
                ContactsContract.Contacts.CONTENT_URI,
                arrayOf(ContactsContract.Contacts._ID),
                null,
                null,
                null
            )
            cursor?.use {
                return it.count
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error getting contact count", e)
        }
        return 0
    }

    private fun findAndSendNewContacts() {
        try {
            // Query the most recently added contacts
            val cursor = contentResolver.query(
                ContactsContract.Contacts.CONTENT_URI,
                arrayOf(
                    ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.DISPLAY_NAME
                ),
                null,
                null,
                "${ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP} DESC"
            )

            cursor?.use {
                if (it.moveToFirst()) {
                    // Get the most recent contact
                    val contactId = it.getString(it.getColumnIndexOrThrow(ContactsContract.Contacts._ID))
                    val name = it.getString(it.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME))

                    val phoneNumbers = getPhoneNumbers(contactId)
                    val emails = getEmails(contactId)

                    // Send the contact info via WebSocket
                    sendContactAddedEvent(name, phoneNumbers, emails)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error finding new contacts", e)
        }
    }

    private fun getPhoneNumbers(contactId: String): List<String> {
        val phoneNumbers = mutableListOf<String>()
        try {
            val cursor = contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                arrayOf(ContactsContract.CommonDataKinds.Phone.NUMBER),
                "${ContactsContract.CommonDataKinds.Phone.CONTACT_ID} = ?",
                arrayOf(contactId),
                null
            )

            cursor?.use {
                while (it.moveToNext()) {
                    val number = it.getString(it.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER))
                    phoneNumbers.add(number)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error getting phone numbers", e)
        }
        return phoneNumbers
    }

    private fun getEmails(contactId: String): List<String> {
        val emails = mutableListOf<String>()
        try {
            val cursor = contentResolver.query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                arrayOf(ContactsContract.CommonDataKinds.Email.ADDRESS),
                "${ContactsContract.CommonDataKinds.Email.CONTACT_ID} = ?",
                arrayOf(contactId),
                null
            )

            cursor?.use {
                while (it.moveToNext()) {
                    val email = it.getString(it.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Email.ADDRESS))
                    emails.add(email)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error getting emails", e)
        }
        return emails
    }

    private fun sendContactAddedEvent(name: String, phoneNumbers: List<String>, emails: List<String>) {
        Log.d(TAG, "Sending contact added event: $name, phones: $phoneNumbers, emails: $emails")

        val intent = Intent(context, WebSocketService::class.java).apply {
            action = WebSocketService.ACTION_SEND_CONTACT
            putExtra(WebSocketService.EXTRA_CONTACT_NAME, name)
            putExtra(WebSocketService.EXTRA_CONTACT_PHONES, phoneNumbers.toTypedArray())
            putExtra(WebSocketService.EXTRA_CONTACT_EMAILS, emails.toTypedArray())
        }

        context.startForegroundService(intent)
    }

    fun register() {
        contentResolver.registerContentObserver(
            ContactsContract.Contacts.CONTENT_URI,
            true,
            this
        )
        Log.d(TAG, "ContactsObserver registered")
    }

    fun unregister() {
        contentResolver.unregisterContentObserver(this)
        Log.d(TAG, "ContactsObserver unregistered")
    }
}