Beispiel #1
0
        /// <summary>
        /// Sends a request to refresh the access token.
        /// </summary>
        /// <param name="accessToken">May contain an access token, which should be refreshed.</param>
        /// <remarks>
        /// <para>If <paramref name="accessToken"/> parameter is not specified, it will use the current access token from the same property of the current class instance.</para>
        /// <para>Token must contain the <b>refresh_token</b>, which was received together with the access token.</para>
        /// </remarks>
        /// <exception cref="NotSupportedException">
        /// <para>Provider does not support refreshing the access token, or the method is not implemented.</para>
        /// <para>Use the property <see cref="OAuthBase.SupportRefreshToken"/>, to check the possibility of calling this method.</para>
        /// </exception>
        /// <exception cref="AccessTokenException">
        /// <para>Access token is not found or is not specified.</para>
        /// <para>-or-</para>
        /// <para><b>refresh_token</b> value is empty.</para>
        /// </exception>
        /// <exception cref="RequestException">Error during execution of a web request.</exception>
        public override AccessToken RefreshToken(AccessToken accessToken = null)
        {
            if (!this.SupportRefreshToken)
            {
                throw new NotSupportedException();
            }

            var token = (OAuth2AccessToken)base.GetSpecifiedTokenOrCurrent(accessToken, refreshTokenRequired: true);

            var parameters = new HttpParameterCollection();

            parameters.AddFormParameter("access_token", token.Value);
            parameters.AddFormParameter("client_id", this.ApplicationId);
            parameters.AddFormParameter("client_secret", this.ApplicationSecret);
            parameters.AddFormParameter("grant_type", GrantType.RefreshToken);
            parameters.AddFormParameter("refresh_token", token.RefreshToken);

            var result = OAuthUtility.Post
                         (
                this.AccessTokenUrl,
                parameters: parameters
                         );

            return(new OAuth2AccessToken(result));
        }
        public static async Task <RequestResult> SendTweet(string text, List <string> media_ids)
        {
            var parameters = new HttpParameterCollection();

            parameters.AddFormParameter("status", text);

            // images
            if (media_ids != null && media_ids.Count > 0)
            {
                parameters.AddFormParameter("media_ids", String.Join(",", media_ids));
            }

            var t = Task.Run <RequestResult>(() =>
            {
                return(OAuthUtility.Post
                       (
                           "https://api.twitter.com/1.1/statuses/update.json",
                           parameters: parameters,
                           authorization: TwitterApi.GetAuth(),
                           contentType: "application/x-www-form-urlencoded"
                       ));
            });

            return(await t);
        }
        /// <summary>
        /// Uploads media (only photos).
        /// </summary>
        /// <remarks>
        /// <see href="https://dev.twitter.com/rest/reference/post/media/upload-init"/>
        /// </remarks>
        /// <param name="path">File path.</param>
        public static async Task <RequestResult> UploadMedia(string path, MeadiaUploadEventHandler uploadingCallback)
        {
            var file = new FileInfo(path);

            string media_type = "image/jpeg";

            switch (file.Extension.ToLower())
            {
            case ".png":
                media_type = "image/png";
                break;

            case ".gif":
                media_type = "image/gif";
                break;

            case ".bmp":
                media_type = "image/bmp";
                break;
            }

            var parameters = new HttpParameterCollection();

            parameters.AddFormParameter("command", "INIT");
            parameters.AddFormParameter("total_bytes", file.Length.ToString());
            parameters.AddFormParameter("media_type", media_type);
            parameters.AddFormParameter("media_category", "tweet_image");

            var t = Task.Run <RequestResult>(() =>
            {
                return(OAuthUtility.Post
                       (
                           "https://upload.twitter.com/1.1/media/upload.json",
                           parameters: parameters,
                           authorization: TwitterApi.GetAuth(),
                           contentType: "multipart/form-data"
                       ));
            });

            var result = await t;

            if (result.IsSuccessfully)
            {
                return(await TwitterApi.MeadiaUploadAppend(path, result["media_id"].ToString(), 0, uploadingCallback));
            }
            else
            {
                return(result);
            }
        }
        /// <summary>
        /// https://dev.twitter.com/rest/reference/post/media/upload-finalize
        /// </summary>
        /// <param name="media_id">Media id.</param>
        private static async Task <RequestResult> MeadiaUploadFinalize(string path, string media_id)
        {
            var parameters = new HttpParameterCollection();

            parameters.AddFormParameter("command", "FINALIZE");
            parameters.AddFormParameter("media_id", media_id);

            var t = Task.Run <RequestResult>(() =>
            {
                return(OAuthUtility.Post
                       (
                           "https://upload.twitter.com/1.1/media/upload.json",
                           parameters: parameters,
                           authorization: TwitterApi.GetAuth(),
                           contentType: "multipart/form-data"
                       ));
            });

            return(await t);
        }
