public void DidChange(TextDocumentIdentifier textDocument, ICollection <TextDocumentContentChangeEvent> contentChanges) { Program.logWriter.WriteLine("Documento changed"); if (Session.Documents[textDocument.Uri] == null) { Program.logWriter.WriteLine("Unknown doc"); var item = new TextDocumentItem(); item.Uri = textDocument.Uri; var doc = new SessionDocument(item); var session = Session; doc.DocumentChanged += async(sender, args) => { Program.logWriter.WriteLine("Document changed"); // Lint the document when it's changed. var doc1 = ((SessionDocument)sender).Document; var diag1 = session.DiagnosticProvider.LintDocument(doc1, session.Settings.MaxNumberOfProblems); if (session.Documents.ContainsKey(doc1.Uri)) { // In case the document has been closed when we were linting… await session.Client.Document.PublishDiagnostics(doc1.Uri, diag1); } }; Session.Documents.TryAdd(textDocument.Uri, doc); } Program.logWriter.WriteLine("A"); Session.Documents[textDocument.Uri].NotifyChanges(contentChanges); Program.logWriter.WriteLine("B"); }
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); }
private void HighlightSingle(string xpath) { try { var hnode = SessionDocument.Current.SelectSingleNode(xpath); var node = SessionDocument.Descendants().Where(x => x.Current == hnode) .FirstOrDefault() as HtmlNodeHierarchy; if (node != null) { node.Highlight = Brushes.Red; } hnode = DomDocument.Current.SelectSingleNode(xpath); node = DomDocument.Descendants().Where(x => x.Current == hnode) .FirstOrDefault() as HtmlNodeHierarchy; if (node != null) { node.Highlight = Brushes.Red; } } catch (Exception ex) { MessageBox.Show(ex.Message, ex.GetType().ToString()); } NotifyPropertyChanged("SessionDocument"); NotifyPropertyChanged("DomDocument"); }
public async Task DidOpen(TextDocumentItem textDocument) { try { var doc = new SessionDocument(textDocument); var session = Session; doc.DocumentChanged += async(sender, args) => { Program.logWriter.WriteLine("Document changed"); // Lint the document when it's changed. var doc1 = ((SessionDocument)sender).Document; var diag1 = session.DiagnosticProvider.LintDocument(doc1, session.Settings.MaxNumberOfProblems); var colors = session.ColorProvider.ColorDocument(doc1); if (session.Documents.ContainsKey(doc1.Uri)) { // In case the document has been closed when we were linting… await session.Client.Document.PublishDiagnostics(doc1.Uri, diag1); await session.Client.Document.ColorProvider(doc1.Uri, colors); } }; if (Session == null) { Program.logWriter.WriteLine("Session is null"); } if (Session.Documents == null) { Program.logWriter.WriteLine("Session.Documents is null"); } Session.Documents.TryAdd(textDocument.Uri, doc); if (Session.DiagnosticProvider == null) { Program.logWriter.WriteLine("Session.DiagnosticProvider is null"); } if (Session.Settings == null) { Program.logWriter.WriteLine("Session.Settings is null"); } if (doc.Document == null) { Program.logWriter.WriteLine("doc.Document is null"); } var diag = Session.DiagnosticProvider.LintDocument(doc.Document, Session.Settings.MaxNumberOfProblems); await Client.Document.PublishDiagnostics(textDocument.Uri, diag); var color = Session.ColorProvider.ColorDocument(doc.Document); await Client.Document.ColorProvider(textDocument.Uri, color); } catch (Exception exc) { Program.logWriter.WriteLine(exc.Message + "\r\n" + exc.StackTrace); } }
public void TestSessionDocumentMapObjToDto() { var sessionDocument = new SessionDocument("path", DocumentType.Designer); var sessionDocumentDto = new SessionDocumentDto(); DtoMapper.MapObjToDto(sessionDocument, sessionDocumentDto); Assert.AreEqual(sessionDocument.Path, sessionDocumentDto.Path); Assert.AreEqual(sessionDocument.Type, sessionDocumentDto.Type); }
public SessionDocument GetSessionDocument(string swid) { SessionDocument doc = null; CreateSessions(delegate(IDocumentCollection <SessionDocument> sessions) { doc = GetSessionDocument(swid, sessions); }); return(doc); }
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 arg) { logger.Critical("Unhandled exception: " + arg); callback(new UpdateProfileResult(success: false, null)); } }
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); } }); }
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); }
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); } }); }
/// <summary> /// Manager performs login, attempting to gain a new session. /// </summary> /// <param name="loginInfo">Login information</param> /// <param name="ipAddress">IP Address of request</param> public async Task <ManagerLoginResponse> Login(ManagerLoginRequest loginInfo, string ipAddress) { // Pull manager information from database. var manager = await _database.GetManagerByUsername(loginInfo.Username); // Default to a failed login attempt. bool canLogIn = false; if (manager.IsPasswordReset && loginInfo.Password == manager.Password) { // If the manager should reset their password and they have provided the correct cleartext password, // allow them to login -- assuming that the next phase will require them to reset their password. canLogIn = true; } else if (_password.IsPasswordMatch(loginInfo.Password, manager.Salt, manager.Password)) { // If the manager password + salt combination matches the stored password allow them to login canLogIn = true; } // If the login failed, throw an exception. if (!canLogIn) { throw new BadLoginException(); } // Create a new session. var newSession = new SessionDocument { Id = ObjectId.GenerateNewId().ToString(), // Generate a new sessionID. SessionId = await _session.GenerateSessionId(), ManagerId = manager.Id, IPAddress = ipAddress, CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), // If the manager needs to reset their password, limit the access to "RESET" status. AccessLevel = manager.IsPasswordReset ? "RESET" : "FULL", IsActive = true }; // Save new session. Note: _session.GenerateSessionId() handles retrying sessionID collisions. await _database.SaveSession(newSession); // Return manager login response information. return(new ManagerLoginResponse { SessionId = newSession.SessionId, AccessLevel = newSession.AccessLevel }); }
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)); }); }
public void TestSessionMapObjToDto() { var session = new Session("session"); var sessionDocument = new SessionDocument("path", DocumentType.Designer); session.AddDocument(sessionDocument); var sessionDto = new SessionDto(); DtoMapper.MapObjToDto(session, sessionDto); Assert.AreEqual(session.Name, sessionDto.Name); Assert.AreEqual(session.GetDocuments().Count(), sessionDto.DocumentsCount); Assert.AreEqual(sessionDocument.Path, sessionDto.Documents[0].Path); Assert.AreEqual(sessionDocument.Type, sessionDto.Documents[0].Type); }
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)); } else { 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 arg2) { logger.Critical("Unhandled exception: " + arg2); callback(new DisableAllPushNotificationsResult(success: false)); } }; webCall.OnError += delegate { callback(new DisableAllPushNotificationsResult(success: false)); }; webCall.Execute(); } } catch (Exception arg) { logger.Critical("Unhandled exception: " + arg); callback(new DisableAllPushNotificationsResult(success: false)); } }
private QueueItem CreateQueueItem <TResponse>(string path, HttpMethod httpMethod, AbstractGuestControllerWebCallRequest request, GuestControllerAuthenticationType authType, Action <GuestControllerResult <TResponse> > callback) where TResponse : GuestControllerWebCallResponse { string text; byte[] requestBody; if (request == null) { text = null; requestBody = null; } else { text = JsonParser.ToJson(request); requestBody = stringEncoding.GetBytes(text); } if (path.Contains("{client-id}")) { path = path.Replace("{client-id}", clientId); } if (path.Contains("{swid}")) { path = path.Replace("{swid}", swid); } if (path.Contains("{refresh-token}")) { SessionDocument sessionDocument = database.GetSessionDocument(swid); string guestControllerRefreshToken = sessionDocument.GuestControllerRefreshToken; path = path.Replace("{refresh-token}", guestControllerRefreshToken); } Uri uri = new Uri(host + "/jgc/v5" + path); QueueItem queueItem = new QueueItem(); queueItem.Uri = uri; queueItem.HttpMethod = httpMethod; queueItem.RequestBodyJson = text; queueItem.RequestBody = requestBody; queueItem.AuthType = authType; queueItem.ResponseParser = ((string b) => JsonParser.FromJson <TResponse>(b)); queueItem.Callback = delegate(GuestControllerResult <GuestControllerWebCallResponse> r) { callback(new GuestControllerResult <TResponse>(r.Success, (TResponse)r.Response, r.ResponseHeaders)); }; return(queueItem); }
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)); } else { 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)); }); } }
public async Task DidOpen(TextDocumentItem textDocument) { var doc = new SessionDocument(textDocument); var session = Session; doc.DocumentChanged += async(sender, args) => { // Lint the document when it's changed. var doc1 = ((SessionDocument)sender).Document; var diag1 = session.DiagnosticProvider.LintDocument(doc1, session.Settings.MaxNumberOfProblems); if (session.Documents.ContainsKey(doc1.Uri)) { // In case the document has been closed when we were linting… await session.Client.Document.PublishDiagnostics(doc1.Uri, diag1); } }; Session.Documents.TryAdd(textDocument.Uri, doc); var diag = Session.DiagnosticProvider.LintDocument(doc.Document, Session.Settings.MaxNumberOfProblems); await Client.Document.PublishDiagnostics(textDocument.Uri, diag); }
public async Task <IActionResult> Create(CreateSessionDocumentDTO model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var sessionFolderExists = await _sessionContext.SessionFolders.AnyAsync(sf => sf.Id == model.SessionFolderId); if (!sessionFolderExists) { return(BadRequest("SessionFolder does not exist")); } var ozItemExists = await _formService.Exists(model.OzItemId); if (!ozItemExists) { return(BadRequest("OzItem does not exist")); } var sessionDocument = new SessionDocument() { FOzItem = model.OzItemId, FSessionFolder = model.SessionFolderId, OzItemContent = model.OzItemContent }; try { await _sessionContext.SessionDocuments.AddAsync(sessionDocument); await _sessionContext.SaveChangesAsync(); return(Ok()); } catch (Exception) { return(StatusCode((int)HttpStatusCode.InternalServerError)); } }
public void RestoreLastSession(Action <IRestoreLastSessionResult> callback) { try { database.ClearServerTimeOffsetMillis(); SessionDocument lastSessionDoc = database.GetLastLoggedInSessionDocument(); if (lastSessionDoc == null) { callback(new RestoreLastSessionNotFoundResult()); } else { 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 arg) { logger.Fatal("Corruption detected during session restoration: " + arg); callback(new RestoreLastSessionCorruptionDetectedResult()); } catch (Exception arg2) { logger.Critical("Unhandled exception: " + arg2); callback(new RestoreLastSessionResult(success: false, null)); } }
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 arg) { logger.Fatal("Corruption detected during offline session creation: " + arg); return(new OfflineLastSessionCorruptionDetectedResult()); } catch (Exception arg2) { logger.Critical("Error creating session: " + arg2); return(new OfflineLastSessionResult(success: false, null)); } }
private void Highlight(string xpath) { try { bool nodefound = false; var sessNodes = SessionDocument.Current.SelectNodes(xpath); if (sessNodes != null) { foreach (HtmlNodeHierarchy node in SessionDocument.Descendants()) { node.Highlight = sessNodes.Contains(node.Current) ? Brushes.Yellow : Brushes.Transparent; } nodefound = true; } var domNodes = DomDocument.Current.SelectNodes(xpath); if (domNodes != null) { foreach (HtmlNodeHierarchy node in DomDocument.Descendants()) { node.Highlight = domNodes.Contains(node.Current) ? Brushes.Yellow : Brushes.Transparent; } nodefound = true; } if (!nodefound) { MessageBox.Show("null nodes"); } } catch (Exception ex) { MessageBox.Show(ex.Message, ex.GetType().ToString()); } NotifyPropertyChanged("SessionDocument"); NotifyPropertyChanged("DomDocument"); }
private void ExecuteNextCall() { if (isExecuting || queue.Count == 0) { return; } QueueItem item = queue[0]; Dictionary <string, string> dictionary = new Dictionary <string, string>(); dictionary.Add("Content-Type", "application/json"); dictionary.Add("Accept", "application/json"); dictionary.Add("Cache-Control", "no-cache,no-store,must-revalidate"); Dictionary <string, string> dictionary2 = dictionary; if (spoofedIpAddress != null) { dictionary2["X-Forwarded-For"] = spoofedIpAddress; } switch (item.AuthType) { case GuestControllerAuthenticationType.ApiKey: { string guestControllerApiKey = database.GetGuestControllerApiKey(); if (guestControllerApiKey == null) { GetApiKeyImmediately(delegate(GuestControllerResult <GuestControllerWebCallResponse> r) { if (!r.Success) { logger.Critical("Getting API key failed"); queue.Remove(item); CallCallbackWithFailureResult(item, null, null); } ExecuteNextCall(); }); return; } dictionary2["Authorization"] = "APIKEY " + guestControllerApiKey; break; } case GuestControllerAuthenticationType.AccessToken: { SessionDocument sessionDocument = database.GetSessionDocument(swid); if (sessionDocument == null) { logger.Critical("Guest Controller web call requires access token, but no session document found"); queue.Remove(item); CallCallbackWithFailureResult(item, null, null); ExecuteNextCall(); return; } string guestControllerAccessToken = sessionDocument.GuestControllerAccessToken; if (guestControllerAccessToken == null) { logger.Critical("Guest Controller web call requires access token, session document doesn't have one"); queue.Remove(item); CallCallbackWithFailureResult(item, null, null); ExecuteNextCall(); return; } dictionary2["Authorization"] = "BEARER " + guestControllerAccessToken; break; } } item.NumAttempts++; isExecuting = true; IWwwCall wwwCall = wwwCallFactory.Create(item.Uri, item.HttpMethod, item.RequestBody, dictionary2, 60000L, 70000L); logger.Debug(HttpLogBuilder.BuildRequestLog(wwwCall.RequestId, item.Uri, item.HttpMethod, dictionary2, item.RequestBodyJson)); wwwCalls.Add(wwwCall); wwwCall.OnDone += delegate { isExecuting = false; Dictionary <string, string> responseHeaders = new Dictionary <string, string>(wwwCall.ResponseHeaders); string error = wwwCall.Error; int requestId = wwwCall.RequestId; long timeToStartUpload = wwwCall.TimeToStartUpload; long timeToFinishUpload = wwwCall.TimeToFinishUpload; float percentUploaded = wwwCall.PercentUploaded; long timeToStartDownload = wwwCall.TimeToStartDownload; long timeToFinishDownload = wwwCall.TimeToFinishDownload; float percentDownloaded = wwwCall.PercentDownloaded; string timeoutReason = wwwCall.TimeoutReason; long timeoutTime = wwwCall.TimeoutTime; uint statusCode = wwwCall.StatusCode; string responseText = (wwwCall.ResponseBody == null) ? string.Empty : stringEncoding.GetString(wwwCall.ResponseBody); GuestControllerWebCallResponse response = item.ResponseParser(responseText); if (response == null) { CallCallbackWithFailureResult(item, null, responseHeaders); } else { wwwCalls.Remove(wwwCall); wwwCall.Dispose(); if (!string.IsNullOrEmpty(error)) { string text = error.ToLower(); if (text == "couldn't connect to host" || text.Contains("timedout") || text.Contains("timed out")) { string text2 = HttpLogBuilder.BuildTimeoutLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, timeToStartUpload, timeToFinishUpload, percentUploaded, timeToStartDownload, timeToFinishDownload, percentDownloaded, timeoutReason, timeoutTime); item.TimeoutLogs.Append(text2); item.TimeoutLogs.Append("\n\n"); logger.Error(text2); if (item.NumAttempts > 3) { logger.Critical("Too many timeouts: " + item.Uri.AbsoluteUri + "\nPrevious logs:\n" + item.TimeoutLogs); queue.Remove(item); CallCallbackWithFailureResult(item, response, responseHeaders); } ExecuteNextCall(); return; } } if (statusCode >= 500 && statusCode <= 599) { string text2 = HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode); if (item.NumAttempts > 1) { logger.Critical(text2); logger.Critical("Too many server errors"); queue.Remove(item); CallCallbackWithFailureResult(item, response, responseHeaders); } else { logger.Error(text2); } ExecuteNextCall(); } else if (HasErrorCode(response, "API_KEY_INVALID")) { logger.Error(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode)); if (item.RefreshedApiKey) { logger.Critical("Invalid API key. Already got new token once. Giving up."); queue.Remove(item); CallCallbackWithFailureResult(item, response, responseHeaders); ExecuteNextCall(); } else { logger.Error("Invalid API key. Getting new API key..."); GetApiKeyImmediately(delegate(GuestControllerResult <GuestControllerWebCallResponse> r) { if (!r.Success) { logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode)); logger.Critical("Getting new API key failed."); queue.Remove(item); CallCallbackWithFailureResult(item, response, responseHeaders); } ExecuteNextCall(); }); } } else if (HasErrorCode(response, "RATE_LIMITED")) { logger.Error(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode)); if (item.RefreshedApiKey) { logger.Critical("Couldn't get new API key. Already got new API key once. Giving up."); queue.Remove(item); CallCallbackWithFailureResult(item, response, responseHeaders); ExecuteNextCall(); } else { logger.Error("Rate limited. Getting new API key..."); GetApiKeyImmediately(delegate(GuestControllerResult <GuestControllerWebCallResponse> r) { if (!r.Success || HasErrorCode(r.Response, "RATE_LIMITED")) { logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode)); logger.Critical("Getting new API key failed."); queue.Remove(item); CallCallbackWithFailureResult(item, response, responseHeaders); } ExecuteNextCall(); }); } } else if (HasErrorCode(response, "ACCESS_TOKEN_NOT_FOUND", "AUTHORIZATION_INVALID_OR_EXPIRED_TOKEN")) { logger.Error(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode)); if (item.RefreshedAccessToken) { logger.Critical("Invalid access token. Already tried to refresh. Giving up."); queue.Remove(item); CallCallbackWithFailureResult(item, response, responseHeaders); ExecuteNextCall(); } else { logger.Error("Invalid access token. Refreshing..."); RefreshImmediately(delegate(GuestControllerResult <RefreshResponse> r) { if (!r.Success) { logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode)); logger.Critical("Refreshing access token failed"); queue.Remove(item); CallCallbackWithFailureResult(item, response, responseHeaders); } ExecuteNextCall(); }); } } else if (statusCode >= 401 && statusCode <= 499) { logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode)); queue.Remove(item); CallCallbackWithFailureResult(item, response, responseHeaders); ExecuteNextCall(); } else if (statusCode == 400 || (statusCode >= 200 && statusCode <= 299)) { logger.Debug(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode)); queue.Remove(item); item.Callback(new GuestControllerResult <GuestControllerWebCallResponse>(success: true, response, responseHeaders)); ExecuteNextCall(); } else { if (!string.IsNullOrEmpty(error)) { string text = error.ToLower(); if (text.Contains("connection appears to be offline") || text.Contains("connection was lost") || text.Contains("network is unreachable")) { logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode)); logger.Critical("Offline error = " + error); } else { logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode)); logger.Critical("Other web call error = " + error); } } queue.Remove(item); CallCallbackWithFailureResult(item, response, responseHeaders); ExecuteNextCall(); } } }; wwwCall.Execute(); }
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 arg) { throw new ArgumentException("Couldn't deserialize push notification: " + arg); } try { dictionary = DecryptPayload(encryptor, currentSymmetricEncryptionKey, payloadEncryptedBytes); } catch (Exception arg) { byte[] previousSymmetricEncryptionKey = sessionDocument.PreviousSymmetricEncryptionKey; if (previousSymmetricEncryptionKey == null) { throw new ArgumentException("Couldn't decrypt push notification: " + arg); } try { dictionary = DecryptPayload(encryptor, previousSymmetricEncryptionKey, payloadEncryptedBytes); } catch (Exception ex) { throw new ArgumentException("Couldn't decrypt push notification: " + arg + "\n" + ex); } } } StringBuilder stringBuilder = new StringBuilder("Received push notification with payload:\n"); IDictionaryEnumerator enumerator = dictionary.GetEnumerator(); try { while (enumerator.MoveNext()) { DictionaryEntry dictionaryEntry = (DictionaryEntry)enumerator.Current; stringBuilder.Append(dictionaryEntry.Key); stringBuilder.Append(" = "); stringBuilder.Append(dictionaryEntry.Value); stringBuilder.Append('\n'); } } finally { (enumerator as IDisposable)?.Dispose(); } 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)); } }
public SessionDocumentBuilder StartDefault(string path) { _sessionDocument = new SessionDocument(path, DocumentType.Text); return(this); }
public SessionDocumentBuilder StartDefault() { _sessionDocument = new SessionDocument("DEFAULT_PATH", DocumentType.Text); return(this); }
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); } } else if (data == null) { if (error2 != null) { logger.Critical("Received unhandled error exception:\n" + JsonParser.ToJson(error2) + "\nResponse headers:\n" + string.Join("\n", (from h in result.ResponseHeaders select h.Key + ": " + h.Value).ToArray())); } callback(new RestoreLastSessionResult(success: false, null)); } else if (!ValidateRefreshData(data)) { logger.Critical("Error parsing the refresh data: " + JsonParser.ToJson(data)); callback(new RestoreLastSessionResult(success: false, null)); } else { 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 arg) { logger.Critical("Error creating session: " + arg); callback(new RestoreLastSessionResult(success: false, null)); } } } catch (CorruptionException arg2) { logger.Fatal("Corruption detected during session restoration: " + arg2); callback(new RestoreLastSessionCorruptionDetectedResult()); } catch (Exception arg) { logger.Critical("Unhandled exception: " + arg); callback(new RestoreLastSessionResult(success: false, null)); } }