Example #1
0
        public async Task SendPushNotificationAsync(IPushNotification pushNotification, IAppCenterServerConfig appCenterConfig)
        {
            foreach (var target in pushNotification.DeviceTargets)
            {
                if (!appCenterConfig.AppNames.TryGetValue(target.TargetDevicePlatform, out var appNameForPlatform))
                {
                    _logger.LogWarning("App Center app name not found for " + target.TargetDevicePlatform.Value);
                    return;
                }

                var organizationName = appCenterConfig.OrganizationName;
                var appName          = appNameForPlatform;
                var apiEndpoint      = $"https://api.appcenter.ms/v0.1/apps/{organizationName}/{appName}/push/notifications";
                var dto      = new AppCenterPushRequestDto(pushNotification, target.TargetDevicePlatform);
                var apiToken = appCenterConfig.ApiToken;
                var request  = new HttpRequestWrapper <AppCenterPushRequestDto>(apiEndpoint, dto)
                               .WithRequestHeader("X-API-Token", apiToken);

                try
                {
                    await _httpClientService.PostAsync <AppCenterPushRequestDto, AppCenterPushResponseDto>(request, CancellationToken.None);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Failed to send push notification request to app center");
                }
            }
        }
        private void SendNotification(CalendarEventWithAdditionalData message, IPushNotification notificationConfiguration)
        {
            var templateExpressionContext = new Dictionary <string, string>
            {
                ["employee"]  = message.Owner.Name,
                ["startDate"] = message.Event.Dates.StartDate.ToString("dd/MM/yyyy")
            };

            templateExpressionContext = new DictionaryMerge().Perform(
                templateExpressionContext,
                message.Event.AdditionalData.ToDictionary(x => x.Key, x => x.Value));

            var content = new PushNotificationContent
            {
                Title      = notificationConfiguration.Title,
                Body       = new TemplateExpressionParser().Parse(notificationConfiguration.Body, templateExpressionContext),
                CustomData = new
                {
                    message.Event.EventId,
                    message.Owner.EmployeeId,
                    ManagerId = message.Manager.EmployeeId,
                    Type      = message.NotificationType == NotificationType.Created
                        ? CalendarEventPushNotificationTypes.SickLeaveCreatedManager
                        : message.NotificationType == NotificationType.Prolonged
                            ? CalendarEventPushNotificationTypes.SickLeaveProlongedManager
                            : CalendarEventPushNotificationTypes.SickLeaveCancelledManager
                }
            };

            Context.System.EventStream.Publish(new NotificationEventBusMessage(
                                                   new PushNotification(content, message.ManagerPushTokens)));
        }
        public Response <NativeNotification> ExtractUwpNotification(IPushNotification pushNotification)
        {
            var launchProperties = new StringBuilder();

            if (pushNotification.DataProperties.Count > 0)
            {
                launchProperties.Append("{ ");

                launchProperties
                .Append("'Title' : '").Append(pushNotification.Title).Append("', ")
                .Append("'Body' : '").Append(pushNotification.Body).Append("', ")
                .Append("'Template_Name' : '").Append(pushNotification.Name).Append("'");

                foreach (var dataProperty in pushNotification.DataProperties)
                {
                    launchProperties
                    .Append(", '")
                    .Append(dataProperty.Key).Append("' : '").Append(dataProperty.Value).Append("'");
                }

                launchProperties.Append(" }");
            }

            var body = new StringBuilder();

            body.Append($"<toast launch=\"{launchProperties}\"><visual><binding template=\"ToastText01\">")
            .Append("<text id=\"1\">").Append(pushNotification.Title).Append("</text>")
            .Append("<text id=\"2\">").Append(pushNotification.Body).Append("</text>")
            .Append("</binding></visual></toast>");

            var nativeNotification = new NativeNotification(new WindowsNotification(body.ToString()));

            return(Response.Success(nativeNotification));
        }
        public Response <NativeNotification> ExtractAndroidNotification(IPushNotification pushNotification)
        {
            var body = new StringBuilder();

            body.Append("{ ");

            body.Append("\"notification\" : { ");
            body.Append("\"title\" : \"").Append(pushNotification.Title).Append("\", ");
            body.Append("\"body\" : \"").Append(pushNotification.Body).Append("\"");
            body.Append(" }, ");

            body.Append("\"data\" : { ");
            body.Append("\"Template_Name\" : ").Append($"\"{pushNotification.Name}\", ");
            body.Append("\"Title\" : ").Append($"\"{pushNotification.Title}\", ");
            body.Append("\"Body\" : ").Append($"\"{pushNotification.Body}\"");

            foreach (var dataProperty in pushNotification.DataProperties)
            {
                body
                .Append(", \"")
                .Append(dataProperty.Key).Append("\" : \"").Append(dataProperty.Value).Append("\"");
            }

            body.Append(" } }");

            var nativeNotification = new NativeNotification(new FcmNotification(body.ToString()));

            return(Response.Success(nativeNotification));
        }
        public async Task <Response> SendNotificationToTargetAsync(IPushNotification pushNotification, IDeviceTarget deviceTarget, IPushNotificationsHub hub)
        {
            _analyticsService.TraceVerbose(this, "Send push notification to device", new Dictionary <string, object>
            {
                { nameof(PushNotification), pushNotification }, { nameof(DeviceTarget), deviceTarget }
            });

            try
            {
                _hubClientProxy.Initialize(hub);

                var nativeNotificationResult = _nativeNotificationExtractor.ExtractNotification(deviceTarget.Platform, pushNotification);
                if (nativeNotificationResult.IsFailure)
                {
                    return(Response.Failure(nativeNotificationResult.Error));
                }

                var notification = nativeNotificationResult.Value.Notification;
                var devices      = new List <string> {
                    deviceTarget.PushNotificationServicesHandle
                };
                _analyticsService.Trace(this, "Native push notification extracted", LogSeverity.Verbose, notification.ToObjectDictionary());

                await _hubClientProxy.SendDirectNotificationAsync(notification, devices);

                return(Response.Success());
            }
            catch (Exception e)
            {
                return(_analyticsService.LogExceptionResponse(this, e, PushErrors.FailedToSendNotification));
            }
        }
        /// <summary>
        /// Sends notification through AppCenter
        /// </summary>
        /// <param name="notification">The notification to be sent</param>
        /// <returns>Task/void</returns>
        public async Task SendAsync(IPushNotification notification)
        {
            var url     = new Uri($"{BaseUrl}/{Organization}/{Android}/{PushNotificationUri}");
            var content = new StringContent(CreateJson(notification), Encoding.UTF8, "application/json");

            _httpClient.DefaultRequestHeaders.Clear();
            _httpClient.DefaultRequestHeaders.Add(ApiKeyName, _apiKey);
            await _httpClient.PostAsync(url, content);
        }
        public RegisterPageViewModel(INavigationService navigationService, IPageDialogService dialogService) : base(navigationService, dialogService)
        {
            Title = "Registre-se";

            RegisterCommand  = new DelegateCommand(RegisterCommandExecute, RegisterCommandCanExecute);
            PickPhotoCommand = new DelegateCommand(PickPhotoCommandExecute);

            _pushNotification = Xamarin.Forms.DependencyService.Get <IPushNotification>();
        }
        public EventStatusChangedPushNotificationActor(
            IPushNotification pushNotificationConfig,
            IActorRef userPreferencesActor,
            IActorRef pushDevicesActor)
        {
            this.pushNotificationConfig = pushNotificationConfig;
            this.userPreferencesActor   = userPreferencesActor;
            this.pushDevicesActor       = pushDevicesActor;

            Context.System.EventStream.Subscribe <CalendarEventChanged>(this.Self);
        }
