search
This commit is contained in:
parent
6fcad7c252
commit
b8809deaa1
12 changed files with 625 additions and 182 deletions
|
|
@ -1,26 +1,19 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NuGet.Packaging.Core;
|
||||
using NuGet.Versioning;
|
||||
using nuget_host.Data;
|
||||
using nuget_host.Entities;
|
||||
using nuget_host.Helpers;
|
||||
|
||||
namespace nuget_host.Controllers
|
||||
{
|
||||
|
||||
[AllowAnonymous]
|
||||
public class PackagesController : Controller
|
||||
public partial class PackagesController : Controller
|
||||
{
|
||||
private readonly ILogger<PackagesController> logger;
|
||||
private readonly IDataProtector protector;
|
||||
|
|
@ -40,180 +33,67 @@ namespace nuget_host.Controllers
|
|||
this.dbContext = dbContext;
|
||||
}
|
||||
|
||||
[HttpPut("packages")]
|
||||
public async Task<IActionResult> Put()
|
||||
{
|
||||
try
|
||||
{
|
||||
var clientVersionId = Request.Headers["X-NuGet-Client-Version"];
|
||||
var apiKey = Request.Headers["X-NuGet-ApiKey"];
|
||||
ViewData["versionId"] = typeof(PackagesController).Assembly.FullName;
|
||||
var files = new List<string>();
|
||||
ViewData["files"] = files;
|
||||
|
||||
var clearkey = protector.Unprotect(apiKey);
|
||||
var apikey = dbContext.ApiKeys.SingleOrDefault(k => k.Id == clearkey);
|
||||
if (apikey == null)
|
||||
{
|
||||
logger.LogError("403 : no api-key");
|
||||
return Unauthorized();
|
||||
}
|
||||
|
||||
foreach (var file in Request.Form.Files)
|
||||
{
|
||||
string initpath = Path.Combine(Environment.GetEnvironmentVariable("TEMP") ??
|
||||
Environment.GetEnvironmentVariable("TMP") ?? "/tmp",
|
||||
$"nuget_host-{Guid.NewGuid()}.nupkg");
|
||||
|
||||
using (FileStream fw = new FileStream(initpath, FileMode.Create))
|
||||
{
|
||||
file.CopyTo(fw);
|
||||
}
|
||||
|
||||
using (FileStream fw = new FileStream(initpath, FileMode.Open))
|
||||
{
|
||||
var archive = new ZipArchive(fw);
|
||||
|
||||
var nuspec = archive.Entries.FirstOrDefault(e => e.FullName.EndsWith(".nuspec"));
|
||||
if (nuspec==null) return BadRequest("no nuspec from archive");
|
||||
string pkgpath;
|
||||
NuGetVersion version;
|
||||
string pkgid;
|
||||
string fullpath;
|
||||
|
||||
using (var specstr = nuspec.Open())
|
||||
{
|
||||
NuspecCoreReader reader = new NuspecCoreReader(specstr);
|
||||
|
||||
string pkgdesc = reader.GetDescription();
|
||||
pkgid = reader.GetId();
|
||||
version = reader.GetVersion();
|
||||
string pkgidpath = Path.Combine(nugetSettings.PackagesRootDir,
|
||||
pkgid);
|
||||
pkgpath = Path.Combine(pkgidpath, version.ToFullString());
|
||||
string name = $"{pkgid}-{version}.nupkg";
|
||||
fullpath = Path.Combine(pkgpath, name);
|
||||
|
||||
var destpkgiddir = new DirectoryInfo(pkgidpath);
|
||||
Package package = dbContext.Packages.SingleOrDefault(p => p.Id == pkgid);
|
||||
if (package != null)
|
||||
{
|
||||
if (package.OwnerId != apikey.UserId)
|
||||
{
|
||||
return new ForbidResult();
|
||||
}
|
||||
package.Description = pkgdesc;
|
||||
}
|
||||
else
|
||||
{
|
||||
package = new Package
|
||||
{
|
||||
Id = pkgid,
|
||||
Description = pkgdesc,
|
||||
OwnerId = apikey.UserId
|
||||
};
|
||||
dbContext.Packages.Add(package);
|
||||
}
|
||||
if (!destpkgiddir.Exists) destpkgiddir.Create();
|
||||
|
||||
var source = new FileInfo(initpath);
|
||||
var dest = new FileInfo(fullpath);
|
||||
var destdir = new DirectoryInfo(dest.DirectoryName);
|
||||
if (dest.Exists)
|
||||
{
|
||||
ViewData["msg"] = "existant";
|
||||
ViewData["ecode"] = 1;
|
||||
logger.LogWarning("400 : existant");
|
||||
return BadRequest(ViewData);
|
||||
}
|
||||
else
|
||||
{
|
||||
destdir.Create();
|
||||
|
||||
source.MoveTo(fullpath);
|
||||
files.Add(name);
|
||||
string fullstringversion = version.ToFullString();
|
||||
PackageVersion pkgver = dbContext.PackageVersions.FirstOrDefault
|
||||
(v => v.PackageId == package.Id && v.FullString == fullstringversion);
|
||||
if (pkgver == null)
|
||||
{
|
||||
pkgver = new PackageVersion
|
||||
{
|
||||
Package = package,
|
||||
Major = version.Major,
|
||||
Minor = version.Minor,
|
||||
Patch = version.Patch,
|
||||
IsPrerelease = version.IsPrerelease,
|
||||
FullString = version.ToFullString()
|
||||
};
|
||||
dbContext.PackageVersions.Add(pkgver);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
// existant en db mais pas sur le disque
|
||||
// TODO prise en charge de ce cas anormal
|
||||
}
|
||||
|
||||
logger.LogInformation($"new package : {nuspec.Name}");
|
||||
}
|
||||
}
|
||||
using (var shacrypto = System.Security.Cryptography.SHA512.Create())
|
||||
{
|
||||
using (var stream = System.IO.File.OpenRead(fullpath))
|
||||
{
|
||||
var hash = shacrypto.ComputeHash(stream);
|
||||
var shafullname = fullpath + ".sha512";
|
||||
var hashtext = Convert.ToBase64String(hash);
|
||||
var hashtextbytes = Encoding.ASCII.GetBytes(hashtext);
|
||||
|
||||
using (var shafile = System.IO.File.OpenWrite(shafullname))
|
||||
{
|
||||
shafile.Write(hashtextbytes, 0, hashtextbytes.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
nuspec.ExtractToFile(Path.Combine(pkgpath, pkgid + ".nuspec"));
|
||||
}
|
||||
|
||||
}
|
||||
return Ok(ViewData);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex.Message);
|
||||
logger.LogError("Stack Trace: "+ ex.StackTrace);
|
||||
return new ObjectResult(new { ViewData, ex.Message})
|
||||
{ StatusCode = 500 };
|
||||
}
|
||||
}
|
||||
// dotnet add . package -s http://localhost:5000/packages nuget-cli
|
||||
// packages/FindPackagesById()?id='nuget-cli'&semVerLevel=2.0.0
|
||||
[HttpGet("packages/FindPackagesById()")]
|
||||
public IActionResult Index(string id, string semVerLevel)
|
||||
|
||||
// Search
|
||||
// GET {@id}?q={QUERY}&skip={SKIP}&take={TAKE}&prerelease={PRERELEASE}&semVerLevel={SEMVERLEVEL}&packageType={PACKAGETYPE}
|
||||
|
||||
[HttpGet("~/search/index.json")]
|
||||
public IActionResult Index(
|
||||
string q,
|
||||
bool prerelease = false,
|
||||
string packageType = null,
|
||||
int skip = 0,
|
||||
int take = 25,
|
||||
string semVerLevel = "2.0.0")
|
||||
{
|
||||
if (string.IsNullOrEmpty(id))
|
||||
if (string.IsNullOrEmpty(q))
|
||||
{
|
||||
ViewData["msg"] = "no id";
|
||||
ModelState.AddModelError("q", "no value");
|
||||
return NotFound(ModelState);
|
||||
}
|
||||
else
|
||||
{
|
||||
ViewData["id"] = id;
|
||||
// TODO Assert valid sem ver spec
|
||||
var filelst = new DirectoryInfo(nugetSettings.PackagesRootDir);
|
||||
var lst = filelst.GetDirectories(id);
|
||||
ViewData["lst"] = lst.Select(entry => entry.Name);
|
||||
var scope = dbContext.Packages
|
||||
.Include(p => p.Versions)
|
||||
.Where(
|
||||
p => (CamelCaseMatch(p.Id, q) || SeparatedByMinusMatch(p.Id, q))
|
||||
&& (prerelease || p.Versions.Any(v => !v.IsPrerelease))
|
||||
&& (packageType == null || p.Versions.Any(v => v.Type == packageType))
|
||||
);
|
||||
var result = new {
|
||||
totalHits = scope.Count(),
|
||||
data = scope.Skip(skip).Take(take).ToArray()
|
||||
};
|
||||
return Ok(result);
|
||||
}
|
||||
return Ok(ViewData);
|
||||
}
|
||||
|
||||
|
||||
|
||||
[Authorize]
|
||||
[HttpGet("api/get-key/{*apikey}")]
|
||||
public IActionResult GetApiKey(string apiKey)
|
||||
protected static bool CamelCaseMatch(string id, string q)
|
||||
{
|
||||
return Ok(protector.Protect(apiKey));
|
||||
// Assert.False (q==null);
|
||||
string query = q;
|
||||
if (query.Length==0) return false;
|
||||
|
||||
while (id.Length > 0)
|
||||
{
|
||||
int i = 0;
|
||||
while (id.Length > i && char.IsLower(id[i])) i++;
|
||||
if (i==0) break;
|
||||
id = id.Substring(i);
|
||||
if (id.StartsWith(q, System.StringComparison.OrdinalIgnoreCase)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
protected static bool SeparatedByMinusMatch(string id, string q)
|
||||
{
|
||||
foreach (var part in id.Split('-'))
|
||||
{
|
||||
if (part.StartsWith(q, System.StringComparison.OrdinalIgnoreCase)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue