Пример #1
0
        public async Task Register(MobilePlatform platform, string handle, string registrationId, IEnumerable <string> tags)
        {
            var hub = _factory.NotificationHubClient;
            RegistrationDescription registration = null;

            switch (platform)
            {
            case MobilePlatform.Windows:
                registration = new WindowsRegistrationDescription(handle);
                break;

            case MobilePlatform.Apple:
                registration = new AppleRegistrationDescription(handle);
                break;

            case MobilePlatform.Android:
                registration = new FcmRegistrationDescription(handle);
                break;
            }

            registration.RegistrationId = registrationId;
            registration.Tags           = new HashSet <string>(tags ?? Enumerable.Empty <string>());

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException exception)
            {
                _logger.LogError(exception, "Unhandled exception was thrown during registration in Azure Notification Hub");
                throw;
            }
        }
Пример #2
0
        ///
        /// <summary>
        /// Register device to receive push notifications.
        /// Registration ID ontained from Azure Notification Hub has to be provided
        /// Then basing on platform (Android, iOS or Windows) specific
        /// handle (token) obtained from Push Notification Service has to be provided
        /// </summary>
        /// <param name="id"></param>
        /// <param name="deviceUpdate"></param>
        /// <returns></returns>
        public async Task <HubResponse> RegisterForPushNotifications(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registrationDescription = null;

            switch (deviceUpdate.Platform)
            {
            case MobilePlatform.ApplePushNotificationsService:
                registrationDescription = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case MobilePlatform.GoogleCloudMessaging:
                registrationDescription = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(new HubResponse().AddErrorMessage("Please provide correct platform notification service name."));
            }

            registrationDescription.RegistrationId = id;
            if (deviceUpdate.Tags != null)
            {
                registrationDescription.Tags = new HashSet <string>(deviceUpdate.Tags);
            }

            try
            {
                await _hubClient.CreateOrUpdateRegistrationAsync(registrationDescription);

                return(new HubResponse());
            }
            catch (MessagingException)
            {
                return(new HubResponse().AddErrorMessage("Registration failed because of HttpStatusCode.Gone. PLease register once again."));
            }
        }
