Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prefix device-specific distinct IDs with '$device:' #810

Merged
merged 2 commits into from
Feb 24, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ We'd also love for you to come and work with us! Check out our **[opening positi
<a name="changelog"></a>
# Changelog

See [wiki page](https://github.com/mixpanel/mixpanel-android/wiki/Changelog).
See [wiki page](CHANGELOG.md).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
See [wiki page](CHANGELOG.md).
See [changelog](CHANGELOG.md).


<a name="license"></a>
# License
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import com.mixpanel.android.util.HttpService;
import com.mixpanel.android.util.RemoteService;

import org.hamcrest.CoreMatchers;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: redundant

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
Expand All @@ -36,11 +37,14 @@

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.hamcrest.CoreMatchers.*;

@RunWith(AndroidJUnit4.class)
@LargeTest
Expand Down Expand Up @@ -79,12 +83,14 @@ public void testGeneratedDistinctId() {
String fakeToken = UUID.randomUUID().toString();
MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(InstrumentationRegistry.getInstrumentation().getContext(), mMockPreferences, fakeToken);
String generatedId1 = mixpanel.getDistinctId();
assertTrue(generatedId1 != null);
assertThat(generatedId1, startsWith("$device:"));
assertEquals(generatedId1, "$device:" + mixpanel.getAnonymousId());

mixpanel.reset();
String generatedId2 = mixpanel.getDistinctId();
assertTrue(generatedId2 != null);
assertTrue(!generatedId1.equals(generatedId2));
assertThat(generatedId2, startsWith("$device:"));
assertEquals(generatedId2, "$device:" + mixpanel.getAnonymousId());
assertNotEquals(generatedId1, generatedId2);
}

@Test
Expand Down Expand Up @@ -512,6 +518,7 @@ protected AnalyticsMessages getAnalyticsMessages() {
assertNull(anonymousUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS));
assertNull(peopleUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS));

String deviceId = mixpanel.getAnonymousId();
mixpanel.identify("Personal Identity");
people.set("the prop identified", "prop value identified");

Expand All @@ -528,6 +535,88 @@ protected AnalyticsMessages getAnalyticsMessages() {
for (int i=0; i < data.length(); i++) {
JSONObject j = data.getJSONObject(i);
assertEquals("Personal Identity", j.getString("$distinct_id"));
assertEquals(deviceId, j.getString("$device_id"));
}
}

@Test
public void testIdentifyAfterSetToAnonymousId() throws InterruptedException, JSONException {
String token = "TEST TOKEN testIdentifyAfterSet";
final List<AnalyticsMessages.MixpanelDescription> messages = new ArrayList<AnalyticsMessages.MixpanelDescription>();
final BlockingQueue<JSONObject> anonymousUpdates = new LinkedBlockingQueue();
final BlockingQueue<JSONObject> peopleUpdates = new LinkedBlockingQueue();

final MPDbAdapter mockAdapter = new MPDbAdapter(InstrumentationRegistry.getInstrumentation().getContext()) {
@Override
public int addJSON(JSONObject j, String token, Table table) {
if (table == Table.ANONYMOUS_PEOPLE) {
anonymousUpdates.add(j);
} else if (table == Table.PEOPLE) {
peopleUpdates.add(j);
}
return super.addJSON(j, token, table);
}
};
final AnalyticsMessages listener = new AnalyticsMessages(InstrumentationRegistry.getInstrumentation().getContext()) {
@Override
public void peopleMessage(PeopleDescription heard) {
messages.add(heard);
super.peopleMessage(heard);
}

@Override
public void pushAnonymousPeopleMessage(PushAnonymousPeopleDescription pushAnonymousPeopleDescription) {
messages.add(pushAnonymousPeopleDescription);
super.pushAnonymousPeopleMessage(pushAnonymousPeopleDescription);
}

@Override
protected MPDbAdapter makeDbAdapter(Context context) {
return mockAdapter;
}
};

MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(InstrumentationRegistry.getInstrumentation().getContext(), mMockPreferences, token) {
@Override
protected AnalyticsMessages getAnalyticsMessages() {
return listener;
}
};

MixpanelAPI.People people = mixpanel.getPeople();
people.increment("the prop", 0L);
people.append("the prop", 1);
people.set("the prop", 2);
people.increment("the prop", 3L);
people.append("the prop", 5);

assertEquals(0L, anonymousUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS).getJSONObject("$add").getLong("the prop"));
assertEquals(1, anonymousUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS).getJSONObject("$append").get("the prop"));
assertEquals(2, anonymousUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS).getJSONObject("$set").get("the prop"));
assertEquals(3L, anonymousUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS).getJSONObject("$add").getLong("the prop"));
assertEquals(5, anonymousUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS).getJSONObject("$append").get("the prop"));
assertNull(anonymousUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS));
assertNull(peopleUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS));

