Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Feature to extract Deviations from DeviantArt, so that in professional mode, use can pick from images, that are in an compressed archive #203

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions FoliCon/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry)
containerRegistry.RegisterDialog<CustomIconControl, CustomIconControlViewModel>("CustomIcon");
containerRegistry.RegisterDialog<PosterIconConfig, PosterIconConfigViewModel>("PosterIconConfig");
containerRegistry.RegisterDialog<SubfolderProcessing, SubfolderProcessingViewModel>("SubfolderProcessingConfig");
containerRegistry.RegisterDialog<ManualExplorer, ManualExplorerViewModel>("ManualExplorer");
containerRegistry.RegisterDialog<AboutBox, AboutBoxViewModel>("AboutBox");
containerRegistry.RegisterDialog<PosterPicker, PosterPickerViewModel>("PosterPicker");
containerRegistry.RegisterDialog<Previewer, PreviewerViewModel>("Previewer");
Expand Down
1 change: 1 addition & 0 deletions FoliCon/FoliCon.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ dineshsolanki.github.io/folicon/</Description>
<PackageReference Include="Prism.DryIoc" Version="8.1.97" />
<PackageReference Include="Sentry" Version="4.8.1" />
<PackageReference Include="Sentry.NLog" Version="4.8.1" />
<PackageReference Include="SharpCompress" Version="0.37.2" />
<PackageReference Include="TMDbLib" Version="2.2.0" />
<PackageReference Include="Vanara.PInvoke.Shell32" Version="4.0.2" />
<PackageReference Include="WinCopies.IconLib" Version="0.75.0-rc" />
Expand Down
27 changes: 27 additions & 0 deletions FoliCon/Models/Api/DArtDownloadResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace FoliCon.Models.Api;

public record DArtDownloadResponse
{
[JsonProperty("src")]
public string Src { get; init; }

[JsonProperty("filename")]
public string Filename { get; init; }

[JsonProperty("width")]
public int Width { get; init; }

[JsonProperty("height")]
public int Height { get; init; }

[JsonProperty("filesize")]
public int FileSizeBytes { get; init; }

[JsonIgnore]
public string LocalDownloadPath { get; set; }

public string GetFileSizeHumanReadable()
{
return ConvertHelper.ToFileSize(FileSizeBytes);
}
}
7 changes: 7 additions & 0 deletions FoliCon/Models/Data/DArtImageList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,20 @@ public class DArtImageList : BindableBase
{
private string _url;
private BitmapSource _image;
private string _deviationId;

public DArtImageList(string url, BitmapSource bmp)
{
Url = url ?? throw new ArgumentNullException(nameof(url));
Image = bmp ?? throw new ArgumentNullException(nameof(bmp));
}

public DArtImageList(string url, BitmapSource bmp, string deviationId) : this(url, bmp)
{
DeviationId = deviationId ?? throw new ArgumentNullException(nameof(deviationId));
}

public string Url { get => _url; set => SetProperty(ref _url, value); }
public BitmapSource Image { get => _image; set => SetProperty(ref _image, value); }
public string DeviationId { get => _deviationId; set => SetProperty(ref _deviationId, value); }
}
65 changes: 61 additions & 4 deletions FoliCon/Modules/DeviantArt/DArt.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using FoliCon.Models.Api;
using FoliCon.Modules.Configuration;
using FoliCon.Modules.Extension;
using FoliCon.Modules.utils;
using Microsoft.Extensions.Caching.Memory;

namespace FoliCon.Modules.DeviantArt;
Expand All @@ -12,6 +14,8 @@ public class DArt : BindableBase

private readonly MemoryCache _cache = new(new MemoryCacheOptions());

private static readonly JsonSerializerSettings SerializerSettings = new() { NullValueHandling = NullValueHandling.Ignore };

public string ClientId
{
get => _clientId;
Expand Down Expand Up @@ -83,16 +87,64 @@ public async Task<DArtBrowseResult> Browse(string query, int offset = 0)
var url = GetBrowseApiUrl(query, offset);
using var response = await Services.HttpC.GetAsync(new Uri(url));
var jsonData = await response.Content.ReadAsStringAsync();

var serializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
var result = JsonConvert.DeserializeObject<DArtBrowseResult>(jsonData, serializerSettings);

var result = JsonConvert.DeserializeObject<DArtBrowseResult>(jsonData, SerializerSettings);

return result;
}