Beispiel #5
0
        /// <summary>
        /// Sends a request to refresh the access token.
        /// </summary>
        /// <param name="accessToken">May contain an access token, which should be refreshed.</param>
        /// <param name="returnUrl">Callback address that was used in obtaining the access token.</param>
        /// <remarks>
        /// <para>If <paramref name="accessToken"/> parameter is not specified, it will use the current access token from the same property of the current class instance.</para>
        /// <para>Token must contain the <b>refresh_token</b>, which was received together with the access token.</para>
        /// <list type="table">
        /// <item>
        /// <term><img src="../img/warning.png" alt="(!)" title="" /></term>
        /// <term><b>To update the access token, you must specify the return address that was used in obtaining the access token.</b></term>
        /// </item>
        /// </list>
        /// </remarks>
        /// <exception cref="NotSupportedException">
        /// <para>Provider does not support refreshing the access token, or the method is not implemented.</para>
        /// <para>Use the property <see cref="OAuthBase.SupportRefreshToken"/>, to check the possibility of calling this method.</para>
        /// </exception>
        /// <exception cref="AccessTokenException">
        /// <para>Access token is not found or is not specified.</para>
        /// <para>-or-</para>
        /// <para><b>refresh_token</b> value is empty.</para>
        /// </exception>
        /// <exception cref="RequestException">Error during execution of a web request.</exception>
        /// <exception cref="ArgumentNullException">An exception occurs if there is no authorization code.</exception>
        public AccessToken RefreshToken(AccessToken accessToken, string returnUrl)
        {
            var token = (OAuth2AccessToken)base.GetSpecifiedTokenOrCurrent(accessToken, refreshTokenRequired: true);

            var parameters = new HttpParameterCollection();

            parameters.AddFormParameter("client_id", this.ApplicationId);
            parameters.AddFormParameter("client_secret", this.ApplicationSecret);
            parameters.AddFormParameter("redirect_uri", returnUrl);
            parameters.AddFormParameter("grant_type", GrantType.RefreshToken);
            parameters.AddFormParameter("refresh_token", token.RefreshToken);

            var result = OAuthUtility.Post
                         (
                this.AccessTokenUrl,
                parameters: parameters,
                authorization: new HttpAuthorization(AuthorizationType.Basic, OAuthUtility.ToBase64String("{0}:{1}", this.ApplicationId, this.ApplicationSecret))
                         );

            return(new OAuth2AccessToken(result));
        }
        /// <summary>
        /// https://dev.twitter.com/rest/reference/post/media/upload-append
        /// </summary>
        /// <param name="path">File path.</param>
        /// <param name="media_id">Media id.</param>
        /// <param name="chunk">Chunk. Default: 0.</param>
        /// <param name="uploadingCallback">Uploading callback.</param>
        private static async Task <RequestResult> MeadiaUploadAppend(string path, string media_id, int chunk, MeadiaUploadEventHandler uploadingCallback)
        {
            var  file      = new FileInfo(path);
            bool isUploded = false;

            byte[] media = null;

            if (chunk > 0)
            {
                // multiple chunks
                using (var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Inheritable))
                    using (var reader = new BinaryReader(stream))
                    {
                        stream.Position = (TwitterApi.MediaUploadChunkSize * chunk);
                        media           = reader.ReadBytes(TwitterApi.MediaUploadChunkSize);
                        isUploded       = (stream.Position == stream.Length);
                    }
            }
            else
            {
                if (file.Length <= TwitterApi.MediaUploadChunkSize)
                {
                    // one chunk
                    using (var reader = new BinaryReader(file.Open(FileMode.Open, FileAccess.Read, FileShare.Inheritable)))
                    {
                        media     = reader.ReadBytes(Convert.ToInt32(file.Length));
                        isUploded = true;
                    }
                }
                else
                {
                    // multiple chunks
                    using (var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Inheritable))
                        using (var reader = new BinaryReader(stream))
                        {
                            media     = reader.ReadBytes(TwitterApi.MediaUploadChunkSize);
                            isUploded = (stream.Position == stream.Length);
                        }
                }
            }

            var parameters = new HttpParameterCollection();

            parameters.AddFormParameter("command", "APPEND");
            parameters.AddFormParameter("media_id", media_id);
            parameters.AddFormParameter("segment_index", chunk.ToString());
            parameters.Add("media", Path.GetFileName(path), media);

            var t = Task.Run <RequestResult>(() =>
            {
                return(OAuthUtility.Post
                       (
                           "https://upload.twitter.com/1.1/media/upload.json",
                           parameters: parameters,
                           authorization: TwitterApi.GetAuth(),
                           contentType: "multipart/form-data",
                           streamWriteCallback: (object s, StreamWriteEventArgs e) =>
                {
                    int progressPercentage = 0;
                    long totalUploaded = 0;

                    if (chunk > 0)
                    {
                        totalUploaded = TwitterApi.MediaUploadChunkSize * chunk;
                    }

                    totalUploaded += e.TotalBytesWritten;

                    progressPercentage = Convert.ToInt32((totalUploaded * 100) / file.Length);

                    uploadingCallback?.Invoke(s, new ProgressChangedEventArgs(progressPercentage, null));
                }
                       ));
            });

            var result = await t;

            if (!result.IsSuccessfully)
            {
                // error
                return(result);
            }

            if (file.Length > TwitterApi.MediaUploadChunkSize && !isUploded)
            {
                // next chunk
                return(await TwitterApi.MeadiaUploadAppend(path, media_id, chunk + 1, uploadingCallback));
            }
            else
            {
                // finalize
                return(await TwitterApi.MeadiaUploadFinalize(path, media_id));
            }
        }
    /// <summary>
    /// Sends a request to refresh the access token.
    /// </summary>
    /// <param name="accessToken">May contain an access token, which should be refreshed.</param>
    /// <param name="returnUrl">Callback address that was used in obtaining the access token.</param>
    /// <remarks>
    /// <para>If <paramref name="accessToken"/> parameter is not specified, it will use the current access token from the same property of the current class instance.</para>
    /// <para>Token must contain the <b>refresh_token</b>, which was received together with the access token.</para>
    /// <list type="table">
    /// <item>
    /// <term><img src="../img/warning.png" alt="(!)" title="" /></term>
    /// <term><b>To update the access token, you must specify the return address that was used in obtaining the access token.</b></term>
    /// </item>
    /// </list>
    /// </remarks>
    /// <exception cref="NotSupportedException">
    /// <para>Provider does not support refreshing the access token, or the method is not implemented.</para>
    /// <para>Use the property <see cref="OAuthBase.SupportRefreshToken"/>, to check the possibility of calling this method.</para>
    /// </exception>
    /// <exception cref="AccessTokenException">
    /// <para>Access token is not found or is not specified.</para>
    /// <para>-or-</para>
    /// <para><b>refresh_token</b> value is empty.</para>
    /// </exception>
    /// <exception cref="RequestException">Error during execution of a web request.</exception>
    /// <exception cref="ArgumentNullException">An exception occurs if there is no authorization code.</exception>
    public AccessToken RefreshToken(AccessToken accessToken, string returnUrl)
    {
      var token = (OAuth2AccessToken)base.GetSpecifiedTokenOrCurrent(accessToken, refreshTokenRequired: true);

      var parameters = new HttpParameterCollection();
      parameters.AddFormParameter("client_id", this.ApplicationId);
      parameters.AddFormParameter("client_secret", this.ApplicationSecret);
      parameters.AddFormParameter("redirect_uri", returnUrl);
      parameters.AddFormParameter("grant_type", GrantType.RefreshToken);
      parameters.AddFormParameter("refresh_token", token.RefreshToken);

      var result = OAuthUtility.Post
      (
        this.AccessTokenUrl,
        parameters: parameters,
        authorization: new HttpAuthorization(AuthorizationType.Basic, OAuthUtility.ToBase64String("{0}:{1}", this.ApplicationId, this.ApplicationSecret))
      );

      return new OAuth2AccessToken(result);
    }
    /// <summary>
    /// Sends a request to refresh the access token.
    /// </summary>
    /// <param name="accessToken">May contain an access token, which should be refreshed.</param>
    /// <remarks>
    /// <para>If <paramref name="accessToken"/> parameter is not specified, it will use the current access token from the same property of the current class instance.</para>
    /// <para>Token must contain the <b>refresh_token</b>, which was received together with the access token.</para>
    /// </remarks>
    /// <exception cref="NotSupportedException">
    /// <para>Provider does not support refreshing the access token, or the method is not implemented.</para>
    /// <para>Use the property <see cref="OAuthBase.SupportRefreshToken"/>, to check the possibility of calling this method.</para>
    /// </exception>
    /// <exception cref="AccessTokenException">
    /// <para>Access token is not found or is not specified.</para>
    /// <para>-or-</para>
    /// <para><b>refresh_token</b> value is empty.</para>
    /// </exception>
    /// <exception cref="RequestException">Error during execution of a web request.</exception>
    public override AccessToken RefreshToken(AccessToken accessToken = null)
    {
      if (!this.SupportRefreshToken)
      {
        throw new NotSupportedException();
      }

      var token = (OAuth2AccessToken)base.GetSpecifiedTokenOrCurrent(accessToken, refreshTokenRequired: true);

      var parameters = new HttpParameterCollection();
      parameters.AddFormParameter("access_token", token.Value);
      parameters.AddFormParameter("client_id", this.ApplicationId);
      parameters.AddFormParameter("client_secret", this.ApplicationSecret);
      parameters.AddFormParameter("grant_type", GrantType.RefreshToken);
      parameters.AddFormParameter("refresh_token",  token.RefreshToken);

      var result = OAuthUtility.Post
      (
        this.AccessTokenUrl,
        parameters: parameters
      );

      return new OAuth2AccessToken(result);
    }