1package eu.siacs.conversations.services;
2
3import java.util.concurrent.atomic.AtomicInteger;
4import java.util.Collection;
5import java.util.Collections;
6import java.util.HashMap;
7import java.util.Set;
8import java.util.Objects;
9import java.util.ArrayList;
10import java.util.List;
11import java.util.Map;
12import java.util.stream.Collectors;
13import java.util.stream.Stream;
14
15import com.google.common.collect.ImmutableMap;
16import com.google.common.collect.ImmutableList;
17
18import android.content.Intent;
19import android.os.SystemClock;
20import android.net.Uri;
21import android.util.Log;
22
23import eu.siacs.conversations.Config;
24import eu.siacs.conversations.android.PhoneNumberContact;
25import eu.siacs.conversations.entities.Account;
26import eu.siacs.conversations.entities.Contact;
27import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
28import eu.siacs.conversations.xmpp.Jid;
29
30public class QuickConversationsService extends AbstractQuickConversationsService {
31
32 protected final AtomicInteger mRunningSyncJobs = new AtomicInteger(0);
33 protected final SerialSingleThreadExecutor mSerialSingleThreadExecutor = new SerialSingleThreadExecutor(QuickConversationsService.class.getSimpleName());
34 protected HashMap<String,Attempt> mLastSyncAttempt = new HashMap<>();
35
36 QuickConversationsService(XmppConnectionService xmppConnectionService) {
37 super(xmppConnectionService);
38 }
39
40 @Override
41 public void considerSync() {
42 considerSync(false);
43 }
44
45 @Override
46 public void signalAccountStateChange() {
47
48 }
49
50 @Override
51 public boolean isSynchronizing() {
52 return mRunningSyncJobs.get() > 0;
53 }
54
55 @Override
56 public void considerSyncBackground(boolean force) {
57 mRunningSyncJobs.incrementAndGet();
58 mSerialSingleThreadExecutor.execute(() -> {
59 considerSync(force);
60 if (mRunningSyncJobs.decrementAndGet() == 0) {
61 service.updateRosterUi(XmppConnectionService.UpdateRosterReason.INIT);
62 }
63 });
64 }
65
66 @Override
67 public void handleSmsReceived(Intent intent) {
68 Log.d(Config.LOGTAG,"ignoring received SMS");
69 }
70
71 protected static String getNumber(final Set<String> gateways, final Contact contact) {
72 final Jid jid = contact.getJid();
73 if (jid.getLocal() != null && ("quicksy.im".equals(jid.getDomain()) || gateways.contains(jid.getDomain()))) {
74 return jid.getLocal();
75 }
76 return null;
77 }
78
79 protected void refresh(Account account, final Set<String> gateways, Collection<PhoneNumberContact> phoneNumberContacts) {
80 for (Contact contact : account.getRoster().getWithSystemAccounts(PhoneNumberContact.class)) {
81 final Uri uri = contact.getSystemAccount();
82 if (uri == null) {
83 continue;
84 }
85 final String number = getNumber(gateways, contact);
86 final PhoneNumberContact phoneNumberContact = PhoneNumberContact.findByUriOrNumber(phoneNumberContacts, uri, number);
87 final boolean needsCacheClean;
88 if (phoneNumberContact != null) {
89 if (!uri.equals(phoneNumberContact.getLookupUri())) {
90 Log.d(Config.LOGTAG, "lookupUri has changed from " + uri + " to " + phoneNumberContact.getLookupUri());
91 }
92 needsCacheClean = contact.setPhoneContact(phoneNumberContact);
93 } else {
94 needsCacheClean = contact.unsetPhoneContact(PhoneNumberContact.class);
95 Log.d(Config.LOGTAG, uri.toString() + " vanished from address book");
96 }
97 if (needsCacheClean) {
98 service.getAvatarService().clear(contact);
99 }
100 }
101 }
102
103 protected void considerSync(boolean forced) {
104 ImmutableMap<String, PhoneNumberContact> allContacts = null;
105 for (final Account account : ImmutableList.copyOf(service.getAccounts())) {
106 final var gateways = gateways(account);
107 if (allContacts == null) allContacts = PhoneNumberContact.load(service);
108 refresh(account, gateways, allContacts.values());
109 if (!considerSync(account, gateways, allContacts, forced)) {
110 service.syncRoster(account);
111 }
112 }
113 }
114
115 protected Set<String> gateways(final Account account) {
116 return Stream.concat(
117 account.getGateways("pstn").stream(),
118 account.getGateways("sms").stream()
119 ).map(a -> a.getJid().asBareJid().toString()).collect(Collectors.toSet());
120 }
121
122 protected boolean considerSync(final Account account, final Set<String> gateways, final Map<String, PhoneNumberContact> contacts, final boolean forced) {
123 final int hash = Objects.hash(contacts.keySet(), gateways);
124 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": consider sync of " + hash);
125 if (!mLastSyncAttempt.getOrDefault(account.getUuid(), Attempt.NULL).retry(hash) && !forced) {
126 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not attempt sync");
127 return false;
128 }
129 mRunningSyncJobs.incrementAndGet();
130
131 mLastSyncAttempt.put(account.getUuid(), Attempt.create(hash));
132 final List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(PhoneNumberContact.class);
133 for (Map.Entry<String, PhoneNumberContact> item : contacts.entrySet()) {
134 PhoneNumberContact phoneContact = item.getValue();
135 for(String gateway : gateways) {
136 final Jid jid = Jid.ofLocalAndDomain(phoneContact.getPhoneNumber(), gateway);
137 final Contact contact = account.getRoster().getContact(jid);
138 boolean needsCacheClean = contact.setPhoneContact(phoneContact);
139 needsCacheClean |= contact.setSystemTags(phoneContact.getTags());
140 if (needsCacheClean) {
141 service.getAvatarService().clear(contact);
142 }
143 withSystemAccounts.remove(contact);
144 }
145 }
146 for (final Contact contact : withSystemAccounts) {
147 final boolean needsCacheClean = contact.unsetPhoneContact(PhoneNumberContact.class);
148 if (needsCacheClean) {
149 service.getAvatarService().clear(contact);
150 }
151 }
152
153 mRunningSyncJobs.decrementAndGet();
154 service.syncRoster(account);
155 service.updateRosterUi(XmppConnectionService.UpdateRosterReason.INIT);
156 return true;
157 }
158
159 protected static class Attempt {
160 private final long timestamp;
161 private final int hash;
162
163 private static final Attempt NULL = new Attempt(0, 0);
164
165 private Attempt(long timestamp, int hash) {
166 this.timestamp = timestamp;
167 this.hash = hash;
168 }
169
170 public static Attempt create(int hash) {
171 return new Attempt(SystemClock.elapsedRealtime(), hash);
172 }
173
174 public boolean retry(int hash) {
175 return hash != this.hash || SystemClock.elapsedRealtime() - timestamp >= Config.CONTACT_SYNC_RETRY_INTERVAL;
176 }
177 }
178}