yavsc/Yavsc/Helpers/FileSystemHelpers.cs

94 lines
3.2 KiB
C#
Raw Normal View History

2016-11-14 12:17:07 +01:00
2016-05-17 18:22:18 +02:00
using System.IO;
2016-11-14 12:17:07 +01:00
using System.Linq;
2016-11-30 16:45:37 +01:00
using System.Net.Mime;
2016-11-14 12:17:07 +01:00
using System.Security.Claims;
2016-11-30 16:45:37 +01:00
using Microsoft.AspNet.Http;
using Yavsc.ApiControllers;
using Yavsc.Models;
using Yavsc.Models.FileSystem;
2016-11-14 12:17:07 +01:00
using Yavsc.ViewModels.UserFiles;
2016-05-17 18:22:18 +02:00
namespace Yavsc.Helpers
{
2016-11-30 16:45:37 +01:00
public static class FileSystemHelpers
{
public static UserDirectoryInfo GetUserFiles(this ClaimsPrincipal user, string subdir)
{
UserDirectoryInfo di = new UserDirectoryInfo(user.Identity.Name, subdir);
2016-09-05 00:24:43 +02:00
2016-11-14 12:17:07 +01:00
return di;
}
2016-11-30 16:45:37 +01:00
static char[] ValidChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_~.".ToCharArray();
2016-11-14 12:17:07 +01:00
public static bool IsValidDirectoryName(this string name)
2016-11-30 16:45:37 +01:00
{
return !name.Any(c => !ValidChars.Contains(c));
2016-11-14 12:17:07 +01:00
}
public static bool IsValidPath(this string path)
2016-11-30 16:45:37 +01:00
{
if (path == null) return true;
2016-11-14 12:17:07 +01:00
foreach (var name in path.Split(Path.DirectorySeparatorChar))
2016-11-30 16:45:37 +01:00
{
if (name != null)
2016-11-14 12:17:07 +01:00
if (!IsValidDirectoryName(name)
2016-11-30 16:45:37 +01:00
|| name.Equals(".."))
return false;
}
2016-11-14 12:17:07 +01:00
return true;
2016-05-17 18:22:18 +02:00
}
2016-11-30 16:45:37 +01:00
public static string InitPostToFileSystem(
this ClaimsPrincipal user,
string subpath)
{
var root = Path.Combine(Startup.UserFilesDirName, user.Identity.Name);
// TOSO secure this path
// if (subdir!=null) root = Path.Combine(root, subdir);
var diRoot = new DirectoryInfo(root);
if (!diRoot.Exists) diRoot.Create();
if (subpath != null)
if (subpath.IsValidPath())
{
root = Path.Combine(root, subpath);
diRoot = new DirectoryInfo(root);
if (!diRoot.Exists) diRoot.Create();
}
return root;
}
public static FileRecievedInfo ReceiveUserFile(this ApplicationUser user, string root, long quota, ref long usage, IFormFile f)
{
var item = new FileRecievedInfo();
// form-data; name="file"; filename="capt0008.jpg"
ContentDisposition contentDisposition = new ContentDisposition(f.ContentDisposition);
item.FileName = contentDisposition.FileName;
var fi = new FileInfo(Path.Combine(root, item.FileName));
if (fi.Exists) item.Overriden = true;
using (var dest = fi.OpenWrite())
{
using (var org = f.OpenReadStream())
{
byte[] buffer = new byte[1024];
long len = org.Length;
user.DiskUsage += len;
if (len > (quota - usage)) throw new FSQuotaException();
while (len > 0)
{
int blen = len > 1024 ? 1024 : (int)len;
org.Read(buffer, 0, blen);
dest.Write(buffer, 0, blen);
len -= blen;
}
dest.Close();
org.Close();
}
}
return item;
}
2016-05-17 18:22:18 +02:00
}
}