Esempio n. 1
0
        public void Execute(bool force)
        {
            if (RefreshStatus == WebCallRefreshStatus.WaitingForRefreshCallback)
            {
                if (!force)
                {
                    return;
                }
                RefreshStatus = WebCallRefreshStatus.NotRefreshing;
            }
            if (force)
            {
                this.OnUnqueued(this, new WebCallUnqueuedEventArgs());
            }
            SessionDocument sessionDocument = database.GetSessionDocument(swid);

            if (!force && sessionDocument != null && sessionDocument.ProtocolVersion != 3)
            {
                this.OnUnauthorized(this, new WebCallUnauthorizedEventArgs("UNAUTHORIZED_MIX_SESSION"));
                return;
            }
            numAttempts++;
            bodyBytes       = Encoding.UTF8.GetBytes(body);
            bodyBytes       = WebCallEncryptor.Encrypt(bodyBytes);
            wwwCall         = wwwCallFactory.Create(uri, method, bodyBytes, headers, latencyWwwCallTimeout, maxWwwCallTimeout);
            wwwCall.OnDone += HandleWwwDone;
            wwwCall.Execute();
            logger.Debug(HttpLogBuilder.BuildRequestLog(wwwCall.RequestId, uri, method, headers, body));
        }
Esempio n. 2
0
        public IInternalSession Create(string swid)
        {
            byte[] localStorageKey = keychain.LocalStorageKey;
            IDocumentCollection <AlertDocument>            documentCollection  = GetDocumentCollection <AlertDocument>(swid, "Alerts", databaseDirectoryCreator, localStorageKey, documentCollectionFactory);
            IDocumentCollection <FriendDocument>           documentCollection2 = GetDocumentCollection <FriendDocument>(swid, "Friends", databaseDirectoryCreator, localStorageKey, documentCollectionFactory);
            IDocumentCollection <FriendInvitationDocument> documentCollection3 = GetDocumentCollection <FriendInvitationDocument>(swid, "FriendInvitations", databaseDirectoryCreator, localStorageKey, documentCollectionFactory);
            IDocumentCollection <UserDocument>             documentCollection4 = GetDocumentCollection <UserDocument>(swid, "Users", databaseDirectoryCreator, localStorageKey, documentCollectionFactory);

            databaseCorruptionHandler.Add(documentCollection4);
            string       dirPath      = BuildDocCollectionPath(databaseDirectoryCreator, swid);
            UserDatabase userDatabase = new UserDatabase(documentCollection, documentCollection2, documentCollection3, documentCollection4, localStorageKey, dirPath, epochTime, documentCollectionFactory, databaseCorruptionHandler, coroutineManager);

            database.ClearServerTimeOffsetMillis();
            epochTime.OffsetMilliseconds = database.GetServerTimeOffsetMillis() ?? 0;
            logger.Debug("Initial time offset: " + epochTime.Offset);
            SessionDocument sessionDocument = database.GetSessionDocument(swid);

            keychain.PushNotificationKey = sessionDocument.CurrentSymmetricEncryptionKey;
            IWebCallEncryptor      webCallEncryptor      = webCallEncryptorFactory.Create(sessionDocument.CurrentSymmetricEncryptionKey, sessionDocument.SessionId);
            IGuestControllerClient guestControllerClient = guestControllerClientFactory.Create(swid);
            ISessionRefresher      sessionRefresher      = sessionRefresherFactory.Create(mixSessionStarter, guestControllerClient);
            IMixWebCallFactory     mixWebCallFactory     = mixWebCallFactoryFactory.Create(webCallEncryptor, swid, sessionDocument.GuestControllerAccessToken, sessionRefresher);

            guestControllerClient.OnAccessTokenChanged += delegate(object sender, AbstractGuestControllerAccessTokenChangedEventArgs e)
            {
                mixWebCallFactory.GuestControllerAccessToken = e.GuestControllerAccessToken;
            };
            AssetLoader             assetLoader           = new AssetLoader(logger, wwwCallFactory);
            IList <IInternalFriend> friends               = CreateFriends(userDatabase);
            AgeBandType             ageBandType           = AgeBandTypeConverter.Convert(sessionDocument.AgeBand);
            DateTime               lastRefreshTime        = epochTime.FromSeconds(sessionDocument.LastProfileRefreshTime);
            RegistrationProfile    registrationProfile    = new RegistrationProfile(logger, sessionDocument.DisplayNameText, sessionDocument.ProposedDisplayName, sessionDocument.ProposedDisplayNameStatus, sessionDocument.FirstName, sessionDocument.AccountStatus, lastRefreshTime, sessionDocument.CountryCode);
            GetStateResponseParser getStateResponseParser = new GetStateResponseParser(logger);
            NotificationPoller     notificationPoller     = new NotificationPoller(logger, mixWebCallFactory, notificationQueue, pollCountdownStopwatch, getStateResponseParser, epochTime, random, database, swid);
            DisplayName            displayName            = new DisplayName(sessionDocument.DisplayNameText);
            LocalUser              localUser              = new LocalUser(logger, displayName, swid, friends, ageBandType, database, userDatabase, registrationProfile, mixWebCallFactory, guestControllerClient, notificationQueue, encryptor, epochTime);
            Session session = new Session(logger, localUser, sessionDocument.GuestControllerAccessToken, sessionDocument.PushNotificationToken != null, notificationPoller, coroutineManager, database, userDatabase, guestControllerClient, mixWebCallFactory, epochTime, databaseCorruptionHandler, sessionStatus, keychain, getStateResponseParser, clientVersion, notificationQueue);

            try
            {
                NotificationHandler.Handle(notificationDispatcher, userDatabase, localUser, epochTime);
                notificationQueue.LatestSequenceNumber = sessionDocument.LatestNotificationSequenceNumber;
                IEnumerable <IncomingFriendInvitation> incomingFriendInvitations = GetIncomingFriendInvitations(userDatabase, localUser);
                foreach (IncomingFriendInvitation item in incomingFriendInvitations)
                {
                    localUser.AddIncomingFriendInvitation(item);
                }
                IEnumerable <OutgoingFriendInvitation> outgoingFriendInvitations = GetOutgoingFriendInvitations(userDatabase, localUser);
                foreach (OutgoingFriendInvitation item2 in outgoingFriendInvitations)
                {
                    localUser.AddOutgoingFriendInvitation(item2);
                }
            }
            catch (Exception)
            {
                session.Dispose();
                throw;
            }
            return(session);
        }
