提交 855f0d2d 编写于 作者: 麦壳饼's avatar 麦壳饼

Add Upgrade's api

上级 387949ec
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IoTSharp.Releases
{
public class GithubRelease
{
public string url { get; set; }
public string html_url { get; set; }
public string assets_url { get; set; }
public string upload_url { get; set; }
public string tarball_url { get; set; }
public string zipball_url { get; set; }
public string id { get; set; }
public string tag_name { get; set; }
public string name { get; set; }
public string body { get; set; }
public ICollection<GithubReleaseAsset> assets { get; set; }
}
public class GithubReleaseAsset
{
public string url { get; set; }
public string browser_download_url { get; set; }
public string id { get; set; }
public string name { get; set; }
public string label { get; set; }
public string state { get; set; }
public string content_type { get; set; }
public long size { get; set; }
public int download_count { get; set; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net46</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Description></Description>
<PackageProjectUrl>https://github.com/maikebing/GithubReleasesDownloader</PackageProjectUrl>
<RepositoryUrl>https://github.com/maikebing/GithubReleasesDownloader</RepositoryUrl>
<Authors>mwhitis;IoTSharp;maikebing</Authors>
<Company>mwhitis;IoTSharp;maikebing</Company>
<PackageTags>Github;Releases;Downloader;IoTSharp</PackageTags>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IoTSharp.Releases
{
public class LinkHeaderParser
{
/*
<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=2>; rel="next",
<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=34>; rel="last"
*/
public string GetNextPageFromHeader(string headerText)
{
if (string.IsNullOrWhiteSpace(headerText))
{
return string.Empty;
}
var links = headerText.Split(',');
foreach (var link in links.Where(link => link.Contains("rel=\"next\"")))
{
return link.Split(';')[0].Replace("<","").Replace(">","").Trim();
}
return string.Empty;
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace IoTSharp.Releases
{
public class ReleaseDownloader
{
private readonly string _baseUri;
private readonly string _accessToken;
private readonly string _userAgent;
private readonly string _releaseUri;
private string _user;
private string _repo;
private string _token;
public ReleaseDownloader(string _url, string accessToken)
{
var uri = new Uri(_url);
_baseUri = $"{ GetBaseUri(uri)}/repos/{GetUserFromUri(uri)}/{GetRepoFromUri(uri)}";
_accessToken = accessToken;
_userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3829.0 Safari/537.36 Edg/77.0.197.1"; ;
_releaseUri = GetReleaseUri();
}
private static string GetUserFromUri(Uri uri)
{
return !uri.LocalPath.Contains("/") ? string.Empty : uri.Segments[1].TrimEnd('/');
}
private static string GetRepoFromUri(Uri uri)
{
return !uri.LocalPath.Contains("/") ? string.Empty : uri.Segments[2].TrimEnd('/');
}
private static string GetBaseUri(Uri uri)
{
return uri.Host.Equals("github.com", StringComparison.OrdinalIgnoreCase) ? "https://api.github.com" : $"{uri.Scheme}://{uri.Host}/api/v3";
}
public ICollection<GithubRelease> GetDataForAllReleases()
{
var requestingUri = GetAccessTokenUri(_releaseUri);
return DownloadReleases(requestingUri);
}
public ICollection<GithubRelease> DownloadReleases(string requestingUri)
{
Console.WriteLine("Requesting: {0}", requestingUri);
var request = (HttpWebRequest)WebRequest.Create(new Uri(requestingUri));
request.UserAgent = _userAgent;
var response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
var responseFromServer = ReadResponseFromServer(response);
var releases = JsonConvert.DeserializeObject<List<GithubRelease>>(responseFromServer);
var parser = new LinkHeaderParser();
var linkHeader = response.Headers["Link"];
var nextUrl = parser.GetNextPageFromHeader(linkHeader);
if (!string.IsNullOrEmpty(nextUrl))
{
releases.AddRange(DownloadReleases(nextUrl));
}
// Clean up the streams and the response.
response.Close();
return releases;
}
private string GetReleaseUri()
{
var releaseUri = $"{_baseUri}/releases";
return releaseUri;
}
private static string ReadResponseFromServer(WebResponse response)
{
using (var dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
using (var reader = new StreamReader(dataStream))
{
// Read the content.
return reader.ReadToEnd();
}
}
}
private string GetAssetsUriForId(string id)
{
var assetUri = $"{_releaseUri}/assets/{id}";
return assetUri;
}
private string GetAccessTokenUri(string uri)
{
return _accessToken == string.Empty ? uri : uri += $"?access_token={_accessToken}";
}
public bool DownloadAsset(string id, string path)
{
WebResponse response = GetAssetResponse(id);
GetBinaryResponseFromResponse(path,response);
return true;
}
public bool DownloadAsset(string id, out byte[] assetdata)
{
WebResponse response = GetAssetResponse(id);
assetdata = GetBinaryResponseFromResponse(response);
return true;
}
private WebResponse GetAssetResponse(string id)
{
var assetUri = GetAccessTokenUri(GetAssetsUriForId(id));
var request = (HttpWebRequest)WebRequest.Create(new Uri(assetUri));
request.Accept = "application/octet-stream";
request.UserAgent = "mwhitis";
var response = request.GetResponse();
return response;
}
private static byte[] GetBinaryResponseFromResponse( WebResponse response)
{
byte[] result = null;
long received = 0;
byte[] buffer = new byte[1024];
using (var ms = new MemoryStream() )
{
using (var input = response.GetResponseStream())
{
int size = input.Read(buffer, 0, buffer.Length);
while (size > 0)
{
ms.Write(buffer, 0, size);
received += size;
size = input.Read(buffer, 0, buffer.Length);
}
}
result = ms.ToArray();
}
return result;
}
private static void GetBinaryResponseFromResponse(string path, WebResponse response)
{
System.IO.File.WriteAllBytes(path, GetBinaryResponseFromResponse(response));
}
}
}
......@@ -23,13 +23,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTClient", "Clients\MQTTC
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MQTT-C-Client", "Clients\MQTT-C-Client\MQTT-C-Client.vcxproj", "{DD36544C-2E7C-4388-B34F-FF705E141E4A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IoTSharp.EdgeSdk.MQTT", "IoTSharp.EdgeSdk.MQTT\IoTSharp.EdgeSdk.MQTT.csproj", "{FE56C09F-89F0-4AC5-8615-AFBB4C23F937}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IoTSharp.EdgeSdk.MQTT", "IoTSharp.EdgeSdk.MQTT\IoTSharp.EdgeSdk.MQTT.csproj", "{FE56C09F-89F0-4AC5-8615-AFBB4C23F937}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IoT Edges", "IoT Edges", "{03D9AC26-8A9E-4128-B2C0-CCA33730720F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IoTSharp.Edge.ModBus", "IoTSharp.Edge.ModBus\IoTSharp.Edge.ModBus.csproj", "{9267A0CE-ECBC-41E4-AD83-927117FD625E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IoTSharp.Extensions", "IoTSharp.Extensions\IoTSharp.Extensions.csproj", "{551E62E3-51DA-4C1D-8DBB-7346A29EE817}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IoTSharp.Extensions", "IoTSharp.Extensions\IoTSharp.Extensions.csproj", "{551E62E3-51DA-4C1D-8DBB-7346A29EE817}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IoTSharp.Releases", "IoTSharp.Releases\IoTSharp.Releases.csproj", "{AA859239-6539-4A35-9A56-DF0D31ADCEED}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
......@@ -211,6 +213,26 @@ Global
{551E62E3-51DA-4C1D-8DBB-7346A29EE817}.Release|x64.Build.0 = Release|Any CPU
{551E62E3-51DA-4C1D-8DBB-7346A29EE817}.Release|x86.ActiveCfg = Release|Any CPU
{551E62E3-51DA-4C1D-8DBB-7346A29EE817}.Release|x86.Build.0 = Release|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Debug|ARM.ActiveCfg = Debug|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Debug|ARM.Build.0 = Debug|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Debug|ARM64.ActiveCfg = Debug|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Debug|ARM64.Build.0 = Debug|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Debug|x64.ActiveCfg = Debug|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Debug|x64.Build.0 = Debug|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Debug|x86.ActiveCfg = Debug|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Debug|x86.Build.0 = Debug|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Release|Any CPU.Build.0 = Release|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Release|ARM.ActiveCfg = Release|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Release|ARM.Build.0 = Release|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Release|ARM64.ActiveCfg = Release|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Release|ARM64.Build.0 = Release|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Release|x64.ActiveCfg = Release|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Release|x64.Build.0 = Release|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Release|x86.ActiveCfg = Release|Any CPU
{AA859239-6539-4A35-9A56-DF0D31ADCEED}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
using IoTSharp.Data;
using IoTSharp.Dtos;
using IoTSharp.Extensions;
using IoTSharp.Releases;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Threading.Tasks;
......@@ -60,20 +67,39 @@ namespace IoTSharp.Controllers
[AllowAnonymous]
[HttpPost]
public async Task<ActionResult<InstanceDto>> Install([FromBody] InstallDto model)
public ActionResult<InstanceDto> Upgrade([FromHeader(Name ="Authorization")] string token, [FromHeader(Name ="Source")] string source , [FromHeader(Name = "AssetName")] string assetname )
{
ActionResult<InstanceDto> actionResult = NoContent();
try
{
if (!_context.Relationship.Any())
var githubDownloader = new ReleaseDownloader(source, token);
var releases = githubDownloader.GetDataForAllReleases();
var asset = releases.FirstOrDefault()?.assets?.FirstOrDefault(at => at.name == assetname);
if (asset != null)
{
await _dBInitializer.SeedRoleAsync();
await _dBInitializer.SeedUserAsync(model);
actionResult = Ok(GetInstanceDto());
if (githubDownloader.DownloadAsset(asset.id, out byte[] assetbinary))
{
using (var ms = new MemoryStream(assetbinary))
{
using (var zip = new System.IO.Compression.ZipArchive(ms))
{
foreach (ZipArchiveEntry item in zip.Entries)
{
var file = new System.IO.FileInfo(System.IO.Path.Combine(AppContext.BaseDirectory, item.FullName));
item.ExtractToFile(file.FullName, true);
}
}
}
actionResult = Ok(asset);
}
else
{
actionResult = BadRequest(new ApiResult(ApiCode.Exception, "Can't download asset!"));
}
}
else
{
actionResult = BadRequest(new { code = ApiCode.AlreadyExists, msg = "Already installed", data = GetInstanceDto() });
actionResult = NotFound(new ApiResult(ApiCode.Exception, "Can't found asset!"));
}
}
catch (Exception ex)
......
......@@ -32,119 +32,6 @@ namespace IoTSharp.Extensions
}
});
}
public static IWebHostBuilder UseContentRootAsEnv(this IWebHostBuilder hostBuilder)
{
bool IsWindowsService = false;
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
using (var process = GetParent(Process.GetCurrentProcess()))
{
IsWindowsService = process != null && process.ProcessName == "services";
}
}
if (Environment.CommandLine.Contains("--usebasedirectory") || (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && IsWindowsService))
{
hostBuilder.UseContentRoot(AppContext.BaseDirectory);
}
else
{
if (!Debugger.IsAttached)
{
hostBuilder.UseContentRoot(System.IO.Directory.GetCurrentDirectory());
}
}
return hostBuilder;
}
public static void RunAsEnv(this IWebHost host)
{
bool IsWindowsService = false;
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
using (var process = GetParent(Process.GetCurrentProcess()))
{
IsWindowsService = process != null && process.ProcessName == "services";
}
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && IsWindowsService)
{
System.IO.Directory.SetCurrentDirectory(AppContext.BaseDirectory);
host.RunAsService();
}
else
{
if (Environment.CommandLine.Contains("--usebasedirectory"))
{
System.IO.Directory.SetCurrentDirectory(AppContext.BaseDirectory);
}
host.Run();
}
}
private static Process GetParent(Process child)
{
var parentId = 0;
var handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (handle == IntPtr.Zero)
{
return null;
}
var processInfo = new PROCESSENTRY32
{
dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32))
};
if (!Process32First(handle, ref processInfo))
{
return null;
}
do
{
if (child.Id == processInfo.th32ProcessID)
{
parentId = (int)processInfo.th32ParentProcessID;
}
} while (parentId == 0 && Process32Next(handle, ref processInfo));
if (parentId > 0)
{
return Process.GetProcessById(parentId);
}
return null;
}
private static uint TH32CS_SNAPPROCESS = 2;
[DllImport("kernel32.dll")]
public static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
[DllImport("kernel32.dll")]
public static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[StructLayout(LayoutKind.Sequential)]
public struct PROCESSENTRY32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExeFile;
}
}
}
\ No newline at end of file
......@@ -113,6 +113,10 @@
<ItemGroup>
<Folder Include="Jobs\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\IoTSharp.Extensions\IoTSharp.Extensions.csproj" />
<ProjectReference Include="..\IoTSharp.Releases\IoTSharp.Releases.csproj" />
</ItemGroup>
<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
<!-- Ensure Node.js is installed -->
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册