private IApiRequest GenerateVideosRequest(long?userId = null, long?clipId = null, int?page = null, int?perPage = null, string query = null)
        {
            ThrowIfUnauthorized();

            IApiRequest request  = ApiRequestFactory.GetApiRequest(AccessToken);
            string      endpoint = userId.HasValue
                ? clipId.HasValue ? Endpoints.UserVideo : Endpoints.UserVideos
                : clipId.HasValue ? Endpoints.Video : Endpoints.Videos;

            request.Method = HttpMethod.Get;
            request.Path   = endpoint;

            if (userId.HasValue)
            {
                request.UrlSegments.Add("userId", userId.ToString());
            }
            if (clipId.HasValue)
            {
                request.UrlSegments.Add("clipId", clipId.ToString());
            }
            if (page.HasValue)
            {
                request.Query.Add("page", page.ToString());
            }
            if (perPage.HasValue)
            {
                request.Query.Add("per_page", perPage.ToString());
            }
            if (!string.IsNullOrEmpty(query))
            {
                request.Query.Add("query", query);
            }

            return(request);
        }
Ejemplo n.º 2
0
        public async Task ShouldCreateRightUrl(Type contractType, string methodName, string basePath, string expectedUrl)
        {
            //Arrange
            var msgHandler = new TestMsgHandler();
            var httpClient = new HttpClient(msgHandler)
            {
                BaseAddress = new Uri(basePath)
            };

            var httpClientFactory = new SingleHttpClientProvider(httpClient);
            var factory           = new ApiRequestFactory(contractType, httpClientFactory);

            _output.WriteLine($"Service URL: {factory.ServiceDescription.Url}");
            _output.WriteLine($"Post method URL: {factory.ServiceDescription.Methods.Values.First().Url}");

            var method = contractType.GetMethod(methodName);

            var request = factory.Create(method, new object[] { "foo" });
            //_output.WriteLine($"Request URL: {request.}");

            //Act
            await request.CallAsync();

            //Assert
            _output.WriteLine($"Actual URL: {msgHandler.LastRequest.RequestUri.AbsoluteUri}");

            Assert.Equal(expectedUrl, msgHandler.LastRequest.RequestUri.AbsoluteUri);
        }
        private IApiRequest GenerateUpdateTextTrackRequest(long clipId, long trackId, TextTrack track)
        {
            ThrowIfUnauthorized();

            IApiRequest request = ApiRequestFactory.GetApiRequest(AccessToken);

            request.Method = Method.PATCH;
            request.Path   = Endpoints.TextTrack;
            request.UrlSegments.Add("clipId", clipId.ToString());
            request.UrlSegments.Add("trackId", trackId.ToString());

            if (track != null)
            {
                request.Query.Add("active", track.active.ToString().ToLower());
                if (track.name != null)
                {
                    request.Query.Add("name", track.name);
                }
                if (track.language != null)
                {
                    request.Query.Add("language", track.language);
                }
                if (track.type != null)
                {
                    request.Query.Add("type", track.type);
                }
            }

            return(request);
        }
Ejemplo n.º 4
0
        IAPI Create(ILogin login, IApiConfig config)
        {
            if (config is null)
            {
                throw new Exception("Configuration cannot be null");
            }

            IHttpHandler client      = new HttpHandler();
            IMemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()
            {
                SizeLimit = 128,                 // Each ApiRequest is one in size
            });

            if (!string.IsNullOrEmpty(config.SpecURL))
            {
                Spec = SpecFromUrl(config.SpecURL);
            }

            IFactory <IApiRequest>   apiRequestFactory   = new ApiRequestFactory();
            IFactory <ICacheControl> cacheControlFactory = new CacheControlFactory();

            ITokenManager    tokenManager    = new TokenManager(client, config, login);
            IResponseManager responseManager = new ResponseManager(client, config, login, cacheControlFactory);
            ICacheManager    cacheManager    = new CacheManager(client, config, login, memoryCache, tokenManager, responseManager);
            IRequestManager  requestManager  = new RequestManager(client, config, login, cacheManager, apiRequestFactory, Spec);
            IEventManager    eventManager    = new EventManager(client, config, login, cacheManager, requestManager);

            IFactory <IApiPath>        pathFacotry        = new ApiPathFactory(requestManager);
            IFactory <IApiEventMethod> eventMethodFactory = new ApiEventMethodFactory(eventManager);
            IFactory <IApiEventPath>   eventPathFactory   = new ApiEventPathFactory(eventMethodFactory);

            return(new API(login, config, pathFacotry, Spec, eventPathFactory));
        }