Esempio n. 3
0
        public SessionDocument GetSessionDocument(string swid)
        {
            SessionDocument doc = null;

            CreateSessions(delegate(IDocumentCollection <SessionDocument> sessions)
            {
                doc = GetSessionDocument(swid, sessions);
            });
            return(doc);
        }
Esempio n. 4
0
 public static void UpdateProfile(AbstractLogger logger, IGuestControllerClient guestControllerClient, IDatabase database, string swid, IEpochTime epochTime, IInternalRegistrationProfile profile, string firstName, string lastName, string displayName, string email, string parentEmail, DateTime?dateOfBirth, IEnumerable <KeyValuePair <IMarketingItem, bool> > marketingAgreements, IEnumerable <ILegalDocument> acceptedLegalDocuments, Action <IUpdateProfileResult> callback)
 {
     try
     {
         Dictionary <string, string> dictionary = new Dictionary <string, string>();
         if (!string.IsNullOrEmpty(firstName))
         {
             dictionary.Add("firstName", firstName);
         }
         if (!string.IsNullOrEmpty(lastName))
         {
             dictionary.Add("lastName", lastName);
         }
         if (!string.IsNullOrEmpty(email))
         {
             dictionary.Add("email", email);
         }
         if (!string.IsNullOrEmpty(parentEmail))
         {
             dictionary.Add("parentEmail", parentEmail);
         }
         if (dateOfBirth.HasValue)
         {
             string value = dateOfBirth.Value.ToString("yyyy-MM-dd");
             dictionary.Add("dateOfBirth", value);
         }
         List <Disney.Mix.SDK.Internal.GuestControllerDomain.MarketingItem> marketing = marketingAgreements?.Select((KeyValuePair <IMarketingItem, bool> pair) => new Disney.Mix.SDK.Internal.GuestControllerDomain.MarketingItem
         {
             code       = pair.Key.Id,
             subscribed = pair.Value
         }).ToList();
         List <string>   legalAssertions = acceptedLegalDocuments?.Select((ILegalDocument doc) => doc.Id).ToList();
         SessionDocument sessionDocument = database.GetSessionDocument(swid);
         guestControllerClient.UpdateProfile(new UpdateProfileRequest
         {
             etag        = sessionDocument.GuestControllerEtag,
             profile     = dictionary,
             marketing   = marketing,
             displayName = new RegisterDisplayName
             {
                 proposedDisplayName = displayName
             },
             legalAssertions = legalAssertions
         }, delegate(GuestControllerResult <ProfileResponse> r)
         {
             HandleUpdateProfileResult(logger, database, swid, epochTime, r, profile, callback);
         });
     }
     catch (Exception ex)
     {
         logger.Critical("Unhandled exception: " + ex);
         callback(new UpdateProfileResult(success: false, null));
     }
 }
