public IActionResult CreateShortUrl([FromBody] string requestJson) { try{ UrlRequest request = JsonConvert.DeserializeObject <UrlRequest>(requestJson); string longUrl = request.LongUrl; if (!longUrl.Contains("http", StringComparison.OrdinalIgnoreCase)) { longUrl = "http://" + longUrl; } if (!UrlUtils.IsUrlValid(longUrl)) { return(BadRequest()); } longUrl = UrlUtils.GetIdn(longUrl); string shortUrl = urlService.MapToShort(longUrl); UrlResponse urlResponse = new UrlResponse() { LongUrl = longUrl, ShortUrl = shortUrl }; urlService.SaveUrlMap(urlResponse); urlResponse.ShortUrl = "http://localhost:5000/" + shortUrl; return(Ok(urlResponse)); } catch (Exception e) { Console.WriteLine("invalid format for request. the error message is {0}", e.Message); return(BadRequest()); } }
public UrlResource GenerateShortUrl(UrlRequest urlRequest) { if (Validator.UrlValidator(urlRequest.Url)) { string shortUrl; Task <bool> check; do { shortUrl = RandomStringGenerator.GeneratRandomString(8); check = dbContext.UrlResources.AnyAsync(foo => foo.ShortenUrl == shortUrl); check.Wait(); } while(check.Result); UrlResource resource = new UrlResource { ShortenUrl = shortUrl, Url = urlRequest.Url }; dbContext.UrlResources.Add(resource); dbContext.SaveChanges(); return(resource); } else { return(null); } }
public Response Get(UrlRequest request) { using (DbConnection connection = _factory.CreateConnection()) { connection.ConnectionString = _connectionString; connection.Open(); DbCommand cmd = connection.CreateCommand(); cmd.CommandText = "select [Value] from EmbedlyCache where [Key] = @key"; DbParameter pKey = cmd.CreateParameter(); pKey.DbType = DbType.Guid; pKey.Direction = ParameterDirection.Input; pKey.ParameterName = "key"; pKey.Value = request.CacheKey; cmd.Parameters.Add(pKey); var value = (string)cmd.ExecuteScalar(); if (value == null) return null; byte[] bytes = Encoding.Default.GetBytes(value); using (var ms = new MemoryStream(bytes)) { var serializer = new DataContractJsonSerializer(typeof (Response)); var response = (Response)serializer.ReadObject(ms); return response; } } }
private static string Deal_POST_Request(string Request_URL, string Encode) { string Return_String = string.Empty; switch (Encode) { case "UTF-8": Return_String = UrlRequest.HttpPost(Request_URL, "", Encoding.UTF8); break; case "Unicode": Return_String = UrlRequest.HttpPost(Request_URL, "", Encoding.Unicode); break; case "BigEndianUnicode": Return_String = UrlRequest.HttpPost(Request_URL, "", Encoding.BigEndianUnicode); break; case "ASCII": Return_String = UrlRequest.HttpPost(Request_URL, "", Encoding.ASCII); break; } return(Return_String); }
/// <summary> /// Gets the cached response for the specified key. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> public Response Get(UrlRequest request) { MemoryCache cache = MemoryCache.Default; var response = (Response)cache.Get(request.CacheKey.ToString()); return(response); }
public async Task <string> GetTextListWithUrl(UrlRequest request) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", APIKeys.OCRAPIKey); var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"); var response = await client.PostAsync(EndPoints.OCRAPI, content); var result = await response.Content.ReadAsStringAsync(); var result2 = JsonConvert.DeserializeObject <OCRAPIResponse>(result); StringBuilder stringBuilder = new StringBuilder(); if (result != null && result2.regions != null) { foreach (var item in result2.regions) { foreach (var line in item.lines) { foreach (var word in line.words) { stringBuilder.Append(word.text); stringBuilder.Append(" "); } stringBuilder.AppendLine(); } stringBuilder.AppendLine(); } } return(stringBuilder.ToString()); } }
public object ShortenUrl(UrlRequest request) { if (String.IsNullOrEmpty(request.Url)) { throw new ArgumentNullException(request.Url); } Uri uri; if (Uri.TryCreate(request.Url, UriKind.Absolute, out uri) == false) { throw new ArgumentNullException(request.Url); } if (uri.AbsoluteUri.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) == false && uri.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) == false && uri.AbsoluteUri.StartsWith("ftp", StringComparison.InvariantCultureIgnoreCase) == false) { throw new ArgumentException(request.Url); } Url entity = new Url(); entity.Href = uri.AbsoluteUri; iAFWebHost.Entities.Url dbEntity = Mapper.MapResponse(entity); UrlService service = new UrlService(); iAFWebHost.Entities.Url dbResponse = service.ShortenUrl(dbEntity); entity = Mapper.MapResponse(dbResponse); return(entity); }
public async Task CanMakeUrlRequest() { var taskCompletionSource = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously); IUrlRequest urlRequest = null; int statusCode = -1; //Can be created on any valid CEF Thread, here we'll use the CEF UI Thread await Cef.UIThreadTaskFactory.StartNew(delegate { var requestClient = new UrlRequestClient((IUrlRequest req, byte[] responseBody) => { statusCode = req.Response.StatusCode; taskCompletionSource.TrySetResult(Encoding.UTF8.GetString(responseBody)); }); var request = new Request(); request.Method = "GET"; request.Url = "https://code.jquery.com/jquery-3.4.1.min.js"; //Global RequestContext will be used urlRequest = new UrlRequest(request, requestClient); }); var stringResult = await taskCompletionSource.Task; Assert.True(!string.IsNullOrEmpty(stringResult)); Assert.Equal(200, statusCode); }
public async Task <GetInfoResult> GetInfoAsync(UrlRequest request) { return(await BaseInvokeCheckModelAsync(request, async() => { IUrlInfo urlInfo = await _videoInfoGetter.GetInfoAsync(request.Url); var responseBuilder = ResponseBuilder <GetInfoResult> .Fail(); //urlInfo can't be null if (urlInfo == null) { throw new ArgumentNullException(nameof(urlInfo)); } if (urlInfo.ContentLength > _videoRestrictsOptions.Value.AllowedSize) { return ResponseBuilder <GetInfoResult> .Fail().SetInfoAndBuild("Maximim video size is 25 MB"); } if (_dbContext.Audios.Any(x => x.UniqueIdentifier == urlInfo.VideoId)) { return responseBuilder.SetInfoAndBuild("Video already uploaded"); } return ResponseBuilder <GetInfoResult> .SuccessBuild(new GetInfoResult { UrlInfo = urlInfo }); })); }
public Response Get(UrlRequest request) { using (DbConnection connection = _factory.CreateConnection()) { connection.ConnectionString = _connectionString; connection.Open(); DbCommand cmd = connection.CreateCommand(); cmd.CommandText = "select [Value] from EmbedlyCache where [Key] = @key"; DbParameter pKey = cmd.CreateParameter(); pKey.DbType = DbType.Guid; pKey.Direction = ParameterDirection.Input; pKey.ParameterName = "key"; pKey.Value = request.CacheKey; cmd.Parameters.Add(pKey); var value = (string)cmd.ExecuteScalar(); if (value == null) { return(null); } byte[] bytes = Encoding.Default.GetBytes(value); using (var ms = new MemoryStream(bytes)) { var serializer = new DataContractJsonSerializer(typeof(Response)); var response = (Response)serializer.ReadObject(ms); return(response); } } }
public void IsValidUrl(string url) { SqlLiteDatabaseTest(options => { var uploadService = _server.Host.Services.GetService(typeof(IUploadService)) as IUploadService; using (var context = new PlayCatDbContext(options)) { uploadService.SetDbContext(context); var request = new UrlRequest() { Url = url, }; GetInfoResult result = uploadService.GetInfo(request); CheckIfSuccess(result); Assert.NotNull(result.UrlInfo); Assert.Equal("Flume", result.UrlInfo.Artist); Assert.Equal("Say It (feat. Tove Lo) (Illenium Remix)", result.UrlInfo.Song); Assert.Equal(8023661, result.UrlInfo.ContentLength); } }); }
public ActionResult <string> Post([FromBody] UrlRequest urlRequest) { string longUrl; if (!(urlRequest.LongUrl.StartsWith("http://") || urlRequest.LongUrl.StartsWith("https://") || urlRequest.LongUrl.StartsWith("ftp://") || urlRequest.LongUrl.StartsWith("file://"))) { longUrl = "http://" + urlRequest.LongUrl; } else { longUrl = urlRequest.LongUrl; } Console.WriteLine("im here!"); if (UrlValidator.validator(longUrl)) { UrlRequest request = new UrlRequest() { LongUrl = longUrl }; UrlResorce shortUrl = urlMapper.setShortUrl(request); return(Ok(shortUrl)); } else { return(BadRequest()); } }
public async Task <IHttpActionResult> AddLongUrl(UrlRequest longUrl) { var url = await _constructInput.ConstructUrl(longUrl.Url); var result = await _validateUrl.CheckWebsite(url); if (result) { var urlSearch = await _urlStorage.GetItem(url); if (urlSearch == null) { var shortUrlCode = _convertUrl.GetShorterUrl(url); var container = new UrlContainer { LongUrl = url, ShortUrl = shortUrlCode }; await _urlStorage.AddItem(container); return(Ok(container.ShortUrl)); } return(Ok(urlSearch.ShortUrl)); } return(BadRequest()); }
public IActionResult DetermineFileTypeFromUrl([FromBody] UrlRequest request) { try { Logger.LogInformation("{0} method invoked", nameof(DetermineFileTypeFromUrl)); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!TryGetFile(request.InputGetUrl, out var file)) { return(BadRequest("Input file could not be downloaded.")); } RecordEngineVersion(); var fileType = DetectFromBytes(file); return(Ok(fileType)); } catch (Exception e) { Logger.LogError(e, $"Exception occured processing file: {e.Message}"); throw; } }
// Use this for initialization private void Start() { UrlLoader loader = new UrlLoader(); UrlRequest request = new UrlRequest("http://docs.unity3d.com/ScriptReference/index.html", OnComplete, OnError); //UrlRequest request = new UrlRequest("http://docs.unity3d.com/xxx", OnComplete, OnError); loader.Load(request); }
private static string Deal_Get_Request(string Request_URL) { string Return_String = string.Empty; Return_String = UrlRequest.HttpGet(Request_URL); return(Return_String); }
public object ExpandUrl(UrlRequest request) { if (!request.ShortId.IsShortCode()) throw new ArgumentNullException(request.ShortId); UrlService service = new UrlService(); var dbResponse = service.ExpandUrl(request.ShortId); return Mapper.MapResponse(dbResponse); }
public async Task <ActionResult <UrlAssociationData> > AddUrlRequestAsync([FromBody] UrlRequest url) { if (string.IsNullOrWhiteSpace(url.Address)) { return(BadRequest("Valid url is required")); } return(await _associationService.AddUrlAsync(url)); }
public async Task <IActionResult> UpdateSucecessUrl(string id, [FromBody] UrlRequest url) { var result = await UpdateUrl(id, url.Url, UrlType.Success); if (result) { return(Ok()); } return(StatusCode(500)); }
/// <summary> /// Caches the response for the specified key. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> public void Put(UrlRequest request, Response response) { MemoryCache cache = MemoryCache.Default; var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.Add(_expiration) // SlidingExpiration = _expiration }; cache.Add(request.CacheKey.ToString(), response, policy); }
public object Any(UrlRequest request) { if (!String.IsNullOrEmpty(request.Url)) return ShortenUrl(request); if (request.ShortId.IsShortCode()) return ExpandUrl(request); return new ArgumentNullException(); }
public async Task <IActionResult> UpdateErrorUrl(string id, [FromBody] UrlRequest url) { var result = await UpdateOrderUrl(id, url.Url, UrlType.Error); if (result) { return(Ok()); } return(StatusCode(500)); }
public async Task <IHttpActionResult> GetLongUrl(UrlRequest url) { var urlSearch = await _urlStorage.GetItem(url.Url); if (urlSearch != null) { return(Ok(urlSearch.LongUrl)); } return(NotFound()); }
/// <summary> /// Caches the response for the specified key. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> public void Put(UrlRequest request, Response response) { MemoryCache cache = MemoryCache.Default; var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.Add(_expiration) // SlidingExpiration = _expiration }; cache.Add(request.CacheKey.ToString(), response, policy); }
public async Task <GetInfoResult> GetUrlInfoAsync([FromBody] UrlRequest request) { CheckTokenResult checkTokenResult = _authService.CheckToken(AccessToken); if (!checkTokenResult.Ok) { return(new GetInfoResult(checkTokenResult)); } return(await _uploadService.GetInfoAsync(request)); }
public GetInfoResult GetUrlInfo([FromBody] UrlRequest request) { CheckTokenResult checkTokenResult = _authService.CheckToken(AccessToken); if (!checkTokenResult.Ok) { return(new GetInfoResult(checkTokenResult)); } return(_uploadService.GetInfo(request)); }
public object ExpandUrl(UrlRequest request) { if (!request.ShortId.IsShortCode()) { throw new ArgumentNullException(request.ShortId); } UrlService service = new UrlService(); var dbResponse = service.ExpandUrl(request.ShortId); return(Mapper.MapResponse(dbResponse)); }
public async Task CheckBadShortening() { var request = new UrlRequest() { LongUrl = "https://www" }; var stringContent = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"); var response = await client.PostAsync("/urls", stringContent); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }
public async Task <IActionResult> CountWords([FromBody] UrlRequest urlRequest) { var bounce = await _countWordsBouncer.Bounce(urlRequest); if (!bounce.IsSuccessful) { return(BadRequest(bounce.Message)); } var result = await _mediator.Send(new WordCounterCommand { Url = urlRequest.url }); return(Ok(result)); }
public void Put(UrlRequest request, Response value) { string valueString; using (var ms = new MemoryStream()) { var serializer = new DataContractJsonSerializer(typeof(Response)); serializer.WriteObject(ms, value); ms.Position = 0; valueString = Encoding.Default.GetString(ms.ToArray()); } using (DbConnection connection = _factory.CreateConnection()) { connection.ConnectionString = _connectionString; connection.Open(); DbCommand cmd = connection.CreateCommand(); cmd.CommandText = "insert into EmbedlyCache ([Key], [Url], [CachedOn], [Value]) values (@key, @url, @cachedOn, @value)"; DbParameter pKey = cmd.CreateParameter(); pKey.DbType = DbType.Guid; pKey.Direction = ParameterDirection.Input; pKey.ParameterName = "key"; pKey.Value = request.CacheKey; DbParameter pUrl = cmd.CreateParameter(); pUrl.DbType = DbType.AnsiString; pUrl.Direction = ParameterDirection.Input; pUrl.ParameterName = "url"; pUrl.Value = request.Url.AbsoluteUri; DbParameter pCachedOn = cmd.CreateParameter(); pCachedOn.DbType = DbType.DateTime; pCachedOn.Direction = ParameterDirection.Input; pCachedOn.ParameterName = "cachedOn"; pCachedOn.Value = DateTime.UtcNow; DbParameter pValue = cmd.CreateParameter(); pValue.DbType = DbType.String; pValue.Direction = ParameterDirection.Input; pValue.ParameterName = "value"; pValue.Value = valueString; cmd.Parameters.Add(pKey); cmd.Parameters.Add(pUrl); cmd.Parameters.Add(pCachedOn); cmd.Parameters.Add(pValue); cmd.ExecuteNonQuery(); } }
public Url Expand(string shortId) { if (shortId.IsShortCode()) { UrlRequest request = new UrlRequest(); request.ShortId = shortId; return(Instance.Get(request)); } else { throw new ArgumentException("Error: Unable to parse shortId parameter"); } }
public Url Expand(string shortId) { if (shortId.IsShortCode()) { UrlRequest request = new UrlRequest(); request.ShortId = shortId; return Instance.Get(request); } else { throw new ArgumentException("Error: Unable to parse shortId parameter"); } }
public void Put(UrlRequest request, Response value) { string valueString; using (var ms = new MemoryStream()) { var serializer = new DataContractJsonSerializer(typeof (Response)); serializer.WriteObject(ms, value); ms.Position = 0; valueString = Encoding.Default.GetString(ms.ToArray()); } using (DbConnection connection = _factory.CreateConnection()) { connection.ConnectionString = _connectionString; connection.Open(); DbCommand cmd = connection.CreateCommand(); cmd.CommandText = "insert into EmbedlyCache ([Key], [Url], [CachedOn], [Value]) values (@key, @url, @cachedOn, @value)"; DbParameter pKey = cmd.CreateParameter(); pKey.DbType = DbType.Guid; pKey.Direction = ParameterDirection.Input; pKey.ParameterName = "key"; pKey.Value = request.CacheKey; DbParameter pUrl = cmd.CreateParameter(); pUrl.DbType = DbType.AnsiString; pUrl.Direction = ParameterDirection.Input; pUrl.ParameterName = "url"; pUrl.Value = request.Url.AbsoluteUri; DbParameter pCachedOn = cmd.CreateParameter(); pCachedOn.DbType = DbType.DateTime; pCachedOn.Direction = ParameterDirection.Input; pCachedOn.ParameterName = "cachedOn"; pCachedOn.Value = DateTime.UtcNow; DbParameter pValue = cmd.CreateParameter(); pValue.DbType = DbType.String; pValue.Direction = ParameterDirection.Input; pValue.ParameterName = "value"; pValue.Value = valueString; cmd.Parameters.Add(pKey); cmd.Parameters.Add(pUrl); cmd.Parameters.Add(pCachedOn); cmd.Parameters.Add(pValue); cmd.ExecuteNonQuery(); } }
public object Any(UrlRequest request) { if (!String.IsNullOrEmpty(request.Url)) { return(ShortenUrl(request)); } if (request.ShortId.IsShortCode()) { return(ExpandUrl(request)); } return(new ArgumentNullException()); }
public Url Shorten(string uri) { UrlRequest request = new UrlRequest(); Uri validUri = null; if (!String.IsNullOrEmpty(uri) && Uri.TryCreate(uri, UriKind.Absolute, out validUri)) { request.Url = uri; return Instance.Get(request); } else { throw new ArgumentException("Error: Unable to parse uri parameter"); } }
public void ShouldFailOnAlreadyUpload() { SqlLiteDatabaseTest(options => { var uploadService = _server.Host.Services.GetService(typeof(IUploadService)) as IUploadService; var fileResolver = _server.Host.Services.GetService(typeof(IFileResolver)) as IFileResolver; using (var context = new PlayCatDbContext(options)) { uploadService.SetDbContext(context); string youtubeUrl = "https://www.youtube.com/watch?v=yPYZpwSpKmA"; var request = new UrlRequest() { Url = youtubeUrl, }; GetInfoResult result = uploadService.GetInfo(request); CheckIfSuccess(result); Guid userId = GetUserId(context); context.CreatePlaylist(true, userId, null, 0); context.SaveChanges(); Assert.NotNull(result.UrlInfo); Assert.Equal("Rick Astley", result.UrlInfo.Artist); Assert.Equal("Together Forever", result.UrlInfo.Song); var uploadResult = uploadService.UploadAudioAsync(userId, new UploadAudioRequest() { Artist = "Rick Astley", Song = "Together Forever", Url = youtubeUrl, }).Result; CheckIfSuccess(uploadResult); string audioFilePath = fileResolver.GetAudioFolderPath(StorageType.FileSystem); File.Delete(Path.Combine(audioFilePath, "yPYZpwSpKmA.mp3")); GetInfoResult checkAgainResult = uploadService.GetInfo(request); CheckIfFail(checkAgainResult); Assert.Equal("Video already uploaded", checkAgainResult.Info); } }); }
public async Task <IActionResult> AnalyzeFromUrl([FromBody] UrlRequest req) { var features = new List <VisualFeatureTypes>(); features.Add(VisualFeatureTypes.Faces); var output = await FaceAnalysisService.AnalyzeFaces(req.url, features); if (output.IsError) { return(BadRequest()); } return(Ok(output.Value)); }
public object ShortenUrl(UrlRequest request) { if (String.IsNullOrEmpty(request.Url)) throw new ArgumentNullException(request.Url); Uri uri; if (Uri.TryCreate(request.Url, UriKind.Absolute, out uri) == false) throw new ArgumentNullException(request.Url); if (uri.AbsoluteUri.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) == false && uri.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) == false && uri.AbsoluteUri.StartsWith("ftp", StringComparison.InvariantCultureIgnoreCase) == false) throw new ArgumentException(request.Url); Url entity = new Url(); entity.Href = uri.AbsoluteUri; iAFWebHost.Entities.Url dbEntity = Mapper.MapResponse(entity); UrlService service = new UrlService(); iAFWebHost.Entities.Url dbResponse = service.ShortenUrl(dbEntity); entity = Mapper.MapResponse(dbResponse); return entity; }
/// <summary> /// Initializes a new instance of the <see cref="Result"/> class. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> public Result(UrlRequest request, Response response) { Request = request; Response = response; }
public Response Get(UrlRequest request) { MongoCacheItem cacheItem = _collection.FindOneById(request.CacheKey); return cacheItem == null ? null : cacheItem.Response; }
/// <summary> /// Gets the cached response for the specified key. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> public Response Get(UrlRequest request) { MemoryCache cache = MemoryCache.Default; var response = (Response)cache.Get(request.CacheKey.ToString()); return response; }
public Response Get(UrlRequest request) { return null; }
/// <summary> /// Initializes a new instance of the <see cref="Result"/> class. /// </summary> /// <param name="request">The request.</param> /// <param name="exception">The exception.</param> public Result(UrlRequest request, Exception exception) { Request = request; Exception = exception; }
public void Put(UrlRequest request, Response response) { // no-op }
public void Put(UrlRequest request, Response response) { var cacheItem = new MongoCacheItem(request.CacheKey, request.Url, response); _collection.Insert(cacheItem); }