private async Task SendBinaryContent(ApiObjectDescriptor sourceDescriptor, ApiObjectDescriptor newAdvertisement) { foreach (var element in sourceDescriptor.Elements) { if (IsBinaryAdvertisementElementType(element.Type)) { var value = element.Value as IBinaryElementValue ?? throw new InvalidOperationException($"Cannot cast advertisement {sourceDescriptor.Id} binary element {element.TemplateCode} value"); if (string.IsNullOrEmpty(value.Raw)) { continue; } var fileData = await SourceRestClient.DownloadFileAsync(sourceDescriptor.Id, value.DownloadUri); var matchedElement = newAdvertisement.Elements.First(e => e.TemplateCode == element.TemplateCode); EnsureUploadUrlIsValid(sourceDescriptor.Id, matchedElement); var res = await DestRestClient.UploadFileAsync(sourceDescriptor.Id, new Uri(matchedElement.UploadUrl), value.Filename, fileData); Interlocked.Increment(ref _uploadedBinariesCount); element.Value = res; } } }
public async Task <ApiObjectDescriptor> UpdateAdvertisementAsync(ApiObjectDescriptor advertisement) { var server = string.Empty; var requestId = string.Empty; var stringResponse = string.Empty; var advertisementId = advertisement.Id.ToString(); var methodUri = new Uri(_amUri, advertisementId); try { using (var content = new StringContent(JsonConvert.SerializeObject(advertisement, ApiSerializerSettings.Default), Encoding.UTF8, ContentType.Json)) { using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), methodUri)) { request.Content = content; using (var response = await _authorizedHttpClient.SendAsync(request)) { (stringResponse, server, requestId) = await HandleResponse(response); response.EnsureSuccessStatusCode(); var descriptor = JsonConvert.DeserializeObject <ApiObjectDescriptor>(stringResponse, ApiSerializerSettings.Default); if (descriptor == null) { throw new SerializationException("Cannot deserialize object descriptor " + advertisementId + ": " + stringResponse); } _logger.LogInformation( "Updated advertisement {id} got new version: {version} (old version {oldVersion})", advertisementId, descriptor.VersionId, advertisement.VersionId); return(descriptor); } } } } catch (HttpRequestException ex) { _logger.LogError( ex, "Request {requestId} to server {server} error while updating advertisement {id} with response: {response}", requestId, server, advertisementId, stringResponse); throw; } catch (Exception ex) { _logger.LogError(ex, "Advertisement {id} update error", advertisementId); throw; } }
public async Task <string> CreateAdvertisementAsync(long id, long firmId, ApiObjectDescriptor advertisement) { var amId = id.ToString(); var methodUri = new Uri(_amUri, amId + "?firm=" + firmId.ToString()); var server = string.Empty; var requestId = string.Empty; var stringResponse = string.Empty; try { using (var content = new StringContent(JsonConvert.SerializeObject(advertisement, ApiSerializerSettings.Default), Encoding.UTF8, "application/json")) { using (var response = await _authorizedHttpClient.PutAsync(methodUri, content)) { (stringResponse, server, requestId) = await HandleResponse(response); if (response.StatusCode == HttpStatusCode.Conflict) { throw new ObjectAlreadyExistsException(id); } response.EnsureSuccessStatusCode(); var res = JsonConvert.DeserializeObject <ApiVersionedDescriptor>(stringResponse, SerializerSettings.Default); if (res == null) { throw new SerializationException("Cannot deserialize response: " + stringResponse); } _logger.LogInformation("Created advertisement {id} got version: {version}", amId, res.VersionId); return(res.VersionId); } } } catch (HttpRequestException ex) { _logger.LogError(new EventId(), ex, "Request {requestId} to server {server} error while advertisement {id} creating with response: {response}", requestId, server, amId, stringResponse); throw; } catch (Exception ex) { _logger.LogError(new EventId(), ex, "Advertisement {id} creating error with response: {response}", amId, stringResponse); throw; } }
private async Task SendBinaryContent(ApiObjectDescriptor sourceDescriptor, ApiObjectDescriptor newAdvertisement) { var binaryElements = sourceDescriptor.Elements.Where(e => IsBinaryAdvertisementElementType(e.Type)); foreach (var element in binaryElements) { var value = element.Value as IBinaryElementValue ?? throw new InvalidOperationException($"Cannot cast advertisement {sourceDescriptor.Id} binary element {element.TemplateCode} value"); if (string.IsNullOrEmpty(value.Raw)) { continue; } var fileData = await SourceRestClient.DownloadFileAsync(sourceDescriptor.Id, value.DownloadUri); var matchedElement = newAdvertisement.Elements.First(e => e.TemplateCode == element.TemplateCode); EnsureUploadUrlIsValid(sourceDescriptor.Id, matchedElement); var uploadResponse = await DestRestClient.UploadFileAsync( sourceDescriptor.Id, new Uri(matchedElement.UploadUrl), value.Filename, fileData); Interlocked.Increment(ref _uploadedBinariesCount); if (element.Type == ElementDescriptorType.CompositeBitmapImage) { var compositeBitmapImageElementValue = element.Value as ICompositeBitmapImageElementValue ?? throw new InvalidOperationException($"Cannot cast advertisement {sourceDescriptor.Id} composite image element {element.TemplateCode} value"); var sizeSpecificImagesUploadTasks = compositeBitmapImageElementValue .SizeSpecificImages .Select(async image => { var imageFileData = await SourceRestClient.DownloadFileAsync(sourceDescriptor.Id, image.DownloadUri); var headers = new[] { new NameValueHeaderValue(HeaderNames.AmsFileType, FileType.SizeSpecificBitmapImage.ToString()), new NameValueHeaderValue(HeaderNames.AmsImageSize, image.Size.ToString()) }; var imageUploadResponse = await DestRestClient.UploadFileAsync( sourceDescriptor.Id, new Uri(matchedElement.UploadUrl), image.Filename, imageFileData, headers); Interlocked.Increment(ref _uploadedBinariesCount); return(new SizeSpecificImage { Size = image.Size, Raw = imageUploadResponse.Raw }); }) .ToList(); element.Value = new CompositeBitmapImageElementValue { Raw = uploadResponse.Raw, CropArea = compositeBitmapImageElementValue.CropArea, SizeSpecificImages = await Task.WhenAll(sizeSpecificImagesUploadTasks) }; } else { element.Value = uploadResponse; } } }
private async Task CloneAdvertisementAsync(ApiListAdvertisement advertisement, bool fetchAdvertisementBeforeCloning) { ApiObjectDescriptor destDescriptor = null; var objectId = advertisement.Id.ToString(); if (fetchAdvertisementBeforeCloning) { destDescriptor = await DestRestClient.GetAdvertisementAsync(advertisement.Id); _logger.LogInformation("Object {id} has been fetched from destination preliminarily with version {versionId}", objectId, destDescriptor.VersionId); } var versionId = destDescriptor?.VersionId; var sourceDescriptor = await SourceRestClient.GetAdvertisementAsync(advertisement.Id); if (destDescriptor == null) { if (sourceDescriptor.Elements.Any(e => IsBinaryAdvertisementElementType(e.Type))) { var newAm = await DestRestClient.CreateAdvertisementPrototypeAsync(advertisement.Template.Id, advertisement.Language.ToString(), advertisement.Firm.Id); await SendBinaryContent(sourceDescriptor, newAm); } try { sourceDescriptor.TemplateVersionId = _destTemplates[sourceDescriptor.TemplateId].VersionId; versionId = await DestRestClient.CreateAdvertisementAsync(advertisement.Id, advertisement.Firm.Id, sourceDescriptor); } catch (ObjectAlreadyExistsException ex) { _logger.LogWarning(new EventId(), ex, "Object {id} already exists in destination, try to continue execution", objectId); } } if (advertisement.IsWhiteListed) { await DestRestClient.SelectAdvertisementToWhitelistAsync(objectId); Interlocked.Increment(ref _selectedToWhitelistCount); } if (sourceDescriptor.Moderation != null && sourceDescriptor.Moderation.Status != ModerationStatus.OnApproval && sourceDescriptor.Moderation.Status != ModerationStatus.NominallyApproved) { if (string.IsNullOrEmpty(versionId)) { _logger.LogWarning("VersionId for object {id} is unknown, need to get latest version", objectId); versionId = (await DestRestClient.GetAdvertisementAsync(advertisement.Id)).VersionId; } await DestRestClient.UpdateAdvertisementModerationStatusAsync(objectId, versionId, sourceDescriptor.Moderation); } switch (sourceDescriptor.Moderation?.Status) { case null: break; case ModerationStatus.Approved: Interlocked.Increment(ref _approvedCount); break; case ModerationStatus.Rejected: Interlocked.Increment(ref _rejectedCount); break; case ModerationStatus.OnApproval: Interlocked.Increment(ref _draftedCount); break; case ModerationStatus.NominallyApproved: Interlocked.Increment(ref _nominallyApprovedCount); break; default: throw new ArgumentOutOfRangeException(nameof(sourceDescriptor.Moderation), sourceDescriptor.Moderation.Status, "Unsupported moderation status"); } }