Example #9
0
        // TODO: Model binding context?

        public SettingsPage()
        {
            _authService            = Resolver.Resolve <IAuthService>();
            _userDialogs            = Resolver.Resolve <IUserDialogs>();
            _settings               = Resolver.Resolve <ISettings>();
            _fingerprint            = Resolver.Resolve <IFingerprint>();
            _pushNotification       = Resolver.Resolve <IPushNotification>();
            _googleAnalyticsService = Resolver.Resolve <IGoogleAnalyticsService>();

            Init();
        }
 public InitiativeBatchService(ICampaignService campaignService,
                               INotificationService notificationService,
                               IPushNotification notification) : base()
 {
     Guard.NotNull(campaignService, nameof(campaignService));
     Guard.NotNull(notificationService, nameof(notificationService));
     Guard.NotNull(notification, nameof(notification));
     _notificationService = notificationService;
     _campaignService     = campaignService;
     _notification        = notification;
 }
Example #11
0
        public LoginPage(string email = null)
            : base(updateActivity: false)
        {
            _email                  = email;
            _authService            = Resolver.Resolve <IAuthService>();
            _userDialogs            = Resolver.Resolve <IUserDialogs>();
            _syncService            = Resolver.Resolve <ISyncService>();
            _settings               = Resolver.Resolve <ISettings>();
            _googleAnalyticsService = Resolver.Resolve <IGoogleAnalyticsService>();
            _pushNotification       = Resolver.Resolve <IPushNotification>();

            Init();
        }
        public EventUserGrantedApprovalPushNotificationActor(
            IPushNotification pushNotificationConfig,
            IActorRef organizationActor,
            IActorRef userPreferencesActor,
            IActorRef pushDevicesActor)
        {
            this.pushNotificationConfig = pushNotificationConfig;
            this.organizationActor      = organizationActor;
            this.userPreferencesActor   = userPreferencesActor;
            this.pushDevicesActor       = pushDevicesActor;

            Context.System.EventStream.Subscribe <CalendarEventApprovalsChanged>(this.Self);
        }