Пример #3
0
        public async Task <IHttpActionResult> GetUpdateRegistration(string id, string platform, string token)
        {
            RegistrationDescription registration = null;

            switch (platform)
            {
            case "fcm":
                registration = new FcmRegistrationDescription(token);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;

            try
            {
                var dd = await _hubClient.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Ok());
        }
        // PUT api/register/5
        // This creates or updates a registration (with provided channelURI) at the specified id
        public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "gcm":
                registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Пример #5
0
        public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
        {
            // IMPORTANT: add logic to make sure that caller is allowed to register for the provided tags
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            //case "mpns":
            //    var toastTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
            //        "<wp:Notification xmlns:wp=\"WPNotification\">" +
            //           "<wp:Toast>" +
            //                "<wp:Text1>$(message)</wp:Text1>" +
            //           "</wp:Toast> " +
            //        "</wp:Notification>";
            //    registration = new MpnsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
            //    break;
            //case "wns":
            //    toastTemplate = @"<toast><visual><binding template=""ToastText01""><text id=""1"">$(message)</text></binding></visual></toast>";
            //    registration = new WindowsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
            //    break;
            case "apns":
                var alertTemplate = "{\"aps\":{\"alert\":\"$(message)\"}}";
                registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, alertTemplate);
                break;

            case "gcm":
                var messageTemplate = "{\"data\":{\"msg\":\"$(message)\"}}";
                registration = new FcmTemplateRegistrationDescription(deviceUpdate.Handle, messageTemplate);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;

            var username = HttpContext.Current.User.Identity.Name;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            if (!registration.Tags.Contains("all"))
            {
                registration.Tags.Add("all");
            }
            registration.Tags.Add("username:" + username);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        public async Task <bool> RegisterForPushNotifications(string id, DeviceRegistration deviceUpdate, UserManager <IdentityUser> userManager, ApplicationDbContext context)
        {
            RegistrationDescription registrationDescription = null;
            int deviceType = 0;

            switch (deviceUpdate.Platform)
            {
            case "apns":
                registrationDescription = new AppleRegistrationDescription(deviceUpdate.Handle, deviceUpdate.Tags);
                deviceType = DeviceType.IOS;
                break;

            case "fcm":
                registrationDescription = new FcmRegistrationDescription(deviceUpdate.Handle, deviceUpdate.Tags);
                deviceType = DeviceType.ANDROID;
                break;
            }

            registrationDescription.RegistrationId = id;
            if (deviceUpdate.Tags != null)
            {
                registrationDescription.Tags = new HashSet <string>(deviceUpdate.Tags);
            }

            try
            {
                var user = await userManager.FindByNameAsync(deviceUpdate.Tags[0].Split(":")[1]);

                if (!context.UserClaims.Any(x => x.UserId == user.Id && x.ClaimType == "PushNotificationsProvider"))
                {
                    IdentityUserClaim <string> claim = new IdentityUserClaim <string>()
                    {
                        UserId     = user.Id,
                        ClaimType  = "PushNotificationsProvider",
                        ClaimValue = deviceType.ToString()
                    };
                    context.Add(claim);
                }
                else
                {
                    var existingClaim = context.UserClaims.Single(x => x.UserId == user.Id && x.ClaimType == "PushNotificationsProvider");
                    existingClaim.ClaimValue = deviceType.ToString();
                    context.Update(existingClaim);
                }

                context.SaveChanges();

                await _hub.CreateOrUpdateRegistrationAsync(registrationDescription);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #7
0
        // PUT api/register/5
        // This creates or updates a registration (with provided channelURI) at the specified id

        //there are two ways be registered in the notifications hub
        //1 is the device directly make the connection
        //2 the Back-end connects the device
        public async Task <HttpResponseMessage> Put(HttpRequestMessage req)
        {
            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);
            RegistrationDescription registration = null;
            string platform = data.platform;
            //handle is the channel uri for the connection with the device, there are different code lines for each OS
            //Ex. var handle = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); for Windows app
            string handle = data.handle;

            switch (platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(handle);
                break;

            case "gcm":
                registration = new GcmRegistrationDescription(handle);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            string id = data.id;

            registration.RegistrationId = id;
            string username = data.username;

            string[] tags = data.tags;
            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(tags);
            //username can be repeated many times due to the devices he has
            registration.Tags.Add("username:" + username);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
 /// <summary>
 /// Creates or updates a registration in the specified location.
 /// </summary>
 /// <param name="registration"></param>
 /// <returns></returns>
 public async Task <RegistrationDescription> CreateOrUpdateRegistration(RegistrationDescription registration)
 {
     if (string.IsNullOrEmpty(registration.RegistrationId) || string.IsNullOrWhiteSpace(registration.RegistrationId))
     {
         return(await CreateRegistration(registration));
     }
     else
     {
         return(await UpdateRegistration(registration));
     }
 }
Пример #9
0
        public async Task <IActionResult> Put(string id, [FromBody] DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "fcm":
                registration = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(BadRequest());
            }

            registration.RegistrationId = id;

            var username = User.GetEmail();
            var userId   = User.GetUserId();

            if (string.IsNullOrEmpty(username))
            {
                return(Unauthorized());
            }

            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            // registration.Tags.Add("email:" + username.ToUpper());
            // registration.Tags.Add("userid:" + userId);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Ok());
        }
Пример #10
0
        public async Task <RegistrationDescription> Register(Guid userId, string installationId, string deviceToken)
        {
            if (Guid.Empty == userId)
            {
                throw new ArgumentException("userId");
            }

            // Get registrations for the current installation ID.
            var regsForInstId = await hubClient.GetRegistrationsByTagAsync(installationId, 100);


            var updated           = false;
            var firstRegistration = true;
            RegistrationDescription registration = null;

            // Check for existing registrations.
            foreach (var registrationDescription in regsForInstId)
            {
                if (firstRegistration)
                {
                    // Update the tags.
                    registrationDescription.Tags = new HashSet <string>()
                    {
                        installationId, userId.ToString()
                    };

                    var iosReg = registrationDescription as AppleRegistrationDescription;
                    iosReg.DeviceToken = deviceToken;
                    registration       = await hubClient.UpdateRegistrationAsync(iosReg);

                    updated           = true;
                    firstRegistration = false;
                }
                else
                {
                    await hubClient.DeleteRegistrationAsync(registrationDescription);
                }
            }

            if (!updated)
            {
                registration = await hubClient.CreateAppleNativeRegistrationAsync(deviceToken,
                                                                                  new string[] { installationId, userId.ToString() });
            }

            // Send out a welcome notification.
            await this.Send(userId, "Thanks for registering");

            return(registration);
        }
        public async Task <IActionResult> Post(DeviceRegistration device)
        {
            // New registration, execute cleanup
            if (device.RegistrationId == null && device.Handle != null)
            {
                var registrations = await _hub.GetRegistrationsByChannelAsync(device.Handle, 100);

                foreach (var registration in registrations)
                {
                    await _hub.DeleteRegistrationAsync(registration);
                }

                device.RegistrationId = await _hub.CreateRegistrationIdAsync();
            }

            // ready to registration
            // ...

            RegistrationDescription deviceRegistration = null;

            switch (device.Platform)
            {
            // ...
            case "apns":
                deviceRegistration = new AppleRegistrationDescription(device.Handle);
                break;
                //...
            }

            deviceRegistration.RegistrationId = device.RegistrationId;

            deviceRegistration.Tags = new HashSet <string>(device.Tags);

            // Get the user email depending on the current identity provider
            deviceRegistration.Tags.Add($"username:{GetCurrentUser()}");

            await _hub.CreateOrUpdateRegistrationAsync(deviceRegistration);

            var deviceInstallation = new Installation();

            // ... populate fields
            deviceInstallation.Templates = new Dictionary <string, InstallationTemplate>();
            deviceInstallation.Templates.Add("type:Welcome", new InstallationTemplate
            {
                Body = "{\"aps\": {\"alert\" : \"Hi ${FullName} welcome to Auctions!\" }}"
            });

            return(Ok());
        }
        public async Task <ApiResponse> RegisterForPushNotifications(string registrationId, DeviceRegistration deviceUpdate)
        {
            var hub = _notificationHubFactory.NotificationHubClient;
            RegistrationDescription registrationDescription = null;

            switch (deviceUpdate.Platform)
            {
            case MobilePlatform.wns:
                registrationDescription = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case MobilePlatform.apns:
                registrationDescription = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case MobilePlatform.fcm:
                registrationDescription = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(new ApiResponse()
                       .SetAsFailureResponse(new Core.Exceptions.Error("Cannot register for push notifications",
                                                                       "Please provide correct platform notification service name")));
            }

            registrationDescription.RegistrationId = registrationId;
            if (deviceUpdate.Tags != null)
            {
                registrationDescription.Tags = new HashSet <string>(deviceUpdate.Tags);
            }

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registrationDescription);

                return(new ApiResponse());
            }
            catch (MessagingException exception)
            {
                Log.Error("Unhandled exception was thrown during registration in the Azure Notification Hub:");
                Log.Error(exception.Message);
                Log.Error(exception.StackTrace);

                return(new ApiResponse()
                       .SetAsFailureResponse(new Core.Exceptions.Error("Cannot register for push notifications",
                                                                       "Registration failed because of HttpStatusCode.Gone. Please register once again")));
            }
        }
Пример #13
0
 private static string setPns(string pns, RegistrationDescription item)
 {
     if (item is WindowsRegistrationDescription)
     {
         pns = "wns";
     }
     else if (item is GcmRegistrationDescription)
     {
         pns = "gcm";
     }
     else if (item is AppleRegistrationDescription)
     {
         pns = "apns";
     }
     return(pns);
 }
Пример #14
0
        // PUT api/register/5
        // This creates or updates a registration (with provided channelURI) at the specified id
        public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                var toastTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                    "<wp:Notification xmlns:wp=\"WPNotification\">" +
                                    "<wp:Toast>" +
                                    "<wp:Text1>$(message)</wp:Text1>" +
                                    "</wp:Toast> " +
                                    "</wp:Notification>";
                registration = new MpnsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
                break;

            case "wns":
                toastTemplate = @"<toast><visual><binding template=""ToastText01""><text id=""1"">$(message)</text></binding></visual></toast>";
                registration  = new WindowsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
                break;

            case "apns":
                var alertTemplate = "{\"aps\":{\"alert\":\"$(nameandmsg)\",\"badge\":1}}";
                registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, alertTemplate);
                break;

            case "gcm":
                var messageTemplate = "{\"data\":{\"msg\":\"$(message)\",\"senderid\":\"$(userid)\",\"sender\":\"$(username)\",\"icon\":\"$(usericon)\"}}";
                registration = new GcmTemplateRegistrationDescription(deviceUpdate.Handle, messageTemplate);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            registration.RegistrationId = id;
            registration.Tags           = new HashSet <string>(deviceUpdate.Tags);
            try
            {
                await _hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Пример #15
0
        // PUT api/register/5
        // This creates or updates a registration (with provided PNS handle) at the specified id
        public async Task <IHttpActionResult> Put(string id, DeviceRegistration deviceUpdate)
        {
            // IMPORTANT: add logic to make sure that caller is allowed to register for the provided tags

            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "gcm":
                registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;

            if (deviceUpdate.Tags != null)
            {
                registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            }

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Ok());
        }
        /// <summary>
        /// Updates an existing registration.
        /// </summary>
        /// <param name="registration"></param>
        /// <returns></returns>
        public async Task <RegistrationDescription> UpdateRegistration(RegistrationDescription registration)
        {
            HttpClient hc = GetClient($"registrations/{registration.RegistrationId}");

            try
            {
                HttpResponseMessage response = await hc.PutAsync(string.Empty, new StringContent(registration.SerializeAsEntry(), Encoding.UTF8, "application/atom+xml"));

                response.EnsureSuccessStatusCode();

                return(registration.Deserialize(await response.Content.ReadAsStringAsync()));
            }
            catch (Exception e)
            {
                throw (new Exception("Error on service call", e));
            }
        }