Ejemplo n.º 5
0
        private IApiRequest GenerateUpdateTextTrackRequest(long clipId, long trackId, [NotNull] TextTrack track)
        {
            ThrowIfUnauthorized();

            var request = ApiRequestFactory.GetApiRequest(AccessToken);

            request.Method = new HttpMethod("PATCH");
            request.Path   = Endpoints.TextTrack;
            request.UrlSegments.Add("clipId", clipId.ToString());
            request.UrlSegments.Add("trackId", trackId.ToString());

            var parameters = new Dictionary <string, string>
            {
                ["active"] = track.active.ToString().ToLower()
            };

            if (track.name != null)
            {
                parameters["name"] = track.name;
            }
            if (track.language != null)
            {
                parameters["language"] = track.language;
            }
            if (track.type != null)
            {
                parameters["type"] = track.type;
            }
            request.Body = new FormUrlEncodedContent(parameters);

            return(request);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Get all thumbnails on a video
        /// </summary>
        /// <param name="clipId"></param>
        /// <returns></returns>
        public async Task <Paginated <Picture> > GetPicturesAsync(long clipId)
        {
            try
            {
                ThrowIfUnauthorized();
                IApiRequest request = ApiRequestFactory.GetApiRequest(AccessToken);
                request.Method = HttpMethod.Get;
                request.Path   = Endpoints.Pictures;
                request.UrlSegments.Add("clipId", clipId.ToString());

                var response = await request.ExecuteRequestAsync <Paginated <Picture> >();

                UpdateRateLimit(response);
                CheckStatusCodeError(response, "Error retrieving video picture.", HttpStatusCode.NotFound);

                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }

                return(response.Content);
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                throw new VimeoApiException("Error retrieving video picture.", ex);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// upload picture asynchronously
        /// </summary>
        /// <param name="fileContent">fileContent</param>
        /// <returns>upload pic </returns>
        public async Task <Picture> UploadPictureAsync(IBinaryContent fileContent, long clipId)
        {
            try
            {
                if (!fileContent.Data.CanRead)
                {
                    throw new ArgumentException("fileContent should be readable");
                }
                if (fileContent.Data.CanSeek && fileContent.Data.Position > 0)
                {
                    fileContent.Data.Position = 0;
                }
                ThrowIfUnauthorized();
                var request = ApiRequestFactory.GetApiRequest(AccessToken);
                request.Method = HttpMethod.Post;
                request.Path   = Endpoints.Pictures;
                request.UrlSegments.Add("clipId", clipId.ToString());

                request.Body = new ByteArrayContent(await fileContent.ReadAllAsync());

                var response = await request.ExecuteRequestAsync <Picture>();

                CheckStatusCodeError(null, response, "Error generating upload ticket to replace video.");

                return(response.Content);
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                throw new VimeoUploadException("Error Uploading picture.", null, ex);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Create new upload ticket asynchronously
        /// </summary>
        /// <returns>Upload ticket</returns>
        public async Task <Video> UploadPullLinkAsync(string link)
        {
            try
            {
                var param = new ParameterDictionary();
                param.Add("type", "pull");
                param.Add("link", link);

                var request = ApiRequestFactory.AuthorizedRequest(
                    AccessToken,
                    HttpMethod.Post,
                    Endpoints.UploadTicket,
                    null,
                    param
                    );

                return(await ExecuteApiRequest <Video>(request));
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                throw new VimeoUploadException("Error generating upload ticket.", null, ex);
            }
        }
        /// <summary>
        /// Upload new text track file asynchronously
        /// </summary>
        /// <param name="fileContent">File content</param>
        /// <param name="videoId">VideoId</param>
        /// <param name="track">Track</param>
        /// <returns>New text track</returns>
        public async Task <TextTrack> UploadTextTrackFileAsync(IBinaryContent fileContent, long videoId, TextTrack track)
        {
            if (!fileContent.Data.CanRead)
            {
                throw new ArgumentException("fileContent should be readable");
            }
            if (fileContent.Data.CanSeek && fileContent.Data.Position > 0)
            {
                fileContent.Data.Position = 0;
            }

            TextTrack ticket = await GetUploadTextTrackTicketAsync(videoId, track);

            IApiRequest request = ApiRequestFactory.GetApiRequest();

            request.Method = Method.PUT;
            request.ExcludeAuthorizationHeader = true;
            request.Path = ticket.link;
            request.Headers.Add(Request.HeaderContentType, fileContent.ContentType);
            request.Headers.Add(Request.HeaderContentLength, fileContent.Data.Length.ToString());
            request.BinaryContent = await fileContent.ReadAllAsync();

            IRestResponse response = await request.ExecuteRequestAsync();

            CheckStatusCodeError(null, response, "Error uploading text track file.", HttpStatusCode.BadRequest);

            return(ticket);
        }
Ejemplo n.º 10
0
        IApiRequest GenerateVideosRequest(string path)
        {
            var result = ApiRequestFactory.GetApiRequest(ClientId, ClientSecret);

            result.Method = Method.GET;
            result.Path   = path;
            return(result);
        }
Ejemplo n.º 11
0
        private IApiRequest GenerateCompleteUploadRequest(UploadTicket ticket)
        {
            IApiRequest request = ApiRequestFactory.GetApiRequest(AccessToken);

            request.Method = HttpMethod.Delete;
            request.Path   = ticket.complete_uri;
            return(request);
        }
Ejemplo n.º 12
0
        private IApiRequest GenerateUploadTicketRequest(string type = "streaming")
        {
            ThrowIfUnauthorized();

            IApiRequest request = ApiRequestFactory.GetApiRequest(AccessToken);

            request.Method = HttpMethod.Post;
            request.Path   = Endpoints.UploadTicket;
            request.Query.Add("type", type);
            return(request);
        }
Ejemplo n.º 13
0
        private IApiRequest GenerateReplaceVideoUploadTicketRequest(long clipId)
        {
            ThrowIfUnauthorized();

            var request = ApiRequestFactory.GetApiRequest(AccessToken);

            request.Method = HttpMethod.Put;
            request.Path   = Endpoints.VideoReplaceFile;
            request.UrlSegments.Add("clipId", clipId.ToString());
            request.Query.Add("type", "streaming");
            return(request);
        }
Ejemplo n.º 14
0
        private IApiRequest GenerateVideoDeleteRequest(long clipId)
        {
            ThrowIfUnauthorized();

            IApiRequest request = ApiRequestFactory.GetApiRequest(AccessToken);

            request.Method = HttpMethod.Delete;
            request.Path   = Endpoints.Video;

            request.UrlSegments.Add("clipId", clipId.ToString());

            return(request);
        }
Ejemplo n.º 15
0
        private IApiRequest GenerateVideoAllowedDomainPatchRequest(long clipId, string domain)
        {
            ThrowIfUnauthorized();

            IApiRequest request = ApiRequestFactory.GetApiRequest(AccessToken);

            request.Method = HttpMethod.Put;
            request.Path   = Endpoints.VideoAllowedDomain;

            request.UrlSegments.Add("clipId", clipId.ToString());
            request.UrlSegments.Add("domain", domain);

            return(request);
        }
        private IApiRequest GenerateDeleteTextTrackRequest(long clipId, long trackId)
        {
            ThrowIfUnauthorized();

            IApiRequest request  = ApiRequestFactory.GetApiRequest(AccessToken);
            string      endpoint = Endpoints.TextTrack;

            request.Method = Method.DELETE;
            request.Path   = endpoint;

            request.UrlSegments.Add("clipId", clipId.ToString());
            request.UrlSegments.Add("trackId", trackId.ToString());

            return(request);
        }
Ejemplo n.º 17
0
        private async Task <IApiRequest> GenerateFileStreamRequest(IBinaryContent fileContent, UploadTicket ticket,
                                                                   long written = 0, int?chunkSize = null, bool verifyOnly = false)
        {
            if (ticket == null || string.IsNullOrWhiteSpace(ticket.ticket_id))
            {
                throw new ArgumentException("Invalid upload ticket.");
            }
            if (fileContent.Data.Length > ticket.user.upload_quota.space.free)
            {
                throw new InvalidOperationException(
                          "User does not have enough free space to upload this video. Remaining space: " +
                          ticket.quota.free_space + ".");
            }

            var request = ApiRequestFactory.GetApiRequest();

            request.Method = HttpMethod.Put;
            request.ExcludeAuthorizationHeader = true;
            request.Path = ticket.upload_link_secure;

            if (verifyOnly)
            {
                var body = new ByteArrayContent(new byte[0]);
                body.Headers.Add("Content-Range", "bytes */*");
                body.Headers.ContentLength = 0;
                request.Body = body;
            }
            else
            {
                if (chunkSize.HasValue)
                {
                    var startIndex = fileContent.Data.CanSeek ? fileContent.Data.Position : written;
                    var endIndex   = Math.Min(startIndex + chunkSize.Value, fileContent.Data.Length);
                    var byteArray  = await fileContent.ReadAsync(startIndex, endIndex);

                    var body = new ByteArrayContent(byteArray, 0, byteArray.Length);
                    body.Headers.Add("Content-Range", $"bytes {startIndex}-{endIndex}/*");
                    body.Headers.ContentLength = endIndex - startIndex;
                    request.Body = body;
                }
                else
                {
                    request.Body = new ByteArrayContent(await fileContent.ReadAllAsync());
                }
            }

            return(request);
        }
        private IApiRequest GenerateTextTracksRequest(long clipId, long?trackId = null)
        {
            ThrowIfUnauthorized();

            IApiRequest request  = ApiRequestFactory.GetApiRequest(AccessToken);
            string      endpoint = trackId.HasValue ? Endpoints.TextTrack : Endpoints.TextTracks;

            request.Method = Method.GET;
            request.Path   = endpoint;

            request.UrlSegments.Add("clipId", clipId.ToString());
            if (trackId.HasValue)
            {
                request.UrlSegments.Add("trackId", trackId.ToString());
            }
            return(request);
        }
Ejemplo n.º 19
0
        private IApiRequest GenerateAlbumVideosRequest(long albumId, long?userId = null, long?clipId = null, int?page = null, int?perPage = null, string sort = null, string direction = null, string[] fields = null)
        {
            ThrowIfUnauthorized();

            IApiRequest request  = ApiRequestFactory.GetApiRequest(AccessToken);
            string      endpoint = clipId.HasValue ? Endpoints.UserAlbumVideo : Endpoints.UserAlbumVideos;

            request.Method = HttpMethod.Get;
            request.Path   = userId.HasValue ? endpoint : Endpoints.GetCurrentUserEndpoint(endpoint);

            request.UrlSegments.Add("albumId", albumId.ToString());
            if (userId.HasValue)
            {
                request.UrlSegments.Add("userId", userId.ToString());
            }
            if (clipId.HasValue)
            {
                request.UrlSegments.Add("clipId", clipId.ToString());
            }
            if (fields != null)
            {
                foreach (var field in fields)
                {
                    request.Fields.Add(field);
                }
            }
            if (page.HasValue)
            {
                request.Query.Add("page", page.ToString());
            }
            if (perPage.HasValue)
            {
                request.Query.Add("per_page", perPage.ToString());
            }
            if (!string.IsNullOrEmpty(sort))
            {
                request.Query.Add("sort", sort);
            }
            if (!string.IsNullOrEmpty(direction))
            {
                request.Query.Add("direction", direction);
            }

            return(request);
        }
Ejemplo n.º 20
0
        private async Task <IApiRequest> GenerateFileStreamRequest(IBinaryContent fileContent, UploadTicket ticket,
                                                                   long written = 0, int?chunkSize = null, bool verifyOnly = false)
        {
            if (ticket == null || string.IsNullOrWhiteSpace(ticket.ticket_id))
            {
                throw new ArgumentException("Invalid upload ticket.");
            }
            if (fileContent.Data.Length > ticket.user.upload_quota.space.free)
            {
                throw new InvalidOperationException(
                          "User does not have enough free space to upload this video. Remaining space: " +
                          ticket.quota.free_space + ".");
            }

            IApiRequest request = ApiRequestFactory.GetApiRequest();

            request.Method = Method.PUT;
            request.ExcludeAuthorizationHeader = true;
            request.Path = ticket.upload_link_secure;
            request.Headers.Add(Request.HeaderContentType, fileContent.ContentType);
            if (verifyOnly)
            {
                request.Headers.Add(Request.HeaderContentLength, "0");
                request.Headers.Add(Request.HeaderContentRange, "bytes */*");
            }
            else
            {
                if (chunkSize.HasValue)
                {
                    long startIndex = fileContent.Data.CanSeek ? fileContent.Data.Position : written;
                    long endIndex   = Math.Min(startIndex + chunkSize.Value, fileContent.Data.Length);
                    request.Headers.Add(Request.HeaderContentLength, (endIndex - startIndex).ToString());
                    request.Headers.Add(Request.HeaderContentRange,
                                        string.Format("bytes {0}-{1}/{2}", startIndex, endIndex, fileContent.Data.Length));
                    request.BinaryContent = await fileContent.ReadAsync(startIndex, endIndex);
                }
                else
                {
                    request.Headers.Add(Request.HeaderContentLength, fileContent.Data.Length.ToString());
                    request.BinaryContent = await fileContent.ReadAllAsync();
                }
            }

            return(request);
        }
Ejemplo n.º 21
0
        private IApiRequest GenerateVideoPatchRequest(long clipId, VideoUpdateMetadata metaData)
        {
            ThrowIfUnauthorized();

            var request = ApiRequestFactory.GetApiRequest(AccessToken);

            request.Method = new HttpMethod("PATCH");
            request.Path   = Endpoints.Video;

            request.UrlSegments.Add("clipId", clipId.ToString());
            var parameters = new Dictionary <string, string>();

            if (metaData.Name != null)
            {
                parameters["name"] = metaData.Name.Trim();
            }
            if (metaData.Description != null)
            {
                parameters["description"] = metaData.Description.Trim();
            }
            if (metaData.Privacy != VideoPrivacyEnum.Unknown)
            {
                parameters["privacy.view"] = metaData.Privacy.ToString().ToLower();
            }
            if (metaData.Privacy == VideoPrivacyEnum.Password)
            {
                parameters["password"] = metaData.Password;
            }
            if (metaData.EmbedPrivacy != VideoEmbedPrivacyEnum.Unknown)
            {
                parameters["privacy.embed"] = metaData.EmbedPrivacy.ToString().ToLower();
            }
            if (metaData.Comments != VideoCommentsEnum.Unknown)
            {
                parameters["privacy.comments"] = metaData.Comments.ToString().ToLower();
            }
            parameters["review_link"]      = metaData.ReviewLinkEnabled.ToString().ToLower();
            parameters["privacy.download"] = metaData.AllowDownloadVideo ? "true" : "false";
            parameters["privacy.add"]      = metaData.AllowAddToAlbumChannelGroup ? "true" : "false";
            request.Body = new FormUrlEncodedContent(parameters);

            return(request);
        }
Ejemplo n.º 22
0
        private IApiRequest GenerateVideoPatchRequest(long clipId, VideoUpdateMetadata metaData)
        {
            ThrowIfUnauthorized();

            IApiRequest request = ApiRequestFactory.GetApiRequest(AccessToken);

            request.Method = Method.PATCH;
            request.Path   = Endpoints.Video;

            request.UrlSegments.Add("clipId", clipId.ToString());
            if (metaData.Name != null)
            {
                request.Query.Add("name", metaData.Name.Trim());
            }
            if (metaData.Description != null)
            {
                request.Query.Add("description", metaData.Description.Trim());
            }
            if (metaData.Privacy != VideoPrivacyEnum.Unknown)
            {
                request.Query.Add("privacy.view", metaData.Privacy.ToString().ToLower());
            }
            if (metaData.Privacy == VideoPrivacyEnum.Password)
            {
                request.Query.Add("password", metaData.Password);
            }
            if (metaData.EmbedPrivacy != VideoEmbedPrivacyEnum.Unknown)
            {
                request.Query.Add("privacy.embed", metaData.EmbedPrivacy.ToString().ToLower());
            }
            if (metaData.Comments != VideoCommentsEnum.Unknown)
            {
                request.Query.Add("privacy.comments", metaData.Comments.ToString().ToLower());
            }
            request.Query.Add("review_link", metaData.ReviewLinkEnabled.ToString().ToLower());
            request.Query.Add("privacy.download", metaData.AllowDownloadVideo ? "true" : "false");
            request.Query.Add("privacy.add", metaData.AllowAddToAlbumChannelGroup ? "true" : "false");

            return(request);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// set thumbnail picture asynchronously
        /// </summary>
        /// <param name="link">link</param>
        /// <returns>Set thumbnail pic </returns>
        public async Task SetThumbnailActiveAsync(string link)
        {
            try
            {
                ThrowIfUnauthorized();
                IApiRequest request = ApiRequestFactory.GetApiRequest(AccessToken);
                request.Method = new HttpMethod("PATCH");
                request.Path   = link;
                request.Query.Add("active", "true");

                var response = await request.ExecuteRequestAsync();

                CheckStatusCodeError(null, response, "Error Setting thumbnail image active.");
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                throw new VimeoUploadException("Error Setting thumbnail image active.", null, ex);
            }
        }
        /// <summary>
        /// upload picture asynchronously
        /// </summary>
        /// <param name="fileContent">fileContent</param>
        /// <param name="link">link</param>
        /// <returns>upload pic </returns>
        public async Task UploadPictureAsync(IBinaryContent fileContent, string link)
        {
            try
            {
                if (!fileContent.Data.CanRead)
                {
                    throw new ArgumentException("fileContent should be readable");
                }
                if (fileContent.Data.CanSeek && fileContent.Data.Position > 0)
                {
                    fileContent.Data.Position = 0;
                }
                ThrowIfUnauthorized();
                var request = ApiRequestFactory.GetApiRequest(AccessToken);
                request.Method = HttpMethod.Put;
                request.Path   = link;
                //request.Header.Add(Request.HeaderContentType, "image/jpeg");
                //request.Headers.Add(Request.HeaderContentLength, fileContent.Data.Length.ToString());

                request.Body = new ByteArrayContent(await fileContent.ReadAllAsync());

                var response = await request.ExecuteRequestAsync();

                CheckStatusCodeError(null, response, "Error generating upload ticket to replace video.");

                //return response.Data;
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                throw new VimeoUploadException("Error Uploading picture.", null, ex);
            }
        }