Esempio n. 1
0
        /// <summary>
        /// Gets an OAuth token for requested grant type.
        /// </summary>
        /// <param name="grantType">The type of grant request</param>
        /// <param name="scopes">List of scopes that is requested</param>
        /// <param name="basicAuthUsername">If you supply this, the basicAuthUsername and basicAuthPassword will be passed as credentials in BasicAuthentication format.  (Needed to generate a token for an addon)</param>
        /// <param name="basicAuthPassword">If you supply this, the basicAuthUsername and basicAuthPassword will be passed as credentials in BasicAuthentication format. </param>
        /// <param name="username">The user name to generate a token on behalf of.  Only valid in
        /// the 'Password' and 'ClientCredentials' grant types.</param>
        /// <param name="code">The authorization code to exchange for an access token.  Only valid in the 'AuthorizationCode' grant type</param>
        /// <param name="redirectUri">The Url that was used to generate an authorization code, and it must match that value.  Only valid in the 'AuthorizationCode' grant.</param>
        /// <param name="password">The user's password to use for authentication when creating a token.  Only valid in the 'Password' grant.</param>
        /// <param name="refreshToken">The refresh token to use to generate a new access token.  Only valid in the 'RefreshToken' grant.</param>
        public HipchatGenerateTokenResponse GenerateToken(
            GrantType grantType,
            IEnumerable <TokenScope> scopes,
            string basicAuthUsername = null,
            string basicAuthPassword = null,
            string username          = null,
            string code         = null,
            string redirectUri  = null,
            string password     = null,
            string refreshToken = null)
        {
            using (JsonSerializerConfigScope())
            {
                var request = new GenerateTokenRequest
                {
                    Username     = username,
                    Code         = code,
                    GrantType    = grantType,
                    Password     = password,
                    RedirectUri  = redirectUri,
                    RefreshToken = refreshToken,
                    Scope        = string.Join(" ", scopes.Select(x => x.ToString()))
                };

                Action <HttpWebRequest> requestFilter = x => { };
                if (!basicAuthUsername.IsEmpty() && !basicAuthPassword.IsEmpty())
                {
                    var auth      = string.Format("{0}:{1}", basicAuthUsername, basicAuthPassword);
                    var encrypted = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
                    var creds     = string.Format("{0} {1}", "Basic", encrypted);
                    requestFilter = x => x.Headers[HttpRequestHeader.Authorization] = creds;
                }



                var endpoint = HipchatEndpoints.GenerateTokenEndpoint;

                var form = request.FormEncodeHipchatRequest();
                try
                {
                    var response = endpoint
                                   .PostToUrl(request.FormEncodeHipchatRequest(), requestFilter: requestFilter)
                                   .FromJson <HipchatGenerateTokenResponse>();
                    return(response);
                }
                catch (Exception exception)
                {
                    if (exception is WebException)
                    {
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "");
                    }

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "GenerateToken");
                }
            }
        }
Esempio n. 2
0
        public HipchatViewRoomHistoryResponse ViewRoomHistory(string roomName, string date = "recent", string timezone = "UTC", int startIndex = 0, int maxResults = 100, bool reverse = true)
        {
            using (JsonSerializerConfigScope())
            {
                if (roomName.IsEmpty() || roomName.Length > 100)
                {
                    throw new ArgumentOutOfRangeException("roomName", "Valid roomName length is 1-100.");
                }
                if (date.IsEmpty())
                {
                    throw new ArgumentOutOfRangeException("date", "Valid date should be passed.");
                }
                if (timezone.IsEmpty())
                {
                    throw new ArgumentOutOfRangeException("timezone", "Valid timezone should be passed.");
                }
                if (startIndex > 100)
                {
                    throw new ArgumentOutOfRangeException("startIndex", "startIndex must be between 0 and 100");
                }
                if (maxResults > 1000)
                {
                    throw new ArgumentOutOfRangeException("maxResults", "maxResults must be between 0 and 1000");
                }

                try
                {
                    return(HipchatEndpoints.ViewRoomHistoryEndpoint.Fmt(roomName)
                           .AddQueryParam("date", date)
                           .AddQueryParam("timezone", timezone)
                           .AddQueryParam("start-index", startIndex)
                           .AddQueryParam("max-results", maxResults)
                           .AddQueryParam("reverse", reverse)
                           .AddHipchatAuthentication(_authToken)
                           .GetJsonFromUrl()
                           .FromJson <HipchatViewRoomHistoryResponse>());
                }
                catch (Exception exception)
                {
                    if (exception is WebException)
                    {
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "view_group");
                    }

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "ViewRoomHistory");
                }
            }
        }