Пример #17
0
        public static bool TryGetPlatform(this RegistrationDescription registration, out PushPlatformEnum platform)
        {
            switch (registration)
            {
            case AppleRegistrationDescription a:
                platform = PushPlatformEnum.iOS;
                return(true);

            case FcmRegistrationDescription g:
                platform = PushPlatformEnum.Android;
                return(true);

            default:
                platform = PushPlatformEnum.Android;
                return(false);
            }
        }
Пример #18
0
        public static DeviceRegistration Convert(RegistrationDescription description)
        {
            if (description == null || !description.TryGetPlatform(out var platform))
            {
                return(null);
            }

            var deviceRegistration = new DeviceRegistration
            {
                Tags           = new List <string>(description.Tags),
                RegistrationId = description.RegistrationId,
                Platform       = platform,
                PnsHandle      = RetrieveDeviceHandle(platform, description)
            };

            return(deviceRegistration);
        }
Пример #19
0
        public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "gcm":
                registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;
            var identity = (ClaimsIdentity)User.Identity;
            var email    = identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Email).Value;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            //registration.Tags.Add("username:" + email);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Пример #20
0
        // PUT api/register/5
        // This creates or updates a registration (with provided channelURI) at the specified id
        public async Task <IActionResult> Put(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "fcm":
                registration = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;
            var username = HttpContext.User.Identity.Name;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            registration.Tags.Add("username:" + username);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Ok());
        }
        // PUT api/register/5
        // Cria ou atualiza um registron (com o channelURI fornecido) no para id
        public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "gcm":
                registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;
            var username = HttpContext.Current.User.Identity.Name;

            // incluir validação se o usuário pode adicionar essas tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            registration.Tags.Add("username:" + username);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Пример #22
