public SubscriptionBodyResponse Create(int planId, SubscriptionBody items)
        {
            var param = new
            {
                id = planId
            };
            var           result        = Login.EndPoints.CreateSubscription(param, items.ToObjects());
            List <Charge> charges       = new List <Charge>();
            var           chargesJToken = ((Newtonsoft.Json.Linq.JArray)result.data.charges).GetEnumerator();

            while (chargesJToken.MoveNext())
            {
                dynamic current = chargesJToken.Current;
                if (current != null)
                {
                    charges.Add(new Charge(
                                    (int)current.charge_id,
                                    (string)current.status,
                                    (int)current.total,
                                    (int)current.parcel)
                                );
                }
            }
            return(new SubscriptionBodyResponse(
                       (int)result.code,
                       (int)result.data.subscription_id,
                       (string)result.data.status,
                       (string)result.data.customId,
                       charges,
                       DateTime.Parse((string)result.data.created_at)
                       ));
        }
Пример #2
0
		private async Task<ServiceEvent<JToken>> doSubscribe(string channelName,string deviceId)
        {
            var resource = "/subscriptions/"
                + WebUtility.UrlEncode(app.Name)
                + (string.IsNullOrWhiteSpace(channelName) ? "" : "/" + WebUtility.UrlEncode(channelName));
            var body = new SubscriptionBody(deviceId);
            return await Url.Concat(resource).ExecuteAsync<JToken>(app, body.ToJToken(), "POST");
        }
Пример #3
0
        private async Task <ServiceEvent <JToken> > doSubscribe(string channelName, string deviceId, string registrationId)
        {
            var resource = "/subscriptions/"
                           + WebUtility.UrlEncode(app.Name)
                           + (string.IsNullOrWhiteSpace(channelName) ? "" : "/" + WebUtility.UrlEncode(channelName));
            var body = new SubscriptionBody(deviceId, registrationId);

            return(await Url.Concat(resource).ExecuteAsync <JToken>(app, body.ToJToken(), "POST"));
        }
Пример #4
0
        public async Task <string> SubscribeAsync(SubscriptionBody subscriptionBody, string username)
        {
            var subscription = new Subscription(
                username,
                subscriptionBody.DataType,
                subscriptionBody.ModificationTypes.Distinct().ToList(),
                subscriptionBody.Filter);
            await subscriptionCollection.InsertOneAsync(subscription);

            return(subscription.Id);
        }
Пример #5
0
        public async Task <IActionResult> Subscribe([FromBody] SubscriptionBody subscription)
        {
            if (subscription == null)
            {
                return(BadRequest("Subscription body was missing or malformatted"));
            }
            if (subscription.ModificationTypes.Count == 0)
            {
                return(BadRequest($"{nameof(SubscriptionBody.ModificationTypes)} was empty"));
            }
            if (subscription.ModificationTypes.Any(x => x == DataModificationType.Unknown))
            {
                return(BadRequest($"{nameof(SubscriptionBody.ModificationTypes)} contained value '{DataModificationType.Unknown}'"));
            }

            // Authroize
            var loggedInUsername    = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name);
            var authorizationResult = await authorizationModule.AuthorizeAsync(
                new SubscriptionResourceDescription(subscription.DataType),
                loggedInUsername);

            if (!authorizationResult.IsAuthorized)
            {
                return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized"));
            }
            var username = authorizationResult.User.UserName;

            if (await subscriptionManager.HasExistingSubscriptionAsync(subscription, username))
            {
                return(Conflict("A subscription with exact same parameters already exists"));
            }

            // Provide
            var subscriptionId = await subscriptionManager.SubscribeAsync(subscription, username);

            apiEventLogger.Log(LogLevel.Info, $"User '{username}' subscribed to '{subscription.DataType}' with filter '{subscription.Filter}'");
            return(new ContentResult
            {
                ContentType = "text/plain",
                Content = subscriptionId,
                StatusCode = (int)HttpStatusCode.OK
            });
        }
Пример #6
0
        public async Task <bool> HasExistingSubscriptionAsync(SubscriptionBody subscriptionBody, string username)
        {
            using var cursor = await subscriptionCollection.Find(
                      x =>
                      x.Username == username &&
                      x.DataType == subscriptionBody.DataType &&
                      x.Filter == subscriptionBody.Filter)
                               .ToCursorAsync();

            while (await cursor.MoveNextAsync())
            {
                foreach (var subscription in cursor.Current)
                {
                    var matchesNewSubscription = subscription.ModificationTypes.Distinct().ToList()
                                                 .Equivalent(subscriptionBody.ModificationTypes.Distinct().ToList());
                    if (matchesNewSubscription)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
        private static HttpContent ConstructSubscriptionBody(string dataType, IList <DataModificationType> modificationTypes, string filter)
        {
            var subscriptionBody = new SubscriptionBody(dataType, modificationTypes.ToList(), filter);

            return(PostBodyBuilder.ConstructBody(subscriptionBody));
        }
        /// <summary>
        /// Create a new integration subscription of a given kind.
        /// </summary>
        /// <param name="integrationKey">The key used to specify the integration kind.</param>
        /// <param name="subscriptionBody">Create a new integration subscription.</param>
        /// <returns>IntegrationSubscription</returns>
        public IntegrationSubscription PostIntegrationSubscription(string integrationKey, SubscriptionBody subscriptionBody)
        {
            // verify the required parameter 'integrationKey' is set
            if (integrationKey == null)
            {
                throw new ApiException(400, "Missing required parameter 'integrationKey' when calling PostIntegrationSubscription");
            }

            // verify the required parameter 'subscriptionBody' is set
            if (subscriptionBody == null)
            {
                throw new ApiException(400, "Missing required parameter 'subscriptionBody' when calling PostIntegrationSubscription");
            }


            var path = "/integrations/{integrationKey}";

            path = path.Replace("{format}", "json");
            path = path.Replace("{" + "integrationKey" + "}", ApiClient.ParameterToString(integrationKey));

            var    queryParams  = new Dictionary <String, String>();
            var    headerParams = new Dictionary <String, String>();
            var    formParams   = new Dictionary <String, String>();
            var    fileParams   = new Dictionary <String, FileParameter>();
            String postBody     = null;

            postBody = ApiClient.Serialize(subscriptionBody);                                     // http body (model) parameter

            // authentication setting, if any
            String[] authSettings = new String[] { "Token" };

            // make the HTTP request
            IRestResponse response = (IRestResponse)ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

            if (((int)response.StatusCode) >= 400)
            {
                throw new ApiException((int)response.StatusCode, "Error calling PostIntegrationSubscription: " + response.Content, response.Content);
            }
            else if (((int)response.StatusCode) == 0)
            {
                throw new ApiException((int)response.StatusCode, "Error calling PostIntegrationSubscription: " + response.ErrorMessage, response.ErrorMessage);
            }

            return((IntegrationSubscription)ApiClient.Deserialize(response.Content, typeof(IntegrationSubscription), response.Headers));
        }
 public SubscriptionBodyResponse Create(PlanResponse <PlanResponseData> planResponse, SubscriptionBody items)
 => Create(planResponse.Data.PlanId, items);