Esempio n. 3
0
        public bool UpdateUser(string idOrEmail, UpdateUserRequest request)
        {
            using (JsonSerializerConfigScope())
            {
                var result = false;
                if (string.IsNullOrEmpty(idOrEmail))
                {
                    throw new ArgumentOutOfRangeException("idOrEmail", "Valid id, email address, or mention name (beginning with an '@') of the user required.");
                }
                if (string.IsNullOrEmpty(request.Name) || request.Name.Length > 50)
                {
                    throw new ArgumentOutOfRangeException("name", "Valid length range: 1 - 50.");
                }
                if (string.IsNullOrEmpty(request.Email))
                {
                    throw new ArgumentOutOfRangeException("email", "Valid email of the user required.");
                }

                try
                {
                    HipchatEndpoints.UpdateUserEndpointFormat
                    .Fmt(idOrEmail)
                    .AddHipchatAuthentication(_authToken)
                    .PutJsonToUrl(data: request, responseFilter: resp =>
                    {
                        if (resp.StatusCode == HttpStatusCode.NoContent)
                        {
                            result = true;
                        }
                    });
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                    if (exception is WebException)
                    {
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "admin_group");
                    }

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "UpdateUser");
                }

                return(result);
            }
        }
Esempio n. 4
0
        public void PrivateMessageUser(string idOrEmailOrMention, string message, bool notify = false,
                                       HipchatMessageFormat messageFormat = HipchatMessageFormat.Text)
        {
            if (idOrEmailOrMention.IsEmpty() || idOrEmailOrMention.Length > 10000)
            {
                throw new ArgumentOutOfRangeException("idOrEmailOrMention", "Valid length range: 1 - 10000.");
            }

            var endpoint = HipchatEndpoints.PrivateMessageUserEnpointFormat
                           .Fmt(idOrEmailOrMention);

            var request = new PrivateMessageUserRequest
            {
                Message       = message,
                Notify        = notify,
                MessageFormat = messageFormat
            };

            try
            {
                using (JsonSerializerConfigScope())
                {
                    endpoint
                    .AddHipchatAuthentication(_authToken)
                    .PostJsonToUrl(request);
                }


                //We could assert that we get a 204 here and return a boolean success / failure
                //but i guess we'll just assume everything went well or we would have got an exception
            }
            catch (Exception x)
            {
                if (x is WebException)
                {
                    throw ExceptionHelpers.WebExceptionHelper(x as WebException, "send_message");
                }

                throw ExceptionHelpers.GeneralExceptionHelper(x, "PrivateMessageUser");
            }
        }
Esempio n. 5
0
        public HipchatGenerateTokenResponse GenerateToken(
            GrantType grantType,
            IEnumerable <TokenScope> scopes,
            string username     = null,
            string code         = null,
            string redirectUri  = null,
            string password     = null,
            string refreshToken = null)
        {
            using (JsonSerializerConfigScope())
            {
                var request = new GenerateTokenRequest
                {
                    Username     = username,
                    Code         = code,
                    GrantType    = grantType,
                    Password     = password,
                    RedirectUri  = redirectUri,
                    RefreshToken = refreshToken,
                    Scope        = string.Join(" ", scopes.Select(x => x.ToString()))
                };

                try
                {
                    return(HipchatEndpoints.GenerateTokenEndpoint
                           .AddHipchatAuthentication(_authToken)
                           .PostJsonToUrl(request)
                           .FromJson <HipchatGenerateTokenResponse>());
                }
                catch (Exception exception)
                {
                    if (exception is WebException)
                    {
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "");
                    }

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "GenerateToken");
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Creates a webhook
        /// </summary>
        /// <param name="roomName">the name of the room</param>
        /// <param name="request">the request to send</param>
        /// <remarks>
        /// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/create_webhook
        /// </remarks>
        public CreateWebHookResponse CreateWebHook(string roomName, CreateWebHookRequest request)
        {
            using (JsonSerializerConfigScope())
            {
                try
                {
                    return(HipchatEndpoints.CreateWebhookEndpointFormat.Fmt(roomName)
                           .AddHipchatAuthentication()
                           .PostJsonToUrl(request)
                           .FromJson <CreateWebHookResponse>());
                }
                catch (Exception exception)
                {
                    if (exception is WebException)
                    {
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "admin_room");
                    }

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "CreateWebHook");
                }
            }
        }