/// <summary>
/// Downloads a file from the DeviantArt API.
/// </summary>
/// <param name="deviationId">The ID of the deviation.</param>
/// <returns>The DArtDownloadResponse object containing the download details.</returns>
public async Task<DArtDownloadResponse> Download(string deviationId)
{
GetClientAccessTokenAsync();
var dArtDownloadResponse = await GetDArtDownloadResponseAsync(deviationId);
var targetDirectoryPath = FileUtils.CreateDirectoryInFoliConTemp(deviationId);
dArtDownloadResponse.LocalDownloadPath = targetDirectoryPath;
var downloadResponse = await Services.HttpC.GetAsync(dArtDownloadResponse.Src);

if (FileUtils.IsCompressedArchive(dArtDownloadResponse.Filename))
{
await ProcessCompressedFiles(downloadResponse, targetDirectoryPath);
}
else
{
await FileStreamToDestination(downloadResponse, targetDirectoryPath, dArtDownloadResponse.Filename);
}

FileUtils.DeleteDirectoryIfEmpty(targetDirectoryPath);

return dArtDownloadResponse;
}

public async Task<DArtDownloadResponse> GetDArtDownloadResponseAsync(string deviationId)
{
var url = GetDownloadApiUrl(deviationId);
using var response = await Services.HttpC.GetAsync(new Uri(url));
var jsonData = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<DArtDownloadResponse>(jsonData);
}

private async Task ProcessCompressedFiles(HttpResponseMessage downloadResponse, string targetDirectoryPath)
{
await using var stream = await downloadResponse.Content.ReadAsStreamAsync();
stream.ExtractPngAndIcoToDirectory(targetDirectoryPath);
}

private async Task FileStreamToDestination(HttpResponseMessage downloadResponse, string targetDirectoryPath,
string filename)
{
await using var fileStream = await downloadResponse.Content.ReadAsStreamAsync();
await using var file = File.Create(Path.Combine(targetDirectoryPath, filename));
await fileStream.CopyToAsync(file);
}

private static string GetPlaceboApiUrl(string clientAccessToken)
{
return "https://www.deviantart.com/api/v1/oauth2/placebo?access_token=" + clientAccessToken;
return $"https://www.deviantart.com/api/v1/oauth2/placebo?access_token={clientAccessToken}";
}

private string GetTokenApiUrl()
Expand All @@ -104,4 +156,9 @@ private string GetBrowseApiUrl(string query, int offset)
{
return $"https://www.deviantart.com/api/v1/oauth2/browse/newest?timerange=alltime&offset={offset}&q={query} folder icon&limit=20&access_token={ClientAccessToken}";
}

private string GetDownloadApiUrl(string deviationId)
{
return $"https://www.deviantart.com/api/v1/oauth2/deviation/download/{deviationId}?access_token={ClientAccessToken}";
}
}
11 changes: 11 additions & 0 deletions FoliCon/Modules/Extension/DialogServiceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,17 @@ public static void ShowSubfolderProcessingConfig(this IDialogService dialogServi
Logger.Trace("ShowSubfolderProcessingConfig called");
dialogService.ShowDialog("SubfolderProcessingConfig", callBack);
}

public static void ShowManualExplorer(this IDialogService dialogService, string deviationId,
DArt dartObject, Action<IDialogResult> callBack)
{
Logger.Trace("ShowManualExplorer called with deviationId: {DeviationId}", deviationId);
var p = new DialogParameters
{
{"DeviationId", deviationId}, {"dartobject", dartObject}
};
dialogService.ShowDialog("ManualExplorer", p, callBack);
}

public static void ShowAboutBox(this IDialogService dialogService, Action<IDialogResult> callBack)
{
Expand Down
45 changes: 45 additions & 0 deletions FoliCon/Modules/Extension/StreamExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using FoliCon.Modules.utils;
using SharpCompress.Common;
using SharpCompress.Readers;

namespace FoliCon.Modules.Extension;

public static class StreamExtensions
{
/// <summary>
/// Extracts PNG and ICO files from a compressed stream and writes them to a directory.
/// </summary>
/// <param name="archiveStream">The compressed stream containing the PNG and ICO files.</param>
/// <param name="targetPath">The path of the directory where the extracted files should be written.</param>
public static void ExtractPngAndIcoToDirectory(this Stream archiveStream, string targetPath)
{
using var reader = ReaderFactory.Open(archiveStream);
while (reader.MoveToNextEntry())
{
var entryKey = reader.Entry.Key;
if (IsUnwantedDirectoryOrFileType(entryKey, reader))
{
continue;
}

if (FileUtils.IsPngOrIco(entryKey))
{
reader.WriteEntryToDirectory(targetPath, new ExtractionOptions
{
ExtractFullPath = false,
Overwrite = true
});
}
}
}

private static bool IsUnwantedDirectoryOrFileType(string entryKey, IReader reader)
{
return entryKey != null && (reader.Entry.IsDirectory ||
entryKey.Contains("ResourceForks") ||
entryKey.Contains("__MACOSX") ||
entryKey.StartsWith("._") ||
entryKey.Equals(".DS_Store") ||
entryKey.Equals("Thumbs.db"));
}
}
Loading