Skip to content

Commit

Permalink
现在可以上传私信图片了
Browse files Browse the repository at this point in the history
  • Loading branch information
wherewhere committed Oct 15, 2023
1 parent bb4415b commit a1d53eb
Show file tree
Hide file tree
Showing 10 changed files with 102 additions and 101 deletions.
16 changes: 10 additions & 6 deletions OSSUploader/OSSUploader/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Windows.ApplicationModel;
Expand All @@ -23,7 +24,7 @@ namespace CoolapkUWP.OSSUploader
/// <summary>
/// 提供特定于应用程序的行为,以补充默认的应用程序类。
/// </summary>
sealed partial class App : Application
internal sealed partial class App : Application
{
/// <summary>
/// 初始化单一实例应用程序对象。这是执行的创作代码的第一行,
Expand All @@ -34,7 +35,7 @@ public App()
InitializeComponent();
Suspending += OnSuspending;
UnhandledException += Application_UnhandledException;

if (ApiInformation.IsEnumNamedValuePresent("Windows.UI.Xaml.FocusVisualKind", "Reveal"))
{
FocusVisualKind = AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Xbox" ? FocusVisualKind.Reveal : FocusVisualKind.HighVisibility;
Expand Down Expand Up @@ -150,20 +151,23 @@ private async void OnAppServiceRequestReceived(AppServiceConnection sender, AppS

try
{
if (message.TryGetValue("UID", out var uid) && message.TryGetValue("UserName", out var username) && message.TryGetValue("Token", out var token))
if (message.TryGetValue("UID", out object uid) && message.TryGetValue("UserName", out object username) && message.TryGetValue("Token", out object token))
{
NetworkHelper.SetLoginCookie(uid.ToString(), username.ToString(), token.ToString());
}

if (message.TryGetValue("TokenVersion", out var TokenVersion) && message.TryGetValue("UserAgent", out var UserAgent) && message.TryGetValue("APIVersion", out var APIVersion))
if (message.TryGetValue("TokenVersion", out object TokenVersion) && message.TryGetValue("UserAgent", out object UserAgent) && message.TryGetValue("APIVersion", out object APIVersion))
{
NetworkHelper.SetRequestHeaders((TokenVersions)TokenVersion, JsonConvert.DeserializeObject<UserAgent>(UserAgent.ToString(), jSetting), JsonConvert.DeserializeObject<APIVersion>(APIVersion.ToString(), jSetting));
}

if (message.TryGetValue("Images", out var images))
if (message.TryGetValue("Images", out object images))
{
string uploadBucket = message.TryGetValue("UploadBucket", out object UploadBucket) ? UploadBucket.ToString() : "image";
string uploadDir = message.TryGetValue("UploadDir", out object UploadDir) ? UploadDir.ToString() : "feed";
string toUid = message.TryGetValue("ToUid", out object ToUid) ? ToUid.ToString() : string.Empty;
IEnumerable<UploadFileFragment> fragments = JsonConvert.DeserializeObject<IEnumerable<UploadFileFragment>>(images.ToString(), new JsonSerializerSettings { ContractResolver = new IgnoreIgnoredContractResolver() });
returnMessage["Result"] = (await RequestHelper.UploadImages(fragments)).ToArray();
returnMessage["Result"] = await RequestHelper.UploadImages(fragments, uploadBucket, uploadDir, toUid).ContinueWith(x => x.Result.ToArray());
}
}
catch (Exception ex)
Expand Down
34 changes: 17 additions & 17 deletions OSSUploader/OSSUploader/Common/TokenCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class TokenCreator
{
private static readonly string guid = Guid.NewGuid().ToString();
private static readonly string aid = RandHexString(16);
private static readonly string mac = RandMacAdress();
private static readonly string mac = RandMacAddress();
private static readonly string SystemManufacturer;
private static readonly string SystemProductName;

Expand Down Expand Up @@ -48,58 +48,56 @@ public string GetToken()
/// </summary>
private string GetTokenWithDeviceCode(string deviceCode)
{
string timeStamp = DateTime.Now.ConvertDateTimeToUnixTimeStamp().ToString();
string timeStamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();

string base64TimeStamp = timeStamp.GetBase64(true);
string base64TimeStamp = timeStamp.GetBase64();
string md5TimeStamp = timeStamp.GetMD5();
string md5DeviceCode = deviceCode.GetMD5();

string token = $"token://com.coolapk.market/dcf01e569c1e3db93a3d0fcf191a622c?{md5TimeStamp}${md5DeviceCode}&com.coolapk.market";
string base64Token = token.GetBase64(true);
string base64Token = token.GetBase64();
string md5Base64Token = base64Token.GetMD5();
string md5Token = token.GetMD5();

string bcryptSalt = $"{$"$2y$10${base64TimeStamp}/{md5Token}".Substring(0, 31)}u";
string bcryptresult = BCrypt.Net.BCrypt.HashPassword(md5Base64Token, bcryptSalt);
string bcryptResult = BCrypt.Net.BCrypt.HashPassword(md5Base64Token, bcryptSalt);

string appToken = $"v2{bcryptresult.GetBase64(true)}";
string appToken = $"v2{bcryptResult.GetBase64()}";

return appToken;
}

private static string GetCoolapkAppToken()
{
double timeStamp = DateTime.Now.ConvertDateTimeToUnixTimeStamp();
long timeStamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
string hex_timeStamp = $"0x{Convert.ToString((int)timeStamp, 16)}";
// 时间戳加密
string md5_timeStamp = $"{timeStamp}".GetMD5();
string token = $"token://com.coolapk.market/c67ef5943784d09750dcfbb31020f0ab?{md5_timeStamp}${guid}&com.coolapk.market";
string md5_token = token.GetBase64().GetMD5();
string md5_token = token.GetBase64(true).GetMD5();
string appToken = $"{md5_token}{guid}{hex_timeStamp}";
return appToken;
}

/// <summary>
/// CreateDeviceCode Generate your custom device code
/// </summary>
private static string CreateDeviceCode(string aid, string mac, string manufactor, string brand, string model, string buildNumber)
{
return $"{aid}; ; ; {mac}; {manufactor}; {brand}; {model}; {buildNumber}".GetBase64(true).Reverse();
}
private static string CreateDeviceCode(string aid, string mac, string manufactory, string brand, string model, string buildNumber) =>
$"{aid}; ; ; {mac}; {manufactory}; {brand}; {model}; {buildNumber}".GetBase64().Reverse();

private static string RandMacAdress()
private static string RandMacAddress()
{
Random rand = new Random();
string macAdress = string.Empty;
string macAddress = string.Empty;
for (int i = 0; i < 6; i++)
{
macAdress += rand.Next(256).ToString("x2");
macAddress += rand.Next(256).ToString("x2");
if (i != 5)
{
macAdress += ":";
macAddress += ":";
}
}
return macAdress;
return macAddress;
}

private static string RandHexString(int n)
Expand All @@ -109,6 +107,8 @@ private static string RandHexString(int n)
rand.NextBytes(bytes);
return BitConverter.ToString(bytes).ToUpperInvariant().Replace("-", "");
}

public override string ToString() => GetToken();
}

public enum TokenVersions
Expand Down
1 change: 0 additions & 1 deletion OSSUploader/OSSUploader/CoolapkUWP.OSSUploader.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,6 @@
<Compile Include="Common\ExceptionHandling.cs" />
<Compile Include="Common\TokenCreator.cs" />
<Compile Include="Helpers\DataHelper.cs" />
<Compile Include="Helpers\DateHelper.cs" />
<Compile Include="Helpers\NetworkHelper.cs" />
<Compile Include="Helpers\OSSUploadHelper.cs" />
<Compile Include="Helpers\RequestHelper.cs" />
Expand Down
33 changes: 14 additions & 19 deletions OSSUploader/OSSUploader/Helpers/DataHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Runtime.InteropServices.WindowsRuntime;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage.Streams;

namespace CoolapkUWP.OSSUploader.Helpers
Expand All @@ -16,18 +17,16 @@ public static string GetMD5(this string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input));

string results = BitConverter.ToString(data).ToLowerInvariant();

return results.Replace("-", "");
}
}