Example #13
0
        public Task SendNotificationToUserAsync(IPushNotification notification, string userId, IPushNotificationsHub hub)
        {
            _analyticsService.TraceVerbose(this, "Sending push notification to user", new Dictionary <string, object> {
                { nameof(IPushNotification), notification }, { "UserId", userId }
            });

            var tags = new List <string>
            {
                $"(UserId_{userId} && {notification.Name})"
            };

            return(SendNotificationToTagsAsync(notification, hub, tags));
        }
 public override void SetUp()
 {
     base.SetUp();
     _userId = Guid.NewGuid().ToString();
     _pushNotificationTemplate = new PushNotificationTemplate("MyTemplate", "My Title", "My Body", new List <string>
     {
         "PropertyOne",
         "PropertyTwo"
     });
     _notification = new PushNotificationBuilder(_pushNotificationTemplate)
                     .WithDataProperty("PropertyOne", "ValueOne")
                     .WithDataProperty("PropertyTwo", "ValueTwo")
                     .Create();
 }
Example #15
0
        public void Initialize()
        {
            Client = new MobileServiceClient(ApplicationParameters.AzureAppServiceUrl);

            _auth             = DependencyService.Get <IAuthentication>();
            _pushNotification = DependencyService.Get <IPushNotification>();

            if (!string.IsNullOrWhiteSpace(Settings.FacebookAuthToken) && !string.IsNullOrWhiteSpace(Settings.FacebookUserId))
            {
                Client.CurrentUser = new MobileServiceUser(Settings.FacebookUserId)
                {
                    MobileServiceAuthenticationToken = Settings.FacebookAuthToken
                };
            }
        }
        public InitiativeCampaignStatus(ICampaignService campaignService,
                                        IInitiativeService initiativeService,
                                        IPushNotification notification,
                                        INotificationService notificationService)
        {
            Guard.NotNull(campaignService, nameof(campaignService));
            Guard.NotNull(initiativeService, nameof(initiativeService));
            Guard.NotNull(notification, nameof(notification));
            Guard.NotNull(notificationService, nameof(notificationService));

            _campaignService     = campaignService;
            _initiativeService   = initiativeService;
            _notification        = notification;
            _notificationService = notificationService;
        }
        public LoginTwoFactorPage(string email, string masterPasswordHash, SymmetricCryptoKey key)
            : base(updateActivity: false)
        {
            _email = email;
            _masterPasswordHash = masterPasswordHash;
            _key = key;

            _authService            = Resolver.Resolve <IAuthService>();
            _userDialogs            = Resolver.Resolve <IUserDialogs>();
            _syncService            = Resolver.Resolve <ISyncService>();
            _googleAnalyticsService = Resolver.Resolve <IGoogleAnalyticsService>();
            _pushNotification       = Resolver.Resolve <IPushNotification>();

            Init();
        }
Example #18
0
        public async Task <IPushNotificationResponse> Dispatch(IPushNotification notification, CancellationToken cancellation)
        {
            var push = new FirebasePushNotification.Builder()
                       .WithTitle(notification.Title)
                       .WithText(notification.Text)
                       .WithData(notification.Data)
                       .SendTo(notification.Receiver)
                       .Build();

            var promise = await _client.PostAsync(_configuration.SendUrl, new StringContent(JsonConvert.SerializeObject(push), Encoding.Default, "application/json"));

            var response = await promise.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <PushNotificationResponse>(response));
        }
