Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
  • Loading branch information
wojciech-next committed Aug 30, 2020
0 parents commit 98c36f6
Show file tree
Hide file tree
Showing 33 changed files with 5,275 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.idea/
packages/
Pixel/bin
Pixel/obj
*.user
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Wojciech Piekielniak

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
16 changes: 16 additions & 0 deletions Pixel.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Pixel", "Pixel\Pixel.csproj", "{678454EF-DAF8-43FE-B91E-5EE188ACEC35}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{678454EF-DAF8-43FE-B91E-5EE188ACEC35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{678454EF-DAF8-43FE-B91E-5EE188ACEC35}.Debug|Any CPU.Build.0 = Debug|Any CPU
{678454EF-DAF8-43FE-B91E-5EE188ACEC35}.Release|Any CPU.ActiveCfg = Release|Any CPU
{678454EF-DAF8-43FE-B91E-5EE188ACEC35}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
6 changes: 6 additions & 0 deletions Pixel/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>
36 changes: 36 additions & 0 deletions Pixel/Common/Dictionary.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Collections.Generic;

namespace Pixel.Common
{
public static class Dictionary
{
private static Dictionary<int, bool> _map = new Dictionary<int, bool>();

public static void Put(int key, bool value)
{
_map[key] = value;
}

private static bool Get(int key, bool defaultValue)
{
try
{
return _map[key];
}
catch (KeyNotFoundException)
{
return defaultValue;
}
}

public static bool Get(int key)
{
return Get(key, true);
}

public static void Clear()
{
_map.Clear();
}
}
}
56 changes: 56 additions & 0 deletions Pixel/Common/Favorites.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System.Collections.Generic;
using System.IO;
using Pixel.TinyJson;

namespace Pixel.Common
{
public static class Favorites
{
private static string _json;
private static List<string> _favorites = new List<string>();

private static void ReadJson()
{
if (File.Exists("favorites.json"))
{
_json = File.ReadAllText("favorites.json");
_favorites = _json.FromJson<List<string>>();
}
}

private static void WriteJson()
{
_json = _favorites.ToJson();
File.WriteAllText("favorites.json", _json);
}

public static int CountFavorites()
{
ReadJson();
return _favorites.Count;
}

public static List<string> ReadFavorites()
{
return _favorites;
}

public static void WriteFavorites(List<string> favorites)
{
_favorites = favorites;
WriteJson();
}

public static void AddFavorite(string id)
{
_favorites.Add(id);
WriteJson();
}

public static void RemoveFavorite(string id)
{
_favorites.Remove(id);
WriteJson();
}
}
}
39 changes: 39 additions & 0 deletions Pixel/Common/SizeSuffix.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System;

namespace Pixel.Common
{
public class SizeSuffix
{
private static readonly string[] SizeSuffixes =
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

public static string GetSizeSuffix(long value, int decimalPlaces = 2)
{
if (decimalPlaces < 0)
{
throw new ArgumentOutOfRangeException(nameof(decimalPlaces));
}

if (value < 0)
{
return "-" + GetSizeSuffix(-value);
}

if (value == 0)
{
return string.Format("{0:n" + decimalPlaces + "} bytes", 0);
}

var mag = (int)Math.Log(value, 1024);
var adjustedSize = (decimal)value / (1L << (mag * 10));

if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
{
mag += 1;
adjustedSize /= 1024;
}

return string.Format("{0:n" + decimalPlaces + "} {1}", adjustedSize, SizeSuffixes[mag]);
}
}
}
109 changes: 109 additions & 0 deletions Pixel/Encryption/AES.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;

namespace Pixel.Encryption
{
public class AES
{
private const string NULL_IV = "0000000000000000";

public static string Encrypt(string input, string key, string iv = NULL_IV)
{
key = MD5Hasher.Hash(key);

return Convert.ToBase64String(EncryptStringToBytes(
input,
RawBytesFromString(key),
RawBytesFromString(iv)
));
}

public static string Decrypt(string inputBase64, string key, string iv = NULL_IV)
{
key = MD5Hasher.Hash(key);

return DecryptStringFromBytes(
Convert.FromBase64String(inputBase64),
RawBytesFromString(key),
RawBytesFromString(iv)
);
}

private static byte[] RawBytesFromString(string input)
{
return input.Select(x => (byte) ((ulong) x & 0xFF)).ToArray();
}

private static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException(nameof(plainText));
if (key == null || key.Length <= 0)
throw new ArgumentNullException(nameof(key));
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException(nameof(key));
byte[] encrypted;

using (var cipher = new RijndaelManaged())
{
cipher.Key = key;
cipher.IV = iv;
//cipher.Mode = CipherMode.CBC;
//cipher.Padding = PaddingMode.PKCS7;

var encryptor = cipher.CreateEncryptor(cipher.Key, cipher.IV);

using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}

return encrypted;
}

private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
{
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException(nameof(cipherText));
if (key == null || key.Length <= 0)
throw new ArgumentNullException(nameof(key));
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException(nameof(key));

string plaintext;

using (var cipher = new RijndaelManaged())
{
cipher.Key = key;
cipher.IV = iv;
//cipher.Mode = CipherMode.CBC;
//cipher.Padding = PaddingMode.PKCS7;

var decryptor = cipher.CreateDecryptor(cipher.Key, cipher.IV);

using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}

return plaintext;
}
}
}
23 changes: 23 additions & 0 deletions Pixel/Encryption/MD5Hasher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Text;