String deviceId = mixpanel.getAnonymousId();
mixpanel.identify(mixpanel.getDistinctId());
people.set("the prop identified", "prop value identified");
assertNull(mixpanel.getUserId());

assertEquals("prop value identified", peopleUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS).getJSONObject("$set").getString("the prop identified"));
assertNull(peopleUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS));
assertNull(anonymousUpdates.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS));

String[] storedAnonymous = mockAdapter.generateDataString(MPDbAdapter.Table.ANONYMOUS_PEOPLE, token);
assertNull(storedAnonymous);

String[] storedPeople = mockAdapter.generateDataString(MPDbAdapter.Table.PEOPLE, token);
assertEquals(6, Integer.valueOf(storedPeople[2]).intValue());
JSONArray data = new JSONArray(storedPeople[1]);
for (int i=0; i < data.length(); i++) {
JSONObject j = data.getJSONObject(i);
assertEquals("$device:" + deviceId, j.getString("$distinct_id"));
assertEquals(deviceId, j.getString("$device_id"));
}
}

Expand All @@ -536,57 +625,58 @@ public void testIdentifyAndGetDistinctId() {
MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(InstrumentationRegistry.getInstrumentation().getContext(), mMockPreferences, "Identify Test Token");

String generatedId = metrics.getDistinctId();
assertNotNull(generatedId);
assertThat(generatedId, startsWith("$device:"));
assertEquals(generatedId, "$device:" + metrics.getAnonymousId());

String emptyId = metrics.getPeople().getDistinctId();
assertNull(emptyId);
assertNull(metrics.getUserId());
assertNull(metrics.getPeople().getDistinctId());

metrics.identify("Events Id");
String setId = metrics.getDistinctId();
assertEquals("Events Id", setId);
assertEquals("Events Id", metrics.getDistinctId());
assertEquals("Events Id", metrics.getUserId());
assertEquals("Events Id", metrics.getPeople().getDistinctId());
}

String userId = metrics.getUserId();
assertEquals("Events Id", userId);
@Test
public void testIdentifyToCurrentAnonymousDistinctId() {
MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(InstrumentationRegistry.getInstrumentation().getContext(), mMockPreferences, "Identify Test Token");

String generatedId = metrics.getDistinctId();
assertThat(generatedId, startsWith("$device:"));
assertEquals(generatedId, "$device:" + metrics.getAnonymousId());

String unchangedId = metrics.getDistinctId();
assertEquals("Events Id", unchangedId);
assertNull(metrics.getUserId());
assertNull(metrics.getPeople().getDistinctId());

String setPeopleId = metrics.getPeople().getDistinctId();
assertEquals("Events Id", setPeopleId);
metrics.identify(metrics.getDistinctId());
assertEquals(generatedId, metrics.getDistinctId());
assertNull(metrics.getUserId());
assertEquals(generatedId, metrics.getPeople().getDistinctId());
}

@Test
public void testIdentifyAndCheckUserIDAndDeviceID() {
MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(InstrumentationRegistry.getInstrumentation().getContext(), mMockPreferences, "Identify Test Token");

String generatedId = metrics.getAnonymousId();
assertNotNull(generatedId);
assertNotNull(metrics.getAnonymousId());
String eventsDistinctId = metrics.getDistinctId();
assertNotNull(eventsDistinctId);
assertEquals(eventsDistinctId, generatedId);
assertEquals("$device:" + generatedId, eventsDistinctId);
assertNull(metrics.getUserId());

String emptyId = metrics.getPeople().getDistinctId();
assertNull(emptyId);
assertNull(metrics.getPeople().getDistinctId());

metrics.identify("Distinct Id");
String setId = metrics.getDistinctId();
assertEquals("Distinct Id", setId);
String anonymousIdAfterIdentify = metrics.getAnonymousId();
assertEquals(anonymousIdAfterIdentify, generatedId);

String unchangedId = metrics.getDistinctId();
assertEquals("Distinct Id", unchangedId);

String setPeopleId = metrics.getPeople().getDistinctId();
assertEquals("Distinct Id", setPeopleId);
assertEquals("Distinct Id", metrics.getDistinctId());
assertEquals(generatedId, metrics.getAnonymousId());
assertEquals("Distinct Id", metrics.getPeople().getDistinctId());

// once its reset we will only have generated id but user id should be null
metrics.reset();
String generatedId2 = metrics.getAnonymousId();
assertNotNull(generatedId2);
assertNotSame(generatedId, generatedId2);
assertNotNull(metrics.getDistinctId());
assertEquals("$device:" + generatedId2, metrics.getDistinctId());
assertNull(metrics.getUserId());
}