Example #19
0
        public override void SetUp()
        {
            base.SetUp();

            _pushNotification = new PushNotificationMockBuilder()
                                .With(x => x.Name, "AllMinionsAlert")
                                .With(x => x.Title, "Hear Ye!")
                                .With(x => x.Body, "The king is dead. Long live the king")
                                .With(x => x.DataProperties, new Dictionary <string, object>
            {
                { "Id", _id },
                { "Details", "He was stabbed in the bath" },
                { "Number of stabs", 12 }
            })
                                .Object;
        }
        public SickLeaveManagerPushNotificationActor(
            IPushNotification createdPushNotificationConfig,
            IPushNotification prolongedPushNotificationConfig,
            IPushNotification cancelledPushNotificationConfig,
            IActorRef organizationActor,
            IActorRef userPreferencesActor,
            IActorRef pushDevicesActor)
        {
            this.createdPushNotificationConfig   = createdPushNotificationConfig;
            this.prolongedPushNotificationConfig = prolongedPushNotificationConfig;
            this.cancelledPushNotificationConfig = cancelledPushNotificationConfig;
            this.organizationActor    = organizationActor;
            this.userPreferencesActor = userPreferencesActor;
            this.pushDevicesActor     = pushDevicesActor;

            Context.System.EventStream.Subscribe <CalendarEventCreated>(this.Self);
            Context.System.EventStream.Subscribe <CalendarEventChanged>(this.Self);
        }
Example #21
0
        public AppCenterPushRequestDto(IPushNotification pushNotification, RuntimePlatform targetTargetDevicePlatform)
        {
            foreach (var deviceTarget in pushNotification.DeviceTargets)
            {
                if (deviceTarget.TargetDevicePlatform.Equals(targetTargetDevicePlatform))
                {
                    NotificationTarget.Devices.Add(deviceTarget.TargetDeviceId);
                }
            }

            NotificationContent = new NotificationContent
            {
                Name       = pushNotification.Name,
                Title      = pushNotification.Title,
                Body       = pushNotification.Body,
                CustomData = pushNotification.CustomData
            };
        }
 private string CreateJson(IPushNotification notification)
 {
     return(JsonConvert.SerializeObject(new
     {
         notification_target = new
         {
             type = "devices_target",
             devices = notification.Devices.ToArray()
         },
         notification_content = new
         {
             name = notification.Name,
             title = notification.Title,
             body = notification.Body,
             custom_data = notification.CustomData
         }
     }));
 }
        public override void SetUp()
        {
            base.SetUp();
            _iosNotification = new AppleNotification("{}");
            MockNativeNotificationExtractor.Where_ExtractNotification_returns(new NativeNotification(_iosNotification));

            _pushNotification = new PushNotificationMockBuilder()
                                .With(x => x.Name, "TestNotificationType")
                                .With(x => x.Title, "News Alert")
                                .With(x => x.Body, "The lockdown is only in your mind")
                                .With(x => x.DataProperties, new Dictionary <string, object>
            {
                { "FavouriteColour", "Red" },
                { "FavouriteBand", "The Beatles" },
                { "Id", _id },
            }).Object;

            _target = DeviceTarget.Android("pnsHandle");
        }
        public VaultListSitesPage(bool favorites)
            : base(true)
        {
            _favorites        = favorites;
            _folderService    = Resolver.Resolve <IFolderService>();
            _siteService      = Resolver.Resolve <ISiteService>();
            _connectivity     = Resolver.Resolve <IConnectivity>();
            _userDialogs      = Resolver.Resolve <IUserDialogs>();
            _clipboardService = Resolver.Resolve <IClipboardService>();
            _syncService      = Resolver.Resolve <ISyncService>();
            _pushNotification = Resolver.Resolve <IPushNotification>();
            _settings         = Resolver.Resolve <ISettings>();

            var cryptoService = Resolver.Resolve <ICryptoService>();

            _loadExistingData = !_settings.GetValueOrDefault(Constants.FirstVaultLoad, true) || !cryptoService.KeyChanged;

            Init();
        }
Example #25
0
        private async Task SendNotificationToTagsAsync(IPushNotification notification, IPushNotificationsHub hub, IEnumerable <string> tags)
        {
            _hubClientProxy.Initialize(hub);

            var properties = notification.DataProperties.ToDictionary(notificationDataProperty =>
                                                                      notificationDataProperty.Key, notificationDataProperty => notificationDataProperty.Value.ToString());

            if (!string.IsNullOrWhiteSpace(notification.Title))
            {
                properties.Add("Title", notification.Title);
            }

            if (!string.IsNullOrWhiteSpace(notification.Body))
            {
                properties.Add("Body", notification.Body);
            }

            await _hubClientProxy.SendNotificationAsync(properties, tags);
        }