public static string GetBase64(this string input, bool israw = false)
public static string GetBase64(this string input, bool isRaw = false)
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
string result = Convert.ToBase64String(bytes);
if (israw) { result = result.Replace("=", ""); }
if (!isRaw) { result = result.Replace("=", ""); }
return result;
}

Expand All @@ -38,38 +37,34 @@ public static string Reverse(this string text)
return new string(charArray);
}

public static IBuffer GetBuffer(this IRandomAccessStream randomStream)
public static async Task<IBuffer> GetBufferAsync(this IRandomAccessStream randomStream)
{
using (Stream stream = randomStream.GetInputStreamAt(0).AsStreamForRead())
using (Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomStream.GetInputStreamAt(0)))
{
return stream.GetBuffer();
return await stream.GetBufferAsync();
}
}

public static byte[] GetBytes(this IRandomAccessStream randomStream)
public static async Task<byte[]> GetBytesAsync(this IRandomAccessStream randomStream)
{
using (Stream stream = randomStream.GetInputStreamAt(0).AsStreamForRead())
using (Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomStream.GetInputStreamAt(0)))
{
return stream.GetBytes();
return await stream.GetBytesAsync();
}
}

public static IBuffer GetBuffer(this Stream stream)
public static async Task<IBuffer> GetBufferAsync(this Stream stream)
{
byte[] bytes = new byte[0];
if (stream != null)
{
bytes = stream.GetBytes();
}
byte[] bytes = stream != null ? await stream.GetBytesAsync() : Array.Empty<byte>();
return bytes.AsBuffer();
}