Esempio n. 5
0
 public void StoreSession(string swid, string accessToken, string refreshToken, string displayName, string firstName, string etag, string ageBand, string proposedDisplayName, string proposedDisplayNameStatus, string accountStatus, bool updateLastProfileRefreshTime, string countryCode)
 {
     CreateSessions(delegate(IDocumentCollection <SessionDocument> sessions)
     {
         uint now     = epochTime.Seconds;
         uint[] array = sessions.FindDocumentIdsEqual(SessionDocument.SwidFieldName, swid).ToArray();
         Action <SessionDocument, bool> action = delegate(SessionDocument doc, bool newDoc)
         {
             doc.GuestControllerAccessToken  = accessToken;
             doc.GuestControllerRefreshToken = refreshToken;
             doc.Swid = swid;
             doc.LastSessionUpdateTime = now;
             if (newDoc)
             {
                 doc.LastNotificationTime = long.MinValue;
             }
             doc.DisplayNameText = displayName;
             doc.FirstName       = firstName;
             if (etag != null)
             {
                 doc.GuestControllerEtag = etag;
             }
             doc.AgeBand                          = ageBand;
             doc.LoggedOut                        = false;
             doc.ProposedDisplayName              = proposedDisplayName;
             doc.ProposedDisplayNameStatus        = proposedDisplayNameStatus;
             doc.AccountStatus                    = accountStatus;
             doc.LatestNotificationSequenceNumber = 0L;
             doc.CountryCode                      = countryCode;
             doc.ProtocolVersion                  = 3;
         };
         if (array.Length > 0)
         {
             SessionDocument sessionDocument = sessions.Find(array[0]);
             action(sessionDocument, arg2: false);
             if (updateLastProfileRefreshTime)
             {
                 sessionDocument.LastProfileRefreshTime = epochTime.Seconds;
             }
             sessions.Update(sessionDocument);
         }
         else
         {
             SessionDocument sessionDocument = new SessionDocument
             {
                 LastProfileRefreshTime = epochTime.Seconds
             };
             action(sessionDocument, arg2: true);
             sessions.Insert(sessionDocument);
         }
     });
 }
Esempio n. 6
0
 public void UpdateSessionDocument(string swid, Action <SessionDocument> updateCallback)
 {
     CreateSessions(delegate(IDocumentCollection <SessionDocument> sessions)
     {
         SessionDocument sessionDocument = GetSessionDocument(swid, sessions);
         if (sessionDocument != null)
         {
             updateCallback(sessionDocument);
             sessionDocument.ProtocolVersion = 3;
             sessions.Update(sessionDocument);
         }
     });
 }
Esempio n. 7
0
        public SessionDocument GetLastLoggedInSessionDocument()
        {
            SessionDocument doc = null;

            CreateSessions(delegate(IDocumentCollection <SessionDocument> sessions)
            {
                doc = (from d in sessions
                       where !d.LoggedOut
                       orderby d.LastSessionUpdateTime descending
                       select d).FirstOrDefault();
            });
            return(doc);
        }
Esempio n. 8
0
        public static void Resume(AbstractLogger logger, IGetStateResponseParser getStateResponseParser, IEpochTime epochTime, string clientVersion, INotificationQueue notificationQueue, IMixWebCallFactory mixWebCallFactory, IInternalLocalUser localUser, IDatabase database, IUserDatabase userDatabase, INotificationPoller notificationPoller, Action <IResumeSessionResult> callback)
        {
            epochTime.OffsetMilliseconds = database.GetServerTimeOffsetMillis() ?? 0;
            logger.Debug("Initial time offset: " + epochTime.Offset);
            SessionDocument sessionDocument      = database.GetSessionDocument(localUser.Swid);
            long            lastNotificationTime = sessionDocument.LastNotificationTime;

            StateGetter.GetState(logger, epochTime, clientVersion, database, userDatabase, notificationQueue, mixWebCallFactory, localUser.Swid, lastNotificationTime, delegate(GetStateResponse response)
            {
                HandleGetStateSuccess(logger, getStateResponseParser, response, mixWebCallFactory, localUser, userDatabase, notificationPoller, callback);
            }, delegate
            {
                callback(new ResumeSessionResult(success: false));
            });
        }
Esempio n. 9
0
        public static void DisableVisiblePushNotifications(AbstractLogger logger, IDatabase database, IMixWebCallFactory mixWebCallFactory, string swid, Action <IDisableVisiblePushNotificationsResult> callback)
        {
            SessionDocument sessionDocument = database.GetSessionDocument(swid);

            if (sessionDocument.PushNotificationToken == null)
            {
                callback(new DisableVisiblePushNotificationsResult(success: false));
                return;
            }
            Enable(logger, database, mixWebCallFactory, sessionDocument.PushNotificationToken, sessionDocument.PushNotificationTokenType, sessionDocument.ProvisionId, enableVisible: false, swid, delegate
            {
                callback(new DisableVisiblePushNotificationsResult(success: true));
            }, delegate
            {
                callback(new DisableVisiblePushNotificationsResult(success: false));
            });
        }
Esempio n. 10
0
 public static void DisableAllPushNotifications(AbstractLogger logger, IDatabase database, IMixWebCallFactory mixWebCallFactory, string swid, Action <IDisableAllPushNotificationsResult> callback)
 {
     try
     {
         SessionDocument sessionDocument = database.GetSessionDocument(swid);
         if (sessionDocument.PushNotificationToken == null)
         {
             callback(new DisableAllPushNotificationsResult(success: false));
             return;
         }
         BaseUserRequest request = new BaseUserRequest();
         IWebCall <BaseUserRequest, BaseResponse> webCall = mixWebCallFactory.PushNotificationsSettingDeletePost(request);
         webCall.OnResponse += delegate
         {
             try
             {
                 database.UpdateSessionDocument(swid, delegate(SessionDocument d)
                 {
                     d.PushNotificationToken           = null;
                     d.PushNotificationTokenType       = null;
                     d.VisiblePushNotificationsEnabled = false;
                 });
                 callback(new DisableAllPushNotificationsResult(success: true));
             }
             catch (Exception ex2)
             {
                 logger.Critical("Unhandled exception: " + ex2);
                 callback(new DisableAllPushNotificationsResult(success: false));
             }
         };
         webCall.OnError += delegate
         {
             callback(new DisableAllPushNotificationsResult(success: false));
         };
         webCall.Execute();
     }
     catch (Exception ex)
     {
         logger.Critical("Unhandled exception: " + ex);
         callback(new DisableAllPushNotificationsResult(success: false));
     }
 }
Esempio n. 11
0
 public IInternalOfflineLastSessionResult Create()
 {
     try
     {
         SessionDocument lastLoggedInSessionDocument = database.GetLastLoggedInSessionDocument();
         if (lastLoggedInSessionDocument == null)
         {
             return(new OfflineLastSessionNotFoundResult());
         }
         IInternalSession session = sessionFactory.Create(lastLoggedInSessionDocument.Swid);
         return(new OfflineLastSessionResult(success: true, session));
     }
     catch (CorruptionException ex)
     {
         logger.Fatal("Corruption detected during offline session creation: " + ex);
         return(new OfflineLastSessionCorruptionDetectedResult());
     }
     catch (Exception ex2)
     {
         logger.Critical("Error creating session: " + ex2);
         return(new OfflineLastSessionResult(success: false, null));
     }
 }
Esempio n. 12
0
 public void RestoreLastSession(Action <IRestoreLastSessionResult> callback)
 {
     try
     {
         database.ClearServerTimeOffsetMillis();
         SessionDocument lastSessionDoc = database.GetLastLoggedInSessionDocument();
         if (lastSessionDoc == null)
         {
             callback(new RestoreLastSessionNotFoundResult());
             return;
         }
         IGuestControllerClient guestControllerClient = guestControllerClientFactory.Create(lastSessionDoc.Swid);
         guestControllerClient.Refresh(delegate(GuestControllerResult <RefreshResponse> r)
         {
             if (r.Response == null)
             {
                 logger.Error("Error refreshing auth token");
                 callback(new RestoreLastSessionResult(success: false, null));
             }
             else
             {
                 HandleRefreshSuccess(callback, r, lastSessionDoc);
             }
         });
     }
     catch (CorruptionException ex)
     {
         logger.Fatal("Corruption detected during session restoration: " + ex);
         callback(new RestoreLastSessionCorruptionDetectedResult());
     }
     catch (Exception ex2)
     {
         logger.Critical("Unhandled exception: " + ex2);
         callback(new RestoreLastSessionResult(success: false, null));
     }
 }
Esempio n. 13
0
 private void HandleRefreshSuccess(Action <IRestoreLastSessionResult> callback, GuestControllerResult <RefreshResponse> result, SessionDocument lastSessionDoc)
 {
     try
     {
         GuestApiErrorCollection   error2 = result.Response.error;
         RefreshData               data   = result.Response.data;
         IRestoreLastSessionResult error  = GuestControllerErrorParser.GetRestoreLastSessionResult(error2);
         if (data == null && error != null)
         {
             if (error is IRestoreLastSessionFailedInvalidOrExpiredTokenResult && lastSessionDoc.AccountStatus == "AWAIT_PARENT_CONSENT")
             {
                 callback(new RestoreLastSessionFailedParentalConsentResult());
             }
             else
             {
                 callback(error);
             }
             return;
         }
         if (data == null)
         {
             if (error2 != null)
             {
                 logger.Critical("Received unhandled error exception:\n" + JsonParser.ToJson(error2) + "\nResponse headers:\n" + string.Join("\n", result.ResponseHeaders.Select((KeyValuePair <string, string> h) => h.Key + ": " + h.Value).ToArray()));
             }
             callback(new RestoreLastSessionResult(success: false, null));
             return;
         }
         if (!ValidateRefreshData(data))
         {
             logger.Critical("Error parsing the refresh data: " + JsonParser.ToJson(data));
             callback(new RestoreLastSessionResult(success: false, null));
             return;
         }
         Token token = data.token;
         lastSessionDoc.GuestControllerAccessToken = token.access_token;
         lastSessionDoc.GuestControllerEtag        = data.etag;
         database.UpdateGuestControllerToken(token, data.etag);
         try
         {
             IInternalSession session = sessionFactory.Create(lastSessionDoc.Swid);
             session.Resume(delegate(IResumeSessionResult r)
             {
                 HandleOfflineSessionResumed(r, session, error, callback);
             });
         }
         catch (Exception ex)
         {
             logger.Critical("Error creating session: " + ex);
             callback(new RestoreLastSessionResult(success: false, null));
         }
     }
     catch (CorruptionException ex2)
     {
         logger.Fatal("Corruption detected during session restoration: " + ex2);
         callback(new RestoreLastSessionCorruptionDetectedResult());
     }
     catch (Exception ex)
     {
         logger.Critical("Unhandled exception: " + ex);
         callback(new RestoreLastSessionResult(success: false, null));
     }
 }
        public static IInternalPushNotification Receive(AbstractLogger logger, IEncryptor encryptor, IDatabase database, string swid, IDictionary notification)
        {
            SessionDocument sessionDocument = database.GetSessionDocument(swid);

            byte[]      currentSymmetricEncryptionKey = sessionDocument.CurrentSymmetricEncryptionKey;
            string      optionalString = GetOptionalString(notification, "payload");
            IDictionary dictionary;

            if (optionalString == null)
            {
                dictionary = notification;
            }
            else
            {
                byte[] payloadEncryptedBytes;
                try
                {
                    payloadEncryptedBytes = Convert.FromBase64String(optionalString);
                }
                catch (Exception ex)
                {
                    throw new ArgumentException("Couldn't deserialize push notification: " + ex);
                }
                try
                {
                    dictionary = DecryptPayload(encryptor, currentSymmetricEncryptionKey, payloadEncryptedBytes);
                }
                catch (Exception ex)
                {
                    byte[] previousSymmetricEncryptionKey = sessionDocument.PreviousSymmetricEncryptionKey;
                    if (previousSymmetricEncryptionKey == null)
                    {
                        throw new ArgumentException("Couldn't decrypt push notification: " + ex);
                    }
                    try
                    {
                        dictionary = DecryptPayload(encryptor, previousSymmetricEncryptionKey, payloadEncryptedBytes);
                    }
                    catch (Exception ex2)
                    {
                        throw new ArgumentException(string.Concat("Couldn't decrypt push notification: ", ex, "\n", ex2));
                    }
                }
            }
            StringBuilder stringBuilder = new StringBuilder("Received push notification with payload:\n");

            foreach (DictionaryEntry item in dictionary)
            {
                stringBuilder.Append(item.Key);
                stringBuilder.Append(" = ");
                stringBuilder.Append(item.Value);
                stringBuilder.Append('\n');
            }
            logger.Debug(stringBuilder.ToString());
            string optionalString2 = GetOptionalString(dictionary, "type");

            if (optionalString2 == null)
            {
                throw new ArgumentException("Push notification doesn't have a type");
            }
            string optionalString3        = GetOptionalString(dictionary, "notifications_available");
            bool   notificationsAvailable = optionalString3 == null || optionalString3 == "true";

            switch (optionalString2)
            {
            case "FRIENDSHIP_INVITATION_MESSAGE":
            {
                string optionalString5 = GetOptionalString(dictionary, "friendshipInvitationId");
                return(new FriendshipInvitationReceivedPushNotification(notificationsAvailable, optionalString5));
            }

            case "FRIENDSHIP_MESSAGE":
            {
                string optionalString4 = GetOptionalString(dictionary, "friendId");
                return(new FriendshipAddedPushNotification(notificationsAvailable, optionalString4));
            }

            case "BROADCAST":
                return(new BroadcastPushNotification(notificationsAvailable));

            case "ADD_ALERT":
                return(new AlertAddedPushNotification(notificationsAvailable));

            case "CLEAR_ALERT":
                return(new AlertsClearedPushNotification(notificationsAvailable));

            case "REMOVE_FRIENDSHIP_INVITATION":
                return(new FriendshipInvitationRemovedPushNotification(notificationsAvailable));

            case "REMOVE_FRIENDSHIP_TRUST":
                return(new UntrustedPushNotification(notificationsAvailable));

            default:
                return(new GenericPushNotification(notificationsAvailable));
            }
        }