Skip to content

Commit

Permalink
Add Upgrade's api
Browse files Browse the repository at this point in the history
  • Loading branch information
maikebing committed Jul 4, 2019
1 parent 387949e commit 855f0d2
Show file tree
Hide file tree
Showing 8 changed files with 323 additions and 122 deletions.
38 changes: 38 additions & 0 deletions IoTSharp.Releases/GithubRelease.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
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; }
}
}
18 changes: 18 additions & 0 deletions IoTSharp.Releases/IoTSharp.Releases.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<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>
33 changes: 33 additions & 0 deletions IoTSharp.Releases/LinkHeaderParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
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;
}
}
}
173 changes: 173 additions & 0 deletions IoTSharp.Releases/ReleaseDownloader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
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));
}
}
}
26 changes: 24 additions & 2 deletions IoTSharp.sln
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
38 changes: 32 additions & 6 deletions IoTSharp/Controllers/InstallerController.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
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;

Expand Down Expand Up @@ -60,20 +67,39 @@ private InstanceDto GetInstanceDto()

[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)
Expand Down
Loading

0 comments on commit 855f0d2

Please sign in to comment.