Esempio n. 7
0
        public HipchatGetUserInfoResponse GetUserInfo(string emailOrMentionName)
        {
            using (JsonSerializerConfigScope())
            {
                try
                {
                    return(HipchatEndpoints.GetUserInfoEndpoint
                           .Fmt(emailOrMentionName)
                           .AddHipchatAuthentication(_authToken)
                           .GetJsonFromUrl()
                           .FromJson <HipchatGetUserInfoResponse>());
                }
                catch (Exception exception)
                {
                    if (exception is WebException)
                    {
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "view_group");
                    }

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "GetUserInfo");
                }
            }
        }
Esempio n. 8
0
        public HipchatGetEmoticonResponse GetEmoticon(string shortcut = "")
        {
            using (JsonSerializerConfigScope())
            {
                try
                {
                    return(HipchatEndpoints.GetEmoticonEndpoint
                           .Fmt(shortcut)
                           .AddHipchatAuthentication(_authToken)
                           .GetJsonFromUrl()
                           .FromJson <HipchatGetEmoticonResponse>());
                }
                catch (Exception exception)
                {
                    if (exception is WebException)
                    {
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "view_group");
                    }

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "GetEmoticon");
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Gets all webhooks for this room
        /// </summary>
        /// <param name="roomName">The name of the room</param>
        /// <param name="startIndex">The start index for the result set</param>
        /// <param name="maxResults">The maximum number of results</param>
        /// <returns>A GetAllWebhooks Response</returns>
        /// <remarks>
        /// Auth required, with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/get_all_webhooks
        /// </remarks>
        public HipchatGetAllWebhooksResponse GetAllWebhooks(string roomName, int startIndex = 0, int maxResults = 0)
        {
            using (JsonSerializerConfigScope())
            {
                try
                {
                    return(HipchatEndpoints.GetAllWebhooksEndpointFormat.Fmt(roomName)
                           .AddQueryParam("start-index", startIndex)
                           .AddQueryParam("max-results", maxResults)
                           .AddHipchatAuthentication()
                           .GetJsonFromUrl()
                           .FromJson <HipchatGetAllWebhooksResponse>());
                }
                catch (Exception exception)
                {
                    if (exception is WebException)
                    {
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "admin_room");
                    }

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "GetAllWebhooks");
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Send a message to a room
        /// </summary>
        /// <param name="roomName">The id of the room</param>
        /// <param name="request">The request containing the info about the notification to send</param>
        /// <returns>true if the message successfully sent</returns>
        /// <remarks>
        /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/send_room_notification
        /// </remarks>
        public bool SendNotification(string roomName, SendRoomNotificationRequest request)
        {
            using (JsonSerializerConfigScope())
            {
                if (request.Message.IsEmpty() || request.Message.Length > 10000)
                {
                    throw new ArgumentOutOfRangeException("request",
                                                          "message length must be between 0 and 10k characters");
                }

                var result = false;
                try
                {
                    HipchatEndpoints.SendNotificationEndpointFormat
                    .Fmt(roomName)
                    .AddHipchatAuthentication()
                    .PostJsonToUrl(request, null, x =>
                    {
                        if (x.StatusCode == HttpStatusCode.NoContent)
                        {
                            result = true;
                        }
                    });
                }
                catch (Exception exception)
                {
                    if (exception is WebException)
                    {
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "send_notification");
                    }

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "SendNotification");
                }
                return(result);
            }
        }