namespace Pixel.Encryption
{
public static class MD5Hasher
{
public static string Hash(string input)
{
using (var md5 = System.Security.Cryptography.MD5.Create())
{
var inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
var hashBytes = md5.ComputeHash(inputBytes);

var sb = new StringBuilder();
foreach (var t in hashBytes)
{
sb.Append(t.ToString("X2"));
}
return sb.ToString().ToLower();
}
}
}
}
51 changes: 51 additions & 0 deletions Pixel/Extensions/HttpClientExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Pixel.Extensions
{
public static class HttpClientExtension
{
public static async Task DownloadDataAsync(this HttpClient client, string requestUrl, Stream destination, IProgress<float> progress = null, CancellationToken cancellationToken = default)
{
using (var response = await client.GetAsync(requestUrl, HttpCompletionOption.ResponseHeadersRead)) {
var contentLength = response.Content.Headers.ContentLength;
using (var download = await response.Content.ReadAsStreamAsync()) {
if (progress is null || !contentLength.HasValue) {
await download.CopyToAsync(destination);
return;
}
var progressWrapper = new Progress<long>(totalBytes => progress.Report(GetProgressPercentage(totalBytes, contentLength.Value)));
await download.CopyToAsync(destination, 81920, progressWrapper, cancellationToken);
}
}

float GetProgressPercentage(float totalBytes, float currentBytes) => (totalBytes / currentBytes) * 100f;
}

private static async Task CopyToAsync(this Stream source, Stream destination, int bufferSize, IProgress<long> progress = null, CancellationToken cancellationToken = default)
{
if (bufferSize < 0)
throw new ArgumentOutOfRangeException(nameof(bufferSize));
if (source is null)
throw new ArgumentNullException(nameof(source));
if (!source.CanRead)
throw new InvalidOperationException($"'{nameof(source)}' is not readable.");
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (!destination.CanWrite)
throw new InvalidOperationException($"'{nameof(destination)}' is not writable.");

var buffer = new byte[bufferSize];
long totalBytesRead = 0;
int bytesRead;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) {
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
progress?.Report(totalBytesRead);
}
}
}
}
11 changes: 11 additions & 0 deletions Pixel/Extensions/IndexExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.Collections.Generic;
using System.Linq;

namespace Pixel.Extensions
{
public static class IndexExtension
{
public static IEnumerable<(T item, int index)> LoopIndex<T>(IEnumerable<T> self) =>
self.Select((item, index) => (item, index));
}
}
Loading

0 comments on commit 98c36f6

Please sign in to comment.