99import android .os .Build ;
1010import android .preference .PreferenceManager ;
1111
12+ import com .automattic .android .tracks .TracksClient ;
1213import com .mixpanel .android .mpmetrics .MixpanelAPI ;
1314
1415import org .json .JSONException ;
@@ -83,6 +84,13 @@ private void trackMixpanelDataForInstructions(AnalyticsTrackerMixpanelInstructio
8384 return ;
8485 }
8586
87+ // Just a security check we're tracking the correct user
88+ if (getWordPressComUserName () == null && getAnonID () == null ) {
89+ this .clearAllData ();
90+ generateNewAnonID ();
91+ mMixpanel .identify (getAnonID ());
92+ }
93+
8694 trackMixpanelEventForInstructions (instructions , properties );
8795 trackMixpanelPropertiesForInstructions (instructions );
8896 }
@@ -185,17 +193,41 @@ public void refreshMetadata(boolean isUserConnected, boolean isWordPressComUser,
185193 AppLog .e (AppLog .T .UTILS , e );
186194 }
187195
196+
197+ if (isUserConnected && isWordPressComUser ) {
198+ setWordPressComUserName (username );
199+ // Re-unify the user
200+ if (getAnonID () != null ) {
201+ mMixpanel .alias (getWordPressComUserName (), getAnonID ());
202+ clearAnonID ();
203+ } else {
204+ mMixpanel .identify (username );
205+ }
206+ } else {
207+ // Not wpcom connected. Check if anonID is already present
208+ setWordPressComUserName (null );
209+ if (getAnonID () == null ) {
210+ generateNewAnonID ();
211+ }
212+ mMixpanel .identify (getAnonID ());
213+ }
214+
188215 // Application opened and start.
189216 if (isUserConnected ) {
190- mMixpanel .identify (username );
191217 try {
192- mMixpanel .getPeople ().identify (username );
218+ String userID = getWordPressComUserName () != null ? getWordPressComUserName () : getAnonID ();
219+ if (userID == null ) {
220+ // This should not be an option here
221+ return ;
222+ }
223+
224+ mMixpanel .getPeople ().identify (userID );
193225 JSONObject jsonObj = new JSONObject ();
194- jsonObj .put ("$username" , username );
226+ jsonObj .put ("$username" , userID );
195227 if (email != null ) {
196228 jsonObj .put ("$email" , email );
197229 }
198- jsonObj .put ("$first_name" , username );
230+ jsonObj .put ("$first_name" , userID );
199231 mMixpanel .getPeople ().set (jsonObj );
200232 } catch (JSONException e ) {
201233 AppLog .e (AppLog .T .UTILS , e );
@@ -207,6 +239,7 @@ public void refreshMetadata(boolean isUserConnected, boolean isWordPressComUser,
207239
208240 @ Override
209241 public void clearAllData () {
242+ super .clearAllData ();
210243 mMixpanel .clearSuperProperties ();
211244 try {
212245 mMixpanel .getPeople ().clearPushRegistrationId ();
0 commit comments