0
        public async Task <IActionResult> RegisterDevice(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "fcm":
                registration = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(BadRequest());
            }

            registration.RegistrationId = id;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            registration.Tags.Add("rider:" + deviceUpdate.riderName);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Ok(registration));
        }
        /// <summary>
        /// Delete a push notification hub registration for an existing app instance
        /// </summary>
        /// <param name="hubRegistrationId">Hub registration id</param>
        /// <returns>Delete registration task</returns>
        public async Task DeleteRegistration(string hubRegistrationId)
        {
            // check input
            if (string.IsNullOrWhiteSpace(hubRegistrationId))
            {
                this.Log.LogException("got empty hub registration ID");
            }

            // get the hub client; this call does not hit the network
            NotificationHubClient hubClient = NotificationHubClient.CreateClientFromConnectionString(this.connectionString, this.appId);

            // get the registration & delete it. These calls will hit the network
            RegistrationDescription registrationDescription = await this.GetRegistrationAsync(hubClient, hubRegistrationId);

            if (registrationDescription != null)
            {
                await hubClient.DeleteRegistrationAsync(registrationDescription);
            }
        }
Пример #24
0
        private async Task <bool> VerifyTags(string channelUri, string installationId, NotificationHubClient nhClient)
        {
            IPrincipal user = this.User;
            int        expectedTagsCount = 1;

            if (user.Identity != null && user.Identity.IsAuthenticated)
            {
                expectedTagsCount = 2;
            }

            string continuationToken = null;

            do
            {
                CollectionQueryResult <RegistrationDescription> regsForChannel = await nhClient.GetRegistrationsByChannelAsync(channelUri, continuationToken, 100);

                continuationToken = regsForChannel.ContinuationToken;
                foreach (RegistrationDescription reg in regsForChannel)
                {
                    RegistrationDescription registration = await nhClient.GetRegistrationAsync <RegistrationDescription>(reg.RegistrationId);

                    if (registration.Tags == null || registration.Tags.Count() < expectedTagsCount)
                    {
                        return(false);
                    }
                    if (!registration.Tags.Contains("$InstallationId:{" + installationId + "}"))
                    {
                        return(false);
                    }

                    ClaimsIdentity identity    = user.Identity as ClaimsIdentity;
                    Claim          userIdClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
                    string         userId      = (userIdClaim != null) ? userIdClaim.Value : string.Empty;

                    if (user.Identity != null && user.Identity.IsAuthenticated && !registration.Tags.Contains("_UserId:" + userId))
                    {
                        return(false);
                    }
                }
            } while (continuationToken != null);
            return(true);
        }