public static byte[] GetBytes(this Stream stream)
public static async Task<byte[]> GetBytesAsync(this Stream stream)
{
if (stream.CanSeek) // stream.Length 已确定
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
_ = await stream.ReadAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
Expand All @@ -81,7 +76,7 @@ public static byte[] GetBytes(this Stream stream)
int read = 0;

int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
while ((chunk = await stream.ReadAsync(buffer, read, buffer.Length - read).ConfigureAwait(false)) > 0)
{
read += chunk;

Expand Down
13 changes: 0 additions & 13 deletions OSSUploader/OSSUploader/Helpers/DateHelper.cs

This file was deleted.

9 changes: 4 additions & 5 deletions OSSUploader/OSSUploader/Helpers/NetworkHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
using Windows.Web.Http.Filters;
using HttpClient = System.Net.Http.HttpClient;
using HttpResponseMessage = System.Net.Http.HttpResponseMessage;
using HttpStatusCode = System.Net.HttpStatusCode;

namespace CoolapkUWP.OSSUploader.Helpers
{
Expand Down Expand Up @@ -125,8 +124,8 @@ public static async Task<string> PostAsync(Uri uri, HttpContent content, IEnumer
{
HttpResponseMessage response;
BeforeGetOrPost(coolapkCookies, uri, "XMLHttpRequest");
response = await Client.PostAsync(uri, content);
return await response.Content.ReadAsStringAsync();
response = await Client.PostAsync(uri, content).ConfigureAwait(false);
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (Exception)
{
Expand All @@ -139,7 +138,7 @@ public static async Task<Stream> GetStreamAsync(Uri uri, IEnumerable<(string nam
try
{
BeforeGetOrPost(coolapkCookies, uri, request);
return await Client.GetStreamAsync(uri);
return await Client.GetStreamAsync(uri).ConfigureAwait(false);
}
catch (Exception)
{
Expand All @@ -152,7 +151,7 @@ public static async Task<string> GetStringAsync(Uri uri, IEnumerable<(string nam
try
{
BeforeGetOrPost(coolapkCookies, uri, request);
return await Client.GetStringAsync(uri);
return await Client.GetStringAsync(uri).ConfigureAwait(false);
}
catch (Exception)
{
Expand Down
45 changes: 32 additions & 13 deletions OSSUploader/OSSUploader/Helpers/OSSUploadHelper.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using Aliyun.OSS;
using Aliyun.OSS.Util;
using CoolapkUWP.OSSUploader.Models;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace CoolapkUWP.OSSUploader.Helpers
{
Expand All @@ -11,7 +13,7 @@ public static class OSSUploadHelper
private const string callbackVar = "eyJ4OnZhcjEiOiJmYWxzZSJ9";
private const string callback = "eyJjYWxsYmFja0JvZHlUeXBlIjoiYXBwbGljYXRpb25cL2pzb24iLCJjYWxsYmFja0hvc3QiOiJhcGkuY29vbGFway5jb20iLCJjYWxsYmFja1VybCI6Imh0dHBzOlwvXC9hcGkuY29vbGFway5jb21cL3Y2XC9jYWxsYmFja1wvbW9iaWxlT3NzVXBsb2FkU3VjY2Vzc0NhbGxiYWNrP2NoZWNrQXJ0aWNsZUNvdmVyUmVzb2x1dGlvbj0wJnZlcnNpb25Db2RlPTIxMDIwMzEiLCJjYWxsYmFja0JvZHkiOiJ7XCJidWNrZXRcIjoke2J1Y2tldH0sXCJvYmplY3RcIjoke29iamVjdH0sXCJoYXNQcm9jZXNzXCI6JHt4OnZhcjF9fSJ9";

public static string OssUpload(UploadPrepareInfo prepareInfo, UploadFileInfo fileInfo, Stream stream, string contentType)
public static Task<string> OssUploadAsync(UploadPrepareInfo prepareInfo, UploadFileInfo fileInfo, Stream stream, string contentType)
{
OssClient oss = new OssClient(
prepareInfo.EndPoint.Replace("https://", ""),
Expand All @@ -34,22 +36,39 @@ public static string OssUpload(UploadPrepareInfo prepareInfo, UploadFileInfo fil
stream,
metadata);

PutObjectResult putResult = oss.PutObject(request);

string response = GetCallbackResponse(putResult);
return response;
return oss.PutObjectAsync(request);
}

private static string GetCallbackResponse(PutObjectResult putObjectResult)
private static Task<string> PutObjectAsync(this OssClient client, PutObjectRequest putObjectRequest)
{
string callbackResponse = null;
using (Stream stream = putObjectResult.ResponseStream)
TaskCompletionSource<string> taskCompletionSource = new TaskCompletionSource<string>(client);

IAsyncResult asyncResult = client.BeginPutObject(putObjectRequest, async iar =>
{
byte[] buffer = new byte[4 * 1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
callbackResponse = Encoding.Default.GetString(buffer, 0, bytesRead);
}
return callbackResponse;
// this is the callback

TaskCompletionSource<string> _taskCompletionSource = (TaskCompletionSource<string>)iar.AsyncState;
OssClient _client = (OssClient)_taskCompletionSource.Task.AsyncState;

try
{
PutObjectResult putResult = _client.EndPutObject(iar);
string callbackResponse = null;
using (Stream stream = putResult.ResponseStream)
{
byte[] buffer = new byte[4 * 1024];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
callbackResponse = Encoding.Default.GetString(buffer, 0, bytesRead);
}
_taskCompletionSource.TrySetResult(callbackResponse);
}
catch (Exception ex)
{
_taskCompletionSource.TrySetException(ex);
}
}, taskCompletionSource);

return taskCompletionSource.Task;
}
}
}
Loading

0 comments on commit a1d53eb

Please sign in to comment.