@Test
Expand Down Expand Up @@ -1121,10 +1211,13 @@ protected AnalyticsMessages getAnalyticsMessages() {
oldDistinctIds.add(metrics.getDistinctId());
metrics.identify(newDistinctId + "0");
metrics.reset();

assertThat(oldDistinctIds, not(hasItem(metrics.getDistinctId())));
oldDistinctIds.add(metrics.getDistinctId());
metrics.identify(newDistinctId + "1");
metrics.reset();

assertThat(oldDistinctIds, not(hasItem(metrics.getDistinctId())));
oldDistinctIds.add(metrics.getDistinctId());
metrics.identify(newDistinctId + "2");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public void testUnsetEventsId() {
final SharedPreferences testPreferences = InstrumentationRegistry.getInstrumentation().getContext().getSharedPreferences(TEST_PREFERENCES, Context.MODE_PRIVATE);
testPreferences.edit().clear().commit();
final String eventsId = mPersistentIdentity.getEventsDistinctId();
assertTrue(Pattern.matches("^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$", eventsId));
assertTrue(Pattern.matches("^\\$device:[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$", eventsId));

final String autoId = testPreferences.getString("events_distinct_id", "NOPE");
assertEquals(autoId, eventsId);
Expand Down
22 changes: 10 additions & 12 deletions src/main/java/com/mixpanel/android/mpmetrics/MixpanelAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,7 @@ public void alias(String alias, String distinct_id) {
* value is globally unique for each individual user you intend to track.
*/
public void identify(String distinctId) {
identify(distinctId, true, true);
identify(distinctId, true);
}

/**
Expand All @@ -652,24 +652,22 @@ public void identify(String distinctId) {
*
*/
public void identify(String distinctId, boolean usePeople) {
identify(distinctId, true, usePeople);
}

private void identify(String distinctId, boolean markAsUserId, boolean usePeople) {
if (hasOptedOutTracking()) return;
if (distinctId == null) {
MPLog.e(LOGTAG, "Can't identify with null distinct_id.");
return;
}
synchronized (mPersistentIdentity) {
String currentEventsDistinctId = mPersistentIdentity.getEventsDistinctId();
mPersistentIdentity.setAnonymousIdIfAbsent(currentEventsDistinctId);
mPersistentIdentity.setEventsDistinctId(distinctId);
if(markAsUserId) {
mPersistentIdentity.markEventsUserIdPresent();
}

if (!distinctId.equals(currentEventsDistinctId)) {
if (distinctId.startsWith("$device:")) {
MPLog.e(LOGTAG, "Can't identify with '$device:' distinct_id.");
return;
}

mPersistentIdentity.setEventsDistinctId(distinctId);
mPersistentIdentity.setAnonymousIdIfAbsent(currentEventsDistinctId);
mPersistentIdentity.markEventsUserIdPresent();
try {
JSONObject identifyPayload = new JSONObject();
identifyPayload.put("$anon_distinct_id", currentEventsDistinctId);
Expand Down Expand Up @@ -1779,7 +1777,7 @@ public void identify(String distinctId) {
MPLog.e(LOGTAG, "Can't identify with null distinct_id.");
return;
}
if (distinctId != mPersistentIdentity.getEventsDistinctId()) {
if (!distinctId.equals(mPersistentIdentity.getEventsDistinctId())) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good catch!

MPLog.w(LOGTAG, "Identifying with a distinct_id different from the one being set by MixpanelAPI.identify() is not supported.");
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ private void readIdentities() {

if (mEventsDistinctId == null) {
mAnonymousId = UUID.randomUUID().toString();
mEventsDistinctId = mAnonymousId;
mEventsDistinctId = "$device:" + mAnonymousId;
mEventsUserIdPresent = false;
writeIdentities();
}
Expand Down