Example #26
0
        public NotificationLink(INotifyPropertyChanged source, string sourceProperty, IPushNotification target, string targetProperty)
        {
            Source         = source;
            SourceProperty = sourceProperty;
            Target         = target;
            TargetProperty = targetProperty;

            foreach (NotificationLink other in Registry)
            {
                if (other.Source == Source && other.SourceProperty == SourceProperty &&
                    other.Target == Target && other.TargetProperty == TargetProperty)
                {
                    return;
                }
            }

            Registry.Add(this);

            source.PropertyChanged += Notify;
        }
Example #27
0
        public LoginTwoFactorPage(string email, string masterPasswordHash, byte[] key)
            : base(updateActivity: false)
        {
            _email = email;
            _masterPasswordHash = masterPasswordHash;
            _key = key;

            _cryptoService          = Resolver.Resolve <ICryptoService>();
            _authService            = Resolver.Resolve <IAuthService>();
            _tokenService           = Resolver.Resolve <ITokenService>();
            _deviceInfoService      = Resolver.Resolve <IDeviceInfoService>();
            _appIdService           = Resolver.Resolve <IAppIdService>();
            _userDialogs            = Resolver.Resolve <IUserDialogs>();
            _syncService            = Resolver.Resolve <ISyncService>();
            _settings               = Resolver.Resolve <ISettings>();
            _googleAnalyticsService = Resolver.Resolve <IGoogleAnalyticsService>();
            _pushNotification       = Resolver.Resolve <IPushNotification>();

            Init();
        }
Example #28
0
        public LoginTwoFactorPage(string email, FullLoginResult result, TwoFactorProviderType?type = null)
            : base(updateActivity: false)
        {
            _deviceInfoService = Resolver.Resolve <IDeviceInfoService>();

            _email              = email;
            _result             = result;
            _masterPasswordHash = result.MasterPasswordHash;
            _key          = result.Key;
            _providers    = result.TwoFactorProviders;
            _providerType = type ?? GetDefaultProvider();

            _authService            = Resolver.Resolve <IAuthService>();
            _userDialogs            = Resolver.Resolve <IUserDialogs>();
            _syncService            = Resolver.Resolve <ISyncService>();
            _googleAnalyticsService = Resolver.Resolve <IGoogleAnalyticsService>();
            _twoFactorApiRepository = Resolver.Resolve <ITwoFactorApiRepository>();
            _pushNotification       = Resolver.Resolve <IPushNotification>();

            Init();
        }
Example #29
0
        public VaultListLoginsPage(bool favorites, string uri = null)
            : base(true)
        {
            _favorites              = favorites;
            _folderService          = Resolver.Resolve <IFolderService>();
            _loginService           = Resolver.Resolve <ILoginService>();
            _connectivity           = Resolver.Resolve <IConnectivity>();
            _userDialogs            = Resolver.Resolve <IUserDialogs>();
            _clipboardService       = Resolver.Resolve <IDeviceActionService>();
            _syncService            = Resolver.Resolve <ISyncService>();
            _pushNotification       = Resolver.Resolve <IPushNotification>();
            _deviceInfoService      = Resolver.Resolve <IDeviceInfoService>();
            _settings               = Resolver.Resolve <ISettings>();
            _googleAnalyticsService = Resolver.Resolve <IGoogleAnalyticsService>();

            var cryptoService = Resolver.Resolve <ICryptoService>();

            Uri = uri;

            Init();
        }
        public VaultListLoginsPage(bool favorites, string uri = null)
            : base(true)
        {
            _favorites              = favorites;
            _folderService          = Resolver.Resolve <IFolderService>();
            _loginService           = Resolver.Resolve <ILoginService>();
            _connectivity           = Resolver.Resolve <IConnectivity>();
            _userDialogs            = Resolver.Resolve <IUserDialogs>();
            _clipboardService       = Resolver.Resolve <IClipboardService>();
            _syncService            = Resolver.Resolve <ISyncService>();
            _pushNotification       = Resolver.Resolve <IPushNotification>();
            _deviceInfoService      = Resolver.Resolve <IDeviceInfoService>();
            _settings               = Resolver.Resolve <ISettings>();
            _googleAnalyticsService = Resolver.Resolve <IGoogleAnalyticsService>();

            var cryptoService = Resolver.Resolve <ICryptoService>();

            _loadExistingData = !_settings.GetValueOrDefault(Constants.FirstVaultLoad, true) || !cryptoService.KeyChanged;

            Uri = uri;

            Init();
        }
Example #31
0
 public UserSettingsViewModel(IUserSettings userSettings, IPushNotification pushNotification)
 {
     this.userSettings = userSettings;
     this.pushNotification = pushNotification;
 }