Пример #25
0
        /// <summary>
        /// 以userId更新其裝置PNS的資訊
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pns"></param>
        /// <param name="pnsToken"></param>
        /// <returns></returns>
        public async Task <string> updateRegId(string userId, PNS pns, string pnsToken)
        {
            string tag = getUserTag(userId);

            //取得或新建azure regId
            string regId = await getRegIdAsync(tag);

            //依pns類型建立註冊描述
            RegistrationDescription registration = null;

            switch (pns)
            {
            case PNS.apns:
                registration = new AppleRegistrationDescription(pnsToken);
                break;

            case PNS.gcm:
                registration = new GcmRegistrationDescription(pnsToken);
                break;

            default:
                break;
            }

            try
            {
                //填入內容並更新到azure notification hub
                registration.RegistrationId = regId;
                registration.Tags           = new HashSet <string>();
                registration.Tags.Add(D.NTFTAG.EVERYBODY);
                registration.Tags.Add(tag);

                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                Console.WriteLine(e.ToString());
                return(null);
            }

            return(registration.RegistrationId);
        }
Пример #26
0
        private static string RetrieveDeviceHandle(PushPlatformEnum platform, RegistrationDescription description)
        {
            switch (platform)
            {
            case PushPlatformEnum.iOS:
            {
                return(((AppleTemplateRegistrationDescription)description).DeviceToken);
            }

            case PushPlatformEnum.Android:
            {
                return(((FcmTemplateRegistrationDescription)description).FcmRegistrationId);
            }

            default:
            {
                return(null);
            }
            }
        }
Пример #27
0
        public async Task PutInstallations_RegistersUserId_IfAuthenticatedAndTagsExist()
        {
            // Arrange
            NotificationInstallationsController controller = InitializeAuthenticatedController();
            HttpConfiguration        config       = controller.Configuration;
            NotificationInstallation notification = GetNotificationInstallation();

            // Mock the PushClient and capture the Installation that we send to NH for later verification
            Installation installation   = null;
            var          pushClientMock = new Mock <PushClient>(config);

            pushClientMock.Setup(p => p.CreateOrUpdateInstallationAsync(It.IsAny <Installation>()))
            .Returns <Installation>((inst) =>
            {
                installation = inst;
                return(Task.FromResult(0));
            });
            pushClientMock.Setup(p => p.GetRegistrationsByTagAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()))
            .Returns(() =>
            {
                RegistrationDescription[] registrations = new RegistrationDescription[]
                {
                    new WindowsRegistrationDescription("http://someuri", new string[] { "tag1", "tag2", "_UserId:something" })
                };
                return(Task.FromResult(this.CreateCollectionQueryResult <RegistrationDescription>(registrations)));
            });
            config.SetPushClient(pushClientMock.Object);

            // Act
            await controller.PutInstallation(notification.InstallationId, notification);

            // Assert
            Assert.NotNull(installation);
            Assert.Equal(notification.InstallationId, installation.InstallationId);
            Assert.Equal(notification.PushChannel, installation.PushChannel);
            Assert.Equal(3, installation.Tags.Count());

            // verify the existing userid is removed and replaced with current
            Assert.Equal("_UserId:my:userid", installation.Tags[2]);
        }
Пример #28
0
        public RegistrationModel(RegistrationDescription description)
        {
            RegistrationId   = description.RegistrationId;
            RegistrationTime = description.ExpirationTime.Value.AddDays(-90);
            ExpirationTime   = description.ExpirationTime.Value;
            Tags             = description.Tags ?? new HashSet <string>();

            var windowsRegistrationDescription = description as WindowsRegistrationDescription;

            if (windowsRegistrationDescription != null)
            {
                Platform = Platforms.Windows;
                Handle   = windowsRegistrationDescription.ChannelUri.AbsoluteUri;
            }

            var mpnsRegistrationDescription = description as MpnsRegistrationDescription;

            if (mpnsRegistrationDescription != null)
            {
                Platform = Platforms.WindowsPhone;
                Handle   = mpnsRegistrationDescription.ChannelUri.AbsoluteUri;
            }

            var appleRegistrationDescription = description as AppleRegistrationDescription;

            if (appleRegistrationDescription != null)
            {
                Platform = Platforms.Apple;
                Handle   = appleRegistrationDescription.DeviceToken;
            }

            var gcmRegistrationDescription = description as GcmRegistrationDescription;

            if (gcmRegistrationDescription != null)
            {
                Platform = Platforms.Android;
                Handle   = gcmRegistrationDescription.GcmRegistrationId;
            }
        }
Пример #29
0
        public async Task Register(Registration registration)
        {
            if (registration.Handle == null)
            {
                throw new ArgumentNullException("Registration handle is null");
            }
            try
            {
                var registrations = await Hub.GetRegistrationsByChannelAsync(registration.Handle, 0);

                foreach (var regDescription in registrations)
                {
                    await Hub.DeleteRegistrationAsync(regDescription);
                }

                foreach (var key in registration.Keys)
                {
                    await Unregister(key);
                }
                await RemoveOld(registration.Handle);

                RegistrationDescription reg = await Hub.CreateFcmNativeRegistrationAsync(registration.Handle, registration.Keys);

                lock (devicesLock)
                {
                    Debug.WriteLine("registered " + registration.Keys);
                    registeredDevices.Add(new UserDevice
                    {
                        Registration   = registration,
                        RegistrationID = reg.RegistrationId
                    });
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("REGISTER " + e.Message);
                throw e;
            }
        }
        /// <summary>
        /// Create a push notification hub registration for a new app instance with the push notification hub for this app
        /// </summary>
        /// <param name="clientRegistrationId">Push notification registration id from the mobile OS</param>
        /// <param name="tags">Registration tags</param>
        /// <returns>Hub registration id</returns>
        public async Task <string> CreateRegistration(string clientRegistrationId, IEnumerable <string> tags)
        {
            // check input
            if (string.IsNullOrWhiteSpace(clientRegistrationId))
            {
                this.Log.LogException("got empty client registration ID");
            }

            // get the hub client; this call does not hit the network
            NotificationHubClient hubClient = NotificationHubClient.CreateClientFromConnectionString(this.connectionString, this.appId);

            // create the registration; this call will hit the network
            RegistrationDescription registrationDescription = await this.CreateRegistrationAsync(hubClient, clientRegistrationId, tags);

            if (registrationDescription == null || registrationDescription.IsReadOnly ||
                string.IsNullOrWhiteSpace(registrationDescription.RegistrationId))
            {
                this.Log.LogException("did not get registration back from Azure Hub");
            }

            return(registrationDescription.RegistrationId);
        }