code guidelines

vnext
Paul Schneider 4 years ago
parent 7b529cd3e8
commit c907b387d7
82 changed files with 470 additions and 375 deletions

@ -5,7 +5,7 @@ namespace Yavsc.Attributes.Validation
public partial class YaStringLength: YaValidationAttribute public partial class YaStringLength: YaValidationAttribute
{ {
public long MinimumLength { get; set; } = 0; public long MinimumLength { get; set; } = 0;
private long maxLen; private readonly long maxLen;
public YaStringLength(long maxLen) : base( ()=> "BadStringLength") public YaStringLength(long maxLen) : base( ()=> "BadStringLength")
{ {
this.maxLen = maxLen; this.maxLen = maxLen;
@ -50,4 +50,4 @@ namespace Yavsc.Attributes.Validation
} }
} }
} }

@ -24,8 +24,7 @@ namespace Yavsc.Authentication
readonly Uri accessTokenUrl; readonly Uri accessTokenUrl;
readonly Uri redirectUrl; readonly Uri redirectUrl;
readonly GetUsernameAsyncFunc getUsernameAsync; readonly GetUsernameAsyncFunc getUsernameAsync;
readonly string requestState;
string requestState;
bool reportedForgery = false; bool reportedForgery = false;
/// <summary> /// <summary>

@ -2,7 +2,6 @@ namespace Yavsc.Abstract.FileSystem
{ {
public interface IFileRecievedInfo public interface IFileRecievedInfo
{ {
string MimeType { get; set; }
string DestDir { get; set; } string DestDir { get; set; }
@ -12,4 +11,4 @@ namespace Yavsc.Abstract.FileSystem
bool QuotaOffensed { get; set; } bool QuotaOffensed { get; set; }
} }
} }

@ -16,7 +16,7 @@ namespace Yavsc.ViewModels.UserFiles
public DirectoryShortInfo [] SubDirectories {  public DirectoryShortInfo [] SubDirectories { 
get; set; get; set;
} }
private DirectoryInfo dInfo; private readonly DirectoryInfo dInfo;
// for deserialization // for deserialization
public UserDirectoryInfo() public UserDirectoryInfo()

@ -30,14 +30,13 @@ namespace Yavsc.Models.FileSystem
public FileRecievedInfo() public FileRecievedInfo()
{ {
QuotaOffensed = Overriden = false; QuotaOffensed = Overriden = false;
MimeType = DestDir = FileName = null; DestDir = FileName = null;
} }
public string MimeType { get; set; }
public string DestDir { get; set; } public string DestDir { get; set; }
public string FileName { get; set; } public string FileName { get; set; }
public bool Overriden { get; set; } public bool Overriden { get; set; }
public bool QuotaOffensed { get; set; } public bool QuotaOffensed { get; set; }
} }
} }

@ -65,5 +65,17 @@ namespace Yavsc
/// <returns>the supported activity code</returns> /// <returns>the supported activity code</returns>
public string OnlyOneActivityCode { get; set; } public string OnlyOneActivityCode { get; set; }
/// <summary>
/// Disk usage user list maximum length in memory
/// </summary>
/// <value></value>
public int DUUserListLen { get; set; } = 256;
/// <summary>
/// Default acl file name
/// </summary>
/// <value></value>
public string AccessListFileName { get; set; } = ".access";
} }
} }

@ -16,7 +16,7 @@ namespace Yavsc.Controllers
public class BlogApiController : Controller public class BlogApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public BlogApiController(ApplicationDbContext context) public BlogApiController(ApplicationDbContext context)
{ {

@ -12,7 +12,7 @@ namespace Yavsc.Controllers
[Route("api/blogtags")] [Route("api/blogtags")]
public class BlogTagsApiController : Controller public class BlogTagsApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public BlogTagsApiController(ApplicationDbContext context) public BlogTagsApiController(ApplicationDbContext context)
{ {
@ -144,4 +144,4 @@ namespace Yavsc.Controllers
return _context.TagsDomain.Count(e => e.PostId == id) > 0; return _context.TagsDomain.Count(e => e.PostId == id) > 0;
} }
} }
} }

@ -14,7 +14,7 @@ namespace Yavsc.Controllers
[Route("api/blogcomments")] [Route("api/blogcomments")]
public class CommentsApiController : Controller public class CommentsApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public CommentsApiController(ApplicationDbContext context) public CommentsApiController(ApplicationDbContext context)
{ {
@ -158,4 +158,4 @@ namespace Yavsc.Controllers
return _context.Comment.Count(e => e.Id == id) > 0; return _context.Comment.Count(e => e.Id == id) > 0;
} }
} }
} }

@ -20,9 +20,9 @@ namespace Yavsc.ApiControllers
[Authorize,Route("api/fs")] [Authorize,Route("api/fs")]
public partial class FileSystemApiController : Controller public partial class FileSystemApiController : Controller
{ {
ApplicationDbContext dbContext; readonly ApplicationDbContext dbContext;
private IAuthorizationService AuthorizationService; private readonly IAuthorizationService AuthorizationService;
private ILogger _logger; private readonly ILogger _logger;
public FileSystemApiController(ApplicationDbContext context, public FileSystemApiController(ApplicationDbContext context,
IAuthorizationService authorizationService, IAuthorizationService authorizationService,

@ -25,15 +25,15 @@ namespace Yavsc.ApiControllers
[Route("api/bill"), Authorize] [Route("api/bill"), Authorize]
public class BillingController : Controller public class BillingController : Controller
{ {
ApplicationDbContext dbContext; readonly ApplicationDbContext dbContext;
private IStringLocalizer _localizer; private readonly IStringLocalizer _localizer;
private GoogleAuthSettings _googleSettings; private readonly GoogleAuthSettings _googleSettings;
private IYavscMessageSender _GCMSender; private readonly IYavscMessageSender _GCMSender;
private IAuthorizationService authorizationService; private readonly IAuthorizationService authorizationService;
private ILogger logger; private readonly ILogger logger;
private IBillingService billingService; private readonly IBillingService billingService;
public BillingController( public BillingController(
IAuthorizationService authorizationService, IAuthorizationService authorizationService,

@ -13,11 +13,11 @@ using Yavsc.Models.Billing;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
[Produces("application/json")] [Produces("application/json")]
[Route("api/estimate"),Authorize()] [Route("api/estimate"), Authorize()]
public class EstimateApiController : Controller public class EstimateApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
private ILogger _logger; private readonly ILogger _logger;
public EstimateApiController(ApplicationDbContext context, ILoggerFactory loggerFactory) public EstimateApiController(ApplicationDbContext context, ILoggerFactory loggerFactory)
{ {
_context = context; _context = context;
@ -28,21 +28,21 @@ namespace Yavsc.Controllers
if (User.IsInRole(Constants.AdminGroupName)) return true; if (User.IsInRole(Constants.AdminGroupName)) return true;
return uid == User.GetUserId(); return uid == User.GetUserId();
} }
bool UserIsAdminOrInThese (string oid, string uid) bool UserIsAdminOrInThese(string oid, string uid)
{ {
if (User.IsInRole(Constants.AdminGroupName)) return true; if (User.IsInRole(Constants.AdminGroupName)) return true;
var cuid = User.GetUserId(); var cuid = User.GetUserId();
return cuid == uid || cuid == oid; return cuid == uid || cuid == oid;
} }
// GET: api/Estimate{?ownerId=User.GetUserId()} // GET: api/Estimate{?ownerId=User.GetUserId()}
[HttpGet] [HttpGet]
public IActionResult GetEstimates(string ownerId=null) public IActionResult GetEstimates(string ownerId = null)
{ {
if ( ownerId == null ) ownerId = User.GetUserId(); if (ownerId == null) ownerId = User.GetUserId();
else if (!UserIsAdminOrThis(ownerId)) // throw new Exception("Not authorized") ; else if (!UserIsAdminOrThis(ownerId)) // throw new Exception("Not authorized") ;
// or just do nothing // or just do nothing
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden); return new HttpStatusCodeResult(StatusCodes.Status403Forbidden);
return Ok(_context.Estimates.Include(e=>e.Bill).Where(e=>e.OwnerId == ownerId)); return Ok(_context.Estimates.Include(e => e.Bill).Where(e => e.OwnerId == ownerId));
} }
// GET: api/Estimate/5 // GET: api/Estimate/5
[HttpGet("{id}", Name = "GetEstimate")] [HttpGet("{id}", Name = "GetEstimate")]
@ -53,20 +53,20 @@ namespace Yavsc.Controllers
return HttpBadRequest(ModelState); return HttpBadRequest(ModelState);
} }
Estimate estimate = _context.Estimates.Include(e=>e.Bill).Single(m => m.Id == id); Estimate estimate = _context.Estimates.Include(e => e.Bill).Single(m => m.Id == id);
if (estimate == null) if (estimate == null)
{ {
return HttpNotFound(); return HttpNotFound();
} }
if (UserIsAdminOrInThese(estimate.ClientId,estimate.OwnerId)) if (UserIsAdminOrInThese(estimate.ClientId, estimate.OwnerId))
return Ok(estimate); return Ok(estimate);
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden); return new HttpStatusCodeResult(StatusCodes.Status403Forbidden);
} }
// PUT: api/Estimate/5 // PUT: api/Estimate/5
[HttpPut("{id}"),Produces("application/json")] [HttpPut("{id}"), Produces("application/json")]
public IActionResult PutEstimate(long id, [FromBody] Estimate estimate) public IActionResult PutEstimate(long id, [FromBody] Estimate estimate)
{ {
@ -84,11 +84,11 @@ namespace Yavsc.Controllers
{ {
if (uid != estimate.OwnerId) if (uid != estimate.OwnerId)
{ {
ModelState.AddModelError("OwnerId","You can only modify your own estimates"); ModelState.AddModelError("OwnerId", "You can only modify your own estimates");
return HttpBadRequest(ModelState); return HttpBadRequest(ModelState);
} }
} }
var entry = _context.Attach(estimate); var entry = _context.Attach(estimate);
try try
{ {
@ -106,27 +106,30 @@ namespace Yavsc.Controllers
} }
} }
return Ok( new { Id = estimate.Id }); return Ok(new { estimate.Id });
} }
// POST: api/Estimate // POST: api/Estimate
[HttpPost,Produces("application/json")] [HttpPost, Produces("application/json")]
public IActionResult PostEstimate([FromBody] Estimate estimate) public IActionResult PostEstimate([FromBody] Estimate estimate)
{ {
var uid = User.GetUserId(); var uid = User.GetUserId();
if (estimate.OwnerId==null) estimate.OwnerId = uid; if (estimate.OwnerId == null) estimate.OwnerId = uid;
if (!User.IsInRole(Constants.AdminGroupName)) { if (!User.IsInRole(Constants.AdminGroupName))
{
if (uid != estimate.OwnerId) if (uid != estimate.OwnerId)
{ {
ModelState.AddModelError("OwnerId","You can only create your own estimates"); ModelState.AddModelError("OwnerId", "You can only create your own estimates");
return HttpBadRequest(ModelState); return HttpBadRequest(ModelState);
} }
} }
if (estimate.CommandId!=null) { if (estimate.CommandId != null)
{
var query = _context.RdvQueries.FirstOrDefault(q => q.Id == estimate.CommandId); var query = _context.RdvQueries.FirstOrDefault(q => q.Id == estimate.CommandId);
if (query == null) { if (query == null)
{
return HttpBadRequest(ModelState); return HttpBadRequest(ModelState);
} }
query.ValidationDate = DateTime.Now; query.ValidationDate = DateTime.Now;
@ -136,18 +139,18 @@ namespace Yavsc.Controllers
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
_logger.LogError(JsonConvert.SerializeObject(ModelState)); _logger.LogError(JsonConvert.SerializeObject(ModelState));
return Json(ModelState); return Json(ModelState);
} }
_context.Estimates.Add(estimate); _context.Estimates.Add(estimate);
/* _context.AttachRange(estimate.Bill); /* _context.AttachRange(estimate.Bill);
_context.Attach(estimate); _context.Attach(estimate);
_context.Entry(estimate).State = EntityState.Added; _context.Entry(estimate).State = EntityState.Added;
foreach (var line in estimate.Bill) foreach (var line in estimate.Bill)
_context.Entry(line).State = EntityState.Added; _context.Entry(line).State = EntityState.Added;
// foreach (var l in estimate.Bill) _context.Attach<CommandLine>(l); // foreach (var l in estimate.Bill) _context.Attach<CommandLine>(l);
*/ */
try try
{ {
_context.SaveChanges(User.GetUserId()); _context.SaveChanges(User.GetUserId());
@ -163,7 +166,7 @@ namespace Yavsc.Controllers
throw; throw;
} }
} }
return Ok( new { Id = estimate.Id, Bill = estimate.Bill }); return Ok(new { estimate.Id, estimate.Bill });
} }
// DELETE: api/Estimate/5 // DELETE: api/Estimate/5
@ -175,8 +178,8 @@ namespace Yavsc.Controllers
return HttpBadRequest(ModelState); return HttpBadRequest(ModelState);
} }
Estimate estimate = _context.Estimates.Include(e=>e.Bill).Single(m => m.Id == id); Estimate estimate = _context.Estimates.Include(e => e.Bill).Single(m => m.Id == id);
if (estimate == null) if (estimate == null)
{ {
return HttpNotFound(); return HttpNotFound();
@ -186,7 +189,7 @@ namespace Yavsc.Controllers
{ {
if (uid != estimate.OwnerId) if (uid != estimate.OwnerId)
{ {
ModelState.AddModelError("OwnerId","You can only create your own estimates"); ModelState.AddModelError("OwnerId", "You can only create your own estimates");
return HttpBadRequest(ModelState); return HttpBadRequest(ModelState);
} }
} }
@ -195,8 +198,8 @@ namespace Yavsc.Controllers
return Ok(estimate); return Ok(estimate);
} }
protected override void Dispose (bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing) if (disposing)
{ {
@ -210,4 +213,4 @@ namespace Yavsc.Controllers
return _context.Estimates.Count(e => e.Id == id) > 0; return _context.Estimates.Count(e => e.Id == id) > 0;
} }
} }
} }

@ -9,9 +9,10 @@ using Yavsc.ViewModels.FrontOffice;
namespace Yavsc.ApiControllers namespace Yavsc.ApiControllers
{ {
[Route("api/front")] [Route("api/front")]
public class FrontOfficeApiController: Controller public class FrontOfficeApiController : Controller
{ {
ApplicationDbContext dbContext; ApplicationDbContext dbContext;
private IBillingService billing; private IBillingService billing;
public FrontOfficeApiController(ApplicationDbContext context, IBillingService billing) public FrontOfficeApiController(ApplicationDbContext context, IBillingService billing)
@ -20,19 +21,19 @@ namespace Yavsc.ApiControllers
this.billing = billing; this.billing = billing;
} }
[HttpGet("profiles/{actCode}")] [HttpGet("profiles/{actCode}")]
IEnumerable<PerformerProfileViewModel> Profiles (string actCode) IEnumerable<PerformerProfileViewModel> Profiles(string actCode)
{ {
return dbContext.ListPerformers(billing, actCode); return dbContext.ListPerformers(billing, actCode);
} }
[HttpPost("query/reject")] [HttpPost("query/reject")]
public IActionResult RejectQuery (string billingCode, long queryId) public IActionResult RejectQuery(string billingCode, long queryId)
{ {
if (billingCode==null) return HttpBadRequest("billingCode"); if (billingCode == null) return HttpBadRequest("billingCode");
if (queryId==0) return HttpBadRequest("queryId"); if (queryId == 0) return HttpBadRequest("queryId");
var billing = BillingService.GetBillable(dbContext, billingCode, queryId); var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing==null) return HttpBadRequest(); if (billing == null) return HttpBadRequest();
billing.Rejected = true; billing.Rejected = true;
billing.RejectedAt = DateTime.Now; billing.RejectedAt = DateTime.Now;
dbContext.SaveChanges(); dbContext.SaveChanges();

@ -11,8 +11,8 @@ namespace Yavsc.ApiControllers
[Route("api/payment")] [Route("api/payment")]
public class PaymentApiController : Controller public class PaymentApiController : Controller
{ {
private ApplicationDbContext dbContext; private readonly ApplicationDbContext dbContext;
private SiteSettings siteSettings; private readonly SiteSettings siteSettings;
private readonly ILogger _logger; private readonly ILogger _logger;
public PaymentApiController( public PaymentApiController(
ApplicationDbContext dbContext, ApplicationDbContext dbContext,

@ -16,7 +16,7 @@ namespace Yavsc.Controllers
public class PerformersApiController : Controller public class PerformersApiController : Controller
{ {
ApplicationDbContext dbContext; ApplicationDbContext dbContext;
private IBillingService billing; private readonly IBillingService billing;
public PerformersApiController(ApplicationDbContext context, IBillingService billing) public PerformersApiController(ApplicationDbContext context, IBillingService billing)
{ {

@ -14,7 +14,7 @@ namespace Yavsc.Controllers
[Route("api/ProductApi")] [Route("api/ProductApi")]
public class ProductApiController : Controller public class ProductApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public ProductApiController(ApplicationDbContext context) public ProductApiController(ApplicationDbContext context)
{ {
@ -146,4 +146,4 @@ namespace Yavsc.Controllers
return _context.Products.Count(e => e.Id == id) > 0; return _context.Products.Count(e => e.Id == id) > 0;
} }
} }
} }

@ -15,7 +15,7 @@ namespace Yavsc.Controllers
[Route("api/dimiss")] [Route("api/dimiss")]
public class DimissClicksApiController : Controller public class DimissClicksApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public DimissClicksApiController(ApplicationDbContext context) public DimissClicksApiController(ApplicationDbContext context)
{ {
@ -174,4 +174,4 @@ namespace Yavsc.Controllers
return _context.DimissClicked.Count(e => e.UserId == id) > 0; return _context.DimissClicked.Count(e => e.UserId == id) > 0;
} }
} }
} }

@ -16,7 +16,7 @@ namespace Yavsc.Controllers
[Authorize] [Authorize]
public class FileCircleApiController : Controller public class FileCircleApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public FileCircleApiController(ApplicationDbContext context) public FileCircleApiController(ApplicationDbContext context)
{ {
@ -185,4 +185,4 @@ namespace Yavsc.Controllers
return _context.CircleAuthorizationToFile.Count(e => e.CircleId == id) > 0; return _context.CircleAuthorizationToFile.Count(e => e.CircleId == id) > 0;
} }
} }
} }

@ -14,7 +14,7 @@ namespace Yavsc.Controllers
[Route("api/bursherprofiles")] [Route("api/bursherprofiles")]
public class BursherProfilesApiController : Controller public class BursherProfilesApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public BursherProfilesApiController(ApplicationDbContext context) public BursherProfilesApiController(ApplicationDbContext context)
{ {

@ -26,37 +26,12 @@ namespace Yavsc.ApiControllers
[Route("api/haircut")] [Route("api/haircut")]
public class HairCutController : Controller public class HairCutController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
private IEmailSender _emailSender; private readonly ILogger _logger;
private IYavscMessageSender _GCMSender;
private GoogleAuthSettings _googleSettings;
private IStringLocalizer<YavscLocalisation> _localizer;
private ILogger _logger;
private SiteSettings _siteSettings;
private SmtpSettings _smtpSettings;
private UserManager<ApplicationUser> _userManager;
PayPalSettings _paymentSettings;
public HairCutController(ApplicationDbContext context, public HairCutController(ApplicationDbContext context,
IOptions<GoogleAuthSettings> googleSettings,
IYavscMessageSender GCMSender,
UserManager<ApplicationUser> userManager,
IStringLocalizer<Yavsc.YavscLocalisation> localizer,
IEmailSender emailSender,
IOptions<SmtpSettings> smtpSettings,
IOptions<SiteSettings> siteSettings,
IOptions<PayPalSettings> payPalSettings,
ILoggerFactory loggerFactory) ILoggerFactory loggerFactory)
{ {
_context = context; _context = context;
_GCMSender = GCMSender;
_emailSender = emailSender;
_googleSettings = googleSettings.Value;
_userManager = userManager;
_smtpSettings = smtpSettings.Value;
_siteSettings = siteSettings.Value;
_paymentSettings = payPalSettings.Value;
_localizer = localizer;
_logger = loggerFactory.CreateLogger<HairCutController>(); _logger = loggerFactory.CreateLogger<HairCutController>();
} }

@ -5,8 +5,8 @@ namespace Yavsc.ApiControllers
public class DjProfileApiController : ProfileApiController<DjSettings> public class DjProfileApiController : ProfileApiController<DjSettings>
{ {
public DjProfileApiController(ApplicationDbContext context) : base(context) public DjProfileApiController() : base()
{ {
} }
} }
} }

@ -13,7 +13,7 @@ namespace Yavsc.Controllers
[Route("api/museprefs")] [Route("api/museprefs")]
public class MusicalPreferencesApiController : Controller public class MusicalPreferencesApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public MusicalPreferencesApiController(ApplicationDbContext context) public MusicalPreferencesApiController(ApplicationDbContext context)
{ {

@ -13,7 +13,7 @@ namespace Yavsc.Controllers
[Route("api/MusicalTendenciesApi")] [Route("api/MusicalTendenciesApi")]
public class MusicalTendenciesApiController : Controller public class MusicalTendenciesApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public MusicalTendenciesApiController(ApplicationDbContext context) public MusicalTendenciesApiController(ApplicationDbContext context)
{ {
@ -145,4 +145,4 @@ namespace Yavsc.Controllers
return _context.MusicalTendency.Count(e => e.Id == id) > 0; return _context.MusicalTendency.Count(e => e.Id == id) > 0;
} }
} }
} }

@ -11,8 +11,8 @@ using Yavsc.Models.Identity;
[Authorize, Route("~/api/gcm")] [Authorize, Route("~/api/gcm")]
public class NativeConfidentialController : Controller public class NativeConfidentialController : Controller
{ {
ILogger _logger; readonly ILogger _logger;
ApplicationDbContext _context; readonly ApplicationDbContext _context;
public NativeConfidentialController(ApplicationDbContext context, public NativeConfidentialController(ApplicationDbContext context,
ILoggerFactory loggerFactory) ILoggerFactory loggerFactory)

@ -10,7 +10,7 @@ namespace Yavsc.Controllers
[Route("~/api/PostRateApi")] [Route("~/api/PostRateApi")]
public class PostRateApiController : Controller public class PostRateApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public PostRateApiController(ApplicationDbContext context) public PostRateApiController(ApplicationDbContext context)
{ {

@ -9,12 +9,9 @@ namespace Yavsc.ApiControllers
/// </summary> /// </summary>
[Produces("application/json"),Route("api/profile")] [Produces("application/json"),Route("api/profile")]
public abstract class ProfileApiController<T> : Controller public abstract class ProfileApiController<T> : Controller
{ { public ProfileApiController()
ApplicationDbContext dbContext;
public ProfileApiController(ApplicationDbContext context)
{ {
dbContext = context;
} }
} }
} }

@ -14,7 +14,7 @@ namespace Yavsc.Controllers
[Route("api/blacklist"), Authorize] [Route("api/blacklist"), Authorize]
public class BlackListApiController : Controller public class BlackListApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public BlackListApiController(ApplicationDbContext context) public BlackListApiController(ApplicationDbContext context)
{ {
@ -162,4 +162,4 @@ namespace Yavsc.Controllers
return _context.BlackListed.Count(e => e.Id == id) > 0; return _context.BlackListed.Count(e => e.Id == id) > 0;
} }
} }
} }

@ -14,7 +14,7 @@ namespace Yavsc.Controllers
[Route("api/blogacl")] [Route("api/blogacl")]
public class BlogAclApiController : Controller public class BlogAclApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public BlogAclApiController(ApplicationDbContext context) public BlogAclApiController(ApplicationDbContext context)
{ {
@ -164,4 +164,4 @@ namespace Yavsc.Controllers
return _context.CircleAuthorizationToBlogPost.Count(e => e.CircleId == id) > 0; return _context.CircleAuthorizationToBlogPost.Count(e => e.CircleId == id) > 0;
} }
} }
} }

@ -15,9 +15,9 @@ namespace Yavsc.Controllers
[Route("api/chat")] [Route("api/chat")]
public class ChatApiController : Controller public class ChatApiController : Controller
{ {
ApplicationDbContext dbContext; readonly ApplicationDbContext dbContext;
UserManager<ApplicationUser> userManager; readonly UserManager<ApplicationUser> userManager;
private IConnexionManager _cxManager; private readonly IConnexionManager _cxManager;
public ChatApiController(ApplicationDbContext dbContext, public ChatApiController(ApplicationDbContext dbContext,
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,
IConnexionManager cxManager) IConnexionManager cxManager)

@ -15,7 +15,7 @@ namespace Yavsc.Controllers
[Route("api/ChatRoomAccessApi")] [Route("api/ChatRoomAccessApi")]
public class ChatRoomAccessApiController : Controller public class ChatRoomAccessApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public ChatRoomAccessApiController(ApplicationDbContext context) public ChatRoomAccessApiController(ApplicationDbContext context)
{ {
@ -183,4 +183,4 @@ namespace Yavsc.Controllers
return _context.ChatRoomAccess.Count(e => e.ChannelName == id) > 0; return _context.ChatRoomAccess.Count(e => e.ChannelName == id) > 0;
} }
} }
} }

@ -14,7 +14,7 @@ namespace Yavsc.Controllers
[Route("api/ChatRoomApi")] [Route("api/ChatRoomApi")]
public class ChatRoomApiController : Controller public class ChatRoomApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public ChatRoomApiController(ApplicationDbContext context) public ChatRoomApiController(ApplicationDbContext context)
{ {
@ -164,4 +164,4 @@ namespace Yavsc.Controllers
return _context.ChatRoom.Count(e => e.Name == id) > 0; return _context.ChatRoom.Count(e => e.Name == id) > 0;
} }
} }
} }

@ -14,7 +14,7 @@ namespace Yavsc.Controllers
[Route("api/cirle")] [Route("api/cirle")]
public class CircleApiController : Controller public class CircleApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public CircleApiController(ApplicationDbContext context) public CircleApiController(ApplicationDbContext context)
{ {
@ -146,4 +146,4 @@ namespace Yavsc.Controllers
return _context.Circle.Count(e => e.Id == id) > 0; return _context.Circle.Count(e => e.Id == id) > 0;
} }
} }
} }

@ -12,7 +12,7 @@ namespace Yavsc.Controllers
[Route("api/ContactsApi")] [Route("api/ContactsApi")]
public class ContactsApiController : Controller public class ContactsApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public ContactsApiController(ApplicationDbContext context) public ContactsApiController(ApplicationDbContext context)
{ {
@ -125,4 +125,4 @@ namespace Yavsc.Controllers
return _context.ClientProviderInfo.Count(e => e.UserId == id) > 0; return _context.ClientProviderInfo.Count(e => e.UserId == id) > 0;
} }
} }
} }

@ -14,7 +14,7 @@ namespace Yavsc.Controllers
[Route("api/ServiceApi")] [Route("api/ServiceApi")]
public class ServiceApiController : Controller public class ServiceApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public ServiceApiController(ApplicationDbContext context) public ServiceApiController(ApplicationDbContext context)
{ {
@ -146,4 +146,4 @@ namespace Yavsc.Controllers
return _context.Services.Count(e => e.Id == id) > 0; return _context.Services.Count(e => e.Id == id) > 0;
} }
} }
} }

@ -22,9 +22,8 @@ namespace Yavsc.WebApi.Controllers
private UserManager<ApplicationUser> _userManager; private UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager; private readonly SignInManager<ApplicationUser> _signInManager;
readonly ApplicationDbContext _dbContext;
ApplicationDbContext _dbContext; private readonly ILogger _logger;
private ILogger _logger;
public ApiAccountController(UserManager<ApplicationUser> userManager, public ApiAccountController(UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager, ILoggerFactory loggerFactory, ApplicationDbContext dbContext) SignInManager<ApplicationUser> signInManager, ILoggerFactory loggerFactory, ApplicationDbContext dbContext)

@ -14,7 +14,7 @@ namespace Yavsc.Controllers
[Route("api/users")] [Route("api/users")]
public class ApplicationUserApiController : Controller public class ApplicationUserApiController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public ApplicationUserApiController(ApplicationDbContext context) public ApplicationUserApiController(ApplicationDbContext context)
{ {

@ -11,8 +11,8 @@ namespace Yavsc.ApiControllers.accounting
[Route("~/api/profile")] [Route("~/api/profile")]
public class ProfileApiController: Controller public class ProfileApiController: Controller
{ {
UserManager<ApplicationUser> _userManager; readonly UserManager<ApplicationUser> _userManager;
ApplicationDbContext _dbContext; readonly ApplicationDbContext _dbContext;
public ProfileApiController(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager) public ProfileApiController(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
@ -36,4 +36,4 @@ namespace Yavsc.ApiControllers.accounting
.Take(10).ToArray(); .Take(10).ToArray();
} }
} }
} }

@ -16,7 +16,6 @@ namespace Yavsc.Auth
/// </summary> /// </summary>
public class GoogleMiddleware : OAuthMiddleware<YavscGoogleOptions> public class GoogleMiddleware : OAuthMiddleware<YavscGoogleOptions>
{ {
private readonly RequestDelegate _next;
private readonly ILogger _logger; private readonly ILogger _logger;
/// <summary> /// <summary>
@ -37,11 +36,6 @@ namespace Yavsc.Auth
YavscGoogleOptions options) YavscGoogleOptions options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options) : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
_next = next;
if (dataProtectionProvider == null) if (dataProtectionProvider == null)
{ {

@ -12,10 +12,8 @@ namespace Yavsc.Auth
public class MonoJwtSecurityTokenHandler : JwtSecurityTokenHandler public class MonoJwtSecurityTokenHandler : JwtSecurityTokenHandler
{ {
MonoDataProtectionProvider protectionProvider; public MonoJwtSecurityTokenHandler()
public MonoJwtSecurityTokenHandler(MonoDataProtectionProvider prpro)
{ {
protectionProvider = prpro;
} }
public override JwtSecurityToken CreateToken( public override JwtSecurityToken CreateToken(
string issuer, string issuer,
@ -39,4 +37,4 @@ namespace Yavsc.Auth
} }
} }
} }

@ -10,11 +10,6 @@ namespace Yavsc.Auth {
public class UserTokenProvider : Microsoft.AspNet.Identity.IUserTokenProvider<ApplicationUser> public class UserTokenProvider : Microsoft.AspNet.Identity.IUserTokenProvider<ApplicationUser>
{ {
private MonoDataProtector protector=null;
public MonoDataProtector Protector {
get { return protector; }
}
public Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<ApplicationUser> manager, ApplicationUser user) public Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<ApplicationUser> manager, ApplicationUser user)
{ {
return Task.FromResult(true); return Task.FromResult(true);

@ -9,7 +9,7 @@ namespace Yavsc.Auth {
public class MonoXmlEncryptor : IXmlEncryptor public class MonoXmlEncryptor : IXmlEncryptor
{ {
public MonoXmlEncryptor (IServiceProvider serviceProvider) public MonoXmlEncryptor ()
{ {
} }
public EncryptedXmlInfo Encrypt(XElement plaintextElement) public EncryptedXmlInfo Encrypt(XElement plaintextElement)
@ -20,4 +20,4 @@ namespace Yavsc.Auth {
} }
} }
} }

@ -69,7 +69,7 @@ namespace Yavsc.Controllers
[Authorize(Roles = Constants.AdminGroupName)] [Authorize(Roles = Constants.AdminGroupName)]
public IActionResult Index(string page, string len) public IActionResult Index()
{ {
return View(); return View();
} }
@ -591,7 +591,7 @@ namespace Yavsc.Controllers
// GET: /Account/ResetPassword // GET: /Account/ResetPassword
[HttpGet] [HttpGet]
[AllowAnonymous] [AllowAnonymous]
public async Task<IActionResult> ResetPassword(string UserId, string code = null) public async Task<IActionResult> ResetPassword(string UserId)
{ {
var user = await _userManager.FindByIdAsync(UserId); var user = await _userManager.FindByIdAsync(UserId);
if (user==null) return new BadRequestResult(); if (user==null) return new BadRequestResult();

@ -195,9 +195,9 @@ namespace Yavsc.Controllers
// Generate the token and send it // Generate the token and send it
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
// TODO await _smsSender.SendSmsAsync(_twilioSettings, model.PhoneNumber, "Your security code is: " + code); // TODO ? await _smsSender.SendSmsAsync(_twilioSettings, model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber }); return RedirectToAction(nameof(VerifyPhoneNumber), new { model.PhoneNumber });
} }
// //

@ -20,25 +20,12 @@ namespace Yavsc.Controllers
[AllowAnonymous] [AllowAnonymous]
public class OAuthController : Controller public class OAuthController : Controller
{ {
readonly ApplicationDbContext _context;
readonly UserManager<ApplicationUser> _userManager;
readonly SiteSettings _siteSettings;
readonly ILogger _logger; readonly ILogger _logger;
private readonly SignInManager<ApplicationUser> _signInManager;
public OAuthController(ApplicationDbContext context, SignInManager<ApplicationUser> signInManager, IKeyManager keyManager, public OAuthController(ILoggerFactory loggerFactory)
UserManager<ApplicationUser> userManager,
IOptions<SiteSettings> siteSettings,
ILoggerFactory loggerFactory
)
{ {
_siteSettings = siteSettings.Value;
_context = context;
_signInManager = signInManager;
_userManager = userManager;
_logger = loggerFactory.CreateLogger<OAuthController>(); _logger = loggerFactory.CreateLogger<OAuthController>();
} }
[HttpGet("~/api/getclaims"), Produces("application/json")] [HttpGet("~/api/getclaims"), Produces("application/json")]

@ -13,10 +13,9 @@ namespace Yavsc.Controllers
{ {
public class AnnouncesController : Controller public class AnnouncesController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
IStringLocalizer<AnnouncesController> _localizer; readonly IStringLocalizer<AnnouncesController> _localizer;
readonly IAuthorizationService _authorizationService;
IAuthorizationService _authorizationService;
public AnnouncesController(ApplicationDbContext context, public AnnouncesController(ApplicationDbContext context,
IAuthorizationService authorizationService, IAuthorizationService authorizationService,
@ -61,9 +60,7 @@ namespace Yavsc.Controllers
{ {
ViewBag.IsAdmin = User.IsInRole(Constants.AdminGroupName); ViewBag.IsAdmin = User.IsInRole(Constants.AdminGroupName);
ViewBag.IsPerformer = User.IsInRole(Constants.PerformerGroupName); ViewBag.IsPerformer = User.IsInRole(Constants.PerformerGroupName);
ViewBag.AllowEdit = (announce!=null && announce.Id>0) ? ViewBag.AllowEdit = announce==null || announce.Id<=0 || await _authorizationService.AuthorizeAsync(User,announce,new EditRequirement());
await _authorizationService.AuthorizeAsync(User,announce,new EditRequirement()) :
true;
List<SelectListItem> dl = new List<SelectListItem>(); List<SelectListItem> dl = new List<SelectListItem>();
var rnames = System.Enum.GetNames(typeof(Reason)); var rnames = System.Enum.GetNames(typeof(Reason));
var rvalues = System.Enum.GetValues(typeof(Reason)); var rvalues = System.Enum.GetValues(typeof(Reason));

@ -40,7 +40,7 @@ namespace Yavsc.Controllers
// GET: Blog // GET: Blog
[AllowAnonymous] [AllowAnonymous]
public async Task<IActionResult> Index(string id, int skip=0, int maxLen=25) public async Task<IActionResult> Index(string id)
{ {
if (!string.IsNullOrEmpty(id)) { if (!string.IsNullOrEmpty(id)) {
return await UserPosts(id); return await UserPosts(id);

@ -11,7 +11,7 @@ namespace Yavsc.Controllers
{ {
public class CoWorkingController : Controller public class CoWorkingController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public CoWorkingController(ApplicationDbContext context) public CoWorkingController(ApplicationDbContext context)
{ {

@ -90,7 +90,7 @@ namespace Yavsc.Controllers
/// <param name="id"></param> /// <param name="id"></param>
/// <returns></returns> /// <returns></returns>
[HttpGet] [HttpGet]
public IActionResult Create(string proId, string activityCode, string billingCode) public IActionResult Create(string proId, string activityCode)
{ {
if (string.IsNullOrWhiteSpace(proId)) if (string.IsNullOrWhiteSpace(proId))
throw new InvalidOperationException( throw new InvalidOperationException(
@ -159,7 +159,7 @@ namespace Yavsc.Controllers
_context.RdvQueries.Add(command, GraphBehavior.IncludeDependents); _context.RdvQueries.Add(command, GraphBehavior.IncludeDependents);
_context.SaveChanges(User.GetUserId()); _context.SaveChanges(User.GetUserId());
var yaev = command.CreateEvent(_localizer, "NewCommand"); var yaev = command.CreateEvent("NewCommand");
MessageWithPayloadResponse nrep = null; MessageWithPayloadResponse nrep = null;

@ -11,7 +11,7 @@ namespace Yavsc.Controllers
{ {
public class CommandFormsController : Controller public class CommandFormsController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public CommandFormsController(ApplicationDbContext context) public CommandFormsController(ApplicationDbContext context)
{ {

@ -8,7 +8,7 @@ namespace Yavsc.Controllers
{ {
public class DjSettingsController : Controller public class DjSettingsController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public DjSettingsController(ApplicationDbContext context) public DjSettingsController(ApplicationDbContext context)
{ {

@ -21,10 +21,9 @@ namespace Yavsc.Controllers
[Authorize] [Authorize]
public class EstimateController : Controller public class EstimateController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
private SiteSettings _site; private readonly SiteSettings _site;
readonly IAuthorizationService authorizationService;
IAuthorizationService authorizationService;
public EstimateController(ApplicationDbContext context, IAuthorizationService authorizationService, IOptions<SiteSettings> siteSettings) public EstimateController(ApplicationDbContext context, IAuthorizationService authorizationService, IOptions<SiteSettings> siteSettings)
{ {
@ -143,10 +142,6 @@ namespace Yavsc.Controllers
} }
private void Save(ICollection<IFormFile> newGraphics,
ICollection<IFormFile> newFiles) {
}
// GET: Estimate/Edit/5 // GET: Estimate/Edit/5
public IActionResult Edit(long? id) public IActionResult Edit(long? id)
{ {

@ -9,7 +9,7 @@ namespace Yavsc.Controllers
{ {
public class FormsController : Controller public class FormsController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public FormsController(ApplicationDbContext context) public FormsController(ApplicationDbContext context)
{ {

@ -18,13 +18,11 @@ namespace Yavsc.Controllers
public class FrontOfficeController : Controller public class FrontOfficeController : Controller
{ {
ApplicationDbContext _context; readonly ApplicationDbContext _context;
UserManager<ApplicationUser> _userManager; readonly UserManager<ApplicationUser> _userManager;
readonly ILogger _logger;
ILogger _logger; readonly IStringLocalizer _SR;
private readonly IBillingService _billing;
IStringLocalizer _SR;
private IBillingService _billing;
public FrontOfficeController(ApplicationDbContext context, public FrontOfficeController(ApplicationDbContext context,
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,

@ -8,7 +8,7 @@ namespace Yavsc.Controllers
{ {
public class GeneralSettingsController : Controller public class GeneralSettingsController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public GeneralSettingsController(ApplicationDbContext context) public GeneralSettingsController(ApplicationDbContext context)
{ {

@ -8,7 +8,7 @@ namespace Yavsc.Controllers
using Models.Musical; using Models.Musical;
public class MusicalTendenciesController : Controller public class MusicalTendenciesController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public MusicalTendenciesController(ApplicationDbContext context) public MusicalTendenciesController(ApplicationDbContext context)
{ {

@ -10,7 +10,7 @@ namespace Yavsc.Controllers
[Authorize(Roles="Administrator")] [Authorize(Roles="Administrator")]
public class SIRENExceptionsController : Controller public class SIRENExceptionsController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public SIRENExceptionsController(ApplicationDbContext context) public SIRENExceptionsController(ApplicationDbContext context)
{ {

@ -6,10 +6,8 @@ namespace Yavsc.Controllers
{ {
public class FileSystemController : Controller public class FileSystemController : Controller
{ {
ILogger _logger; public FileSystemController()
public FileSystemController(ILoggerFactory loggerFactory)
{ {
_logger = loggerFactory.CreateLogger<FileSystemController>();
} }
public IActionResult Index(string subdir="") public IActionResult Index(string subdir="")
@ -21,4 +19,4 @@ namespace Yavsc.Controllers
return View(files); return View(files);
} }
} }
} }

@ -9,7 +9,7 @@ namespace Yavsc.Controllers
{ {
public class ColorsController : Controller public class ColorsController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public ColorsController(ApplicationDbContext context) public ColorsController(ApplicationDbContext context)
{ {

@ -29,6 +29,7 @@ namespace Yavsc.Controllers
public class HairCutCommandController : CommandController public class HairCutCommandController : CommandController
{ {
readonly PayPalSettings payPalSettings;
public HairCutCommandController(ApplicationDbContext context, public HairCutCommandController(ApplicationDbContext context,
IOptions<PayPalSettings> payPalSettings, IOptions<PayPalSettings> payPalSettings,
IOptions<GoogleAuthSettings> googleSettings, IOptions<GoogleAuthSettings> googleSettings,
@ -44,7 +45,7 @@ namespace Yavsc.Controllers
{ {
this.payPalSettings = payPalSettings.Value; this.payPalSettings = payPalSettings.Value;
} }
PayPalSettings payPalSettings;
private async Task<HairCutQuery> GetQuery(long id) private async Task<HairCutQuery> GetQuery(long id)
{ {

@ -8,7 +8,7 @@ namespace Yavsc.Controllers
{ {
public class HairPrestationsController : Controller public class HairPrestationsController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public HairPrestationsController(ApplicationDbContext context) public HairPrestationsController(ApplicationDbContext context)
{ {

@ -12,7 +12,7 @@ namespace Yavsc.Controllers
[Authorize("AdministratorOnly")] [Authorize("AdministratorOnly")]
public class HairTaintsController : Controller public class HairTaintsController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public HairTaintsController(ApplicationDbContext context) public HairTaintsController(ApplicationDbContext context)
{ {

@ -21,22 +21,19 @@ namespace Yavsc.Controllers
[AllowAnonymous] [AllowAnonymous]
public class HomeController : Controller public class HomeController : Controller
{ {
IHostingEnvironment _hosting; readonly ApplicationDbContext _dbContext;
ApplicationDbContext _dbContext;
readonly IHtmlLocalizer _localizer; readonly IHtmlLocalizer _localizer;
public HomeController(IHtmlLocalizer<Startup> localizer, IHostingEnvironment hosting, public HomeController(IHtmlLocalizer<Startup> localizer,
ApplicationDbContext context, UserManager<ApplicationUser> userManager) ApplicationDbContext context)
{ {
_localizer = localizer; _localizer = localizer;
_hosting = hosting;
_dbContext = context; _dbContext = context;
} }
public async Task<IActionResult> Index(string id) public async Task<IActionResult> Index(string id)
{ {
ViewBag.IsFromSecureProx = (Request.Headers.ContainsKey(Constants.SshHeaderKey)) ? Request.Headers[Constants.SshHeaderKey] == "on" : false; ViewBag.IsFromSecureProx = Request.Headers.ContainsKey(Constants.SshHeaderKey) && Request.Headers[Constants.SshHeaderKey] == "on";
ViewBag.SecureHomeUrl = "https://" + Request.Headers["X-Forwarded-Host"]; ViewBag.SecureHomeUrl = "https://" + Request.Headers["X-Forwarded-Host"];
ViewBag.SshHeaderKey = Request.Headers[Constants.SshHeaderKey]; ViewBag.SshHeaderKey = Request.Headers[Constants.SshHeaderKey];
var uid = User.GetUserId(); var uid = User.GetUserId();

@ -14,7 +14,7 @@ namespace Yavsc.Controllers
[Authorize("AdministratorOnly")] [Authorize("AdministratorOnly")]
public class GitController : Controller public class GitController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public GitController(ApplicationDbContext context) public GitController(ApplicationDbContext context)
{ {

@ -17,13 +17,11 @@ namespace Yavsc.Controllers
[Authorize("AdministratorOnly")] [Authorize("AdministratorOnly")]
public class ProjectController : Controller public class ProjectController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
ILogger _logger; readonly IStringLocalizer<Yavsc.YavscLocalisation> _localizer;
IStringLocalizer<Yavsc.YavscLocalisation> _localizer; readonly IStringLocalizer<BugController> _bugLocalizer;
IStringLocalizer<BugController> _bugLocalizer;
public ProjectController(ApplicationDbContext context, public ProjectController(ApplicationDbContext context,
ILoggerFactory loggerFactory,
IStringLocalizer<Yavsc.YavscLocalisation> localizer, IStringLocalizer<Yavsc.YavscLocalisation> localizer,
IStringLocalizer<BugController> bugLocalizer IStringLocalizer<BugController> bugLocalizer
) )
@ -31,14 +29,11 @@ namespace Yavsc.Controllers
_context = context; _context = context;
_localizer = localizer; _localizer = localizer;
_bugLocalizer = bugLocalizer; _bugLocalizer = bugLocalizer;
_logger = loggerFactory.CreateLogger<ProjectController>();
} }
// GET: Project // GET: Project
public async Task<IActionResult> Index() public async Task<IActionResult> Index()
{ {
var applicationDbContext = _context.Project.Include(p => p.Client).Include(p => p.Context).Include(p => p.PerformerProfile).Include(p => p.Regularisation).Include(p => p.Repository); var applicationDbContext = _context.Project.Include(p => p.Client).Include(p => p.Context).Include(p => p.PerformerProfile).Include(p => p.Regularisation).Include(p => p.Repository);
return View(await applicationDbContext.ToListAsync()); return View(await applicationDbContext.ToListAsync());
} }

@ -12,7 +12,7 @@ namespace Yavsc.Controllers
{ {
public class InstrumentRatingController : Controller public class InstrumentRatingController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public InstrumentRatingController(ApplicationDbContext context) public InstrumentRatingController(ApplicationDbContext context)
{ {

@ -13,7 +13,7 @@ namespace Yavsc.Controllers
[Authorize] [Authorize]
public class InstrumentationController : Controller public class InstrumentationController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public InstrumentationController(ApplicationDbContext context) public InstrumentationController(ApplicationDbContext context)
{ {

@ -8,7 +8,7 @@ namespace Yavsc.Controllers
using Models.Musical; using Models.Musical;
public class InstrumentsController : Controller public class InstrumentsController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public InstrumentsController(ApplicationDbContext context) public InstrumentsController(ApplicationDbContext context)
{ {

@ -14,9 +14,9 @@ namespace Yavsc.Controllers
{ {
public class BugController : Controller public class BugController : Controller
{ {
ApplicationDbContext _context; readonly ApplicationDbContext _context;
IStringLocalizer<BugController> _localizer; readonly IStringLocalizer<BugController> _localizer;
IStringLocalizer<Yavsc.Models.IT.Fixing.Resources> _statusLocalizer; readonly IStringLocalizer<Yavsc.Models.IT.Fixing.Resources> _statusLocalizer;
public BugController(ApplicationDbContext context, public BugController(ApplicationDbContext context,
IStringLocalizer<BugController> localizer, IStringLocalizer<BugController> localizer,

@ -14,8 +14,8 @@ namespace Yavsc.Controllers
public class FeatureController : Controller public class FeatureController : Controller
{ {
private ApplicationDbContext _context; private readonly ApplicationDbContext _context;
private IStringLocalizer<BugController> _bugLocalizer; private readonly IStringLocalizer<BugController> _bugLocalizer;
IEnumerable<SelectListItem> Statuses(FeatureStatus ?status) => IEnumerable<SelectListItem> Statuses(FeatureStatus ?status) =>
_bugLocalizer.CreateSelectListItems(typeof(FeatureStatus), status); _bugLocalizer.CreateSelectListItems(typeof(FeatureStatus), status);

@ -49,9 +49,8 @@ namespace Microsoft.AspNet.Builder
var options = new OAuthAuthorizationServerOptions(); var options = new OAuthAuthorizationServerOptions();
if (configureOptions != null)
configureOptions(options); configureOptions?.Invoke(options);
return app.UseOAuthAuthorizationServer(options); return app.UseOAuthAuthorizationServer(options);
} }

@ -18,11 +18,13 @@ namespace Yavsc.Helpers
public static Stream GetStream(StreamReader reader) public static Stream GetStream(StreamReader reader)
{ {
var procStart = new ProcessStartInfo("node", "node_modules/ansi-to-html/bin/ansi-to-html"); var procStart = new ProcessStartInfo("node", "node_modules/ansi-to-html/bin/ansi-to-html")
procStart.UseShellExecute = false; {
procStart.RedirectStandardInput = true; UseShellExecute = false,
procStart.RedirectStandardOutput = true; RedirectStandardInput = true,
// procStart.RedirectStandardError = true; RedirectStandardOutput = true
};
// procStart.RedirectStandardError = true;
var mem = new MemoryStream(); var mem = new MemoryStream();
var writer = new StreamWriter(mem); var writer = new StreamWriter(mem);
var proc = Process.Start(procStart); var proc = Process.Start(procStart);
@ -54,4 +56,4 @@ namespace Yavsc.Helpers
return GetStream(reader); return GetStream(reader);
} }
} }
} }

@ -11,8 +11,7 @@ namespace Yavsc.Helpers
public static class EventHelpers public static class EventHelpers
{ {
public static RdvQueryEvent CreateEvent(this RdvQuery query, public static RdvQueryEvent CreateEvent(this RdvQuery query, string subtopic)
IStringLocalizer SR, string subtopic)
{ {
var yaev = new RdvQueryEvent(subtopic) var yaev = new RdvQueryEvent(subtopic)
{ {

@ -21,10 +21,11 @@ namespace Yavsc.Helpers
{ {
public static FileRecievedInfo ReceiveProSignature(this ClaimsPrincipal user, string billingCode, long estimateId, IFormFile formFile, string signtype) public static FileRecievedInfo ReceiveProSignature(this ClaimsPrincipal user, string billingCode, long estimateId, IFormFile formFile, string signtype)
{ {
var item = new FileRecievedInfo(); var item = new FileRecievedInfo
item.FileName = AbstractFileSystemHelpers.SignFileNameFormat("pro",billingCode,estimateId); {
item.MimeType = formFile.ContentDisposition; FileName = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, estimateId)
};
var destFileName = Path.Combine(Startup.SiteSetup.Bills, item.FileName); var destFileName = Path.Combine(Startup.SiteSetup.Bills, item.FileName);
var fi = new FileInfo(destFileName); var fi = new FileInfo(destFileName);
@ -200,10 +201,11 @@ namespace Yavsc.Helpers
// this process is not safe at concurrent access. // this process is not safe at concurrent access.
long usage = user.DiskUsage; long usage = user.DiskUsage;
var item = new FileRecievedInfo(); var item = new FileRecievedInfo
item.FileName = AbstractFileSystemHelpers.FilterFileName (destFileName); {
item.MimeType = contentType; FileName = AbstractFileSystemHelpers.FilterFileName(destFileName),
item.DestDir = root; DestDir = root
};
var fi = new FileInfo(Path.Combine(root, item.FileName)); var fi = new FileInfo(Path.Combine(root, item.FileName));
if (fi.Exists) if (fi.Exists)
{ {
@ -251,8 +253,10 @@ namespace Yavsc.Helpers
public static FileRecievedInfo ReceiveAvatar(this ApplicationUser user, IFormFile formFile) public static FileRecievedInfo ReceiveAvatar(this ApplicationUser user, IFormFile formFile)
{ {
var item = new FileRecievedInfo(); var item = new FileRecievedInfo
item.FileName = user.UserName + ".png"; {
FileName = user.UserName + ".png"
};
var destFileName = Path.Combine(Startup.SiteSetup.Avatars, item.FileName); var destFileName = Path.Combine(Startup.SiteSetup.Avatars, item.FileName);

@ -0,0 +1,12 @@
using System;
namespace Yavsc.Services
{
public interface IDiskUsageTracker
{
bool GetSpace(string userName, long space);
void Release(string userName, long space);
}
}

@ -1,6 +1,7 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Yavsc.Models;
using Yavsc.ViewModels.Streaming; using Yavsc.ViewModels.Streaming;
namespace Yavsc.Services namespace Yavsc.Services
@ -17,12 +18,9 @@ namespace Yavsc.Services
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
/// <returns></returns> /// <returns></returns>
Task<bool> AcceptStream (HttpContext context); Task<bool> AcceptStream (HttpContext context, ApplicationUser user, string destDir, string fileName);
/// <summary>
/// live cast entry point
/// </summary>
/// <value></value>
PathString LiveCastingPath {get; set;}
} }
}
}

@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.OptionsModel;
using Yavsc;
using Yavsc.Models;
using Yavsc.Services;
public class DiskUsageTracker : IDiskUsageTracker
{
public class DUTInfo
{
public DUTInfo()
{
Creation = DateTime.Now;
}
public long Usage { get; set; }
public long Quota { get; set; }
public readonly DateTime Creation;
}
readonly Dictionary<string, DUTInfo> DiskUsage;
readonly ApplicationDbContext context;
readonly int ulistLength;
public DiskUsageTracker(IOptions<SiteSettings> options, ApplicationDbContext context)
{
ulistLength = options.Value.DUUserListLen;
DiskUsage = new Dictionary<string, DUTInfo>();
this.context = context;
}
readonly static object userInfoLock = new object();
DUTInfo GetInfo(string username)
{
lock (userInfoLock)
{
if (!DiskUsage.ContainsKey(username))
{
var user = context.Users.SingleOrDefault(u => u.UserName == username);
if (user == null) throw new Exception($"Not an user : {username}");
DUTInfo usage = new DUTInfo
{
Usage = user.DiskUsage,
Quota = user.DiskQuota
};
DiskUsage.Add(username, usage);
if (DiskUsage.Count > ulistLength)
{
// remove the oldest
var oldestts = DateTime.Now;
DUTInfo oinfo = null;
string ouname = null;
foreach (var diskusage in DiskUsage)
{
if (oldestts > usage.Creation)
{
oldestts = diskusage.Value.Creation;
ouname = diskusage.Key;
oinfo = diskusage.Value;
}
}
var ouser = context.Users.SingleOrDefault(u => u.UserName == ouname);
ouser.DiskUsage = oinfo.Usage;
context.SaveChanges();
DiskUsage.Remove(ouname);
}
return usage;
}
return DiskUsage[username];
}
}
public bool GetSpace(string userName, long space)
{
var info = GetInfo(userName);
if (info.Quota < info.Usage + space) return false;
info.Usage += space;
#pragma warning disable CS4014
SaveUserUsage(userName,info.Usage);
#pragma warning restore CS4014
return true;
}
public void Release(string userName, long space)
{
var info = GetInfo(userName);
info.Usage -= space;
#pragma warning disable CS4014
SaveUserUsage(userName,info.Usage);
#pragma warning restore CS4014
}
async Task SaveUserUsage(string username, long usage)
{
await Task.Run(() =>
{
var ouser = context.Users.SingleOrDefault(u => u.UserName == username);
ouser.DiskUsage = usage;
context.SaveChanges();
});
}
}

@ -4,6 +4,9 @@ using System.Security.Principal;
using System.Security.Claims; using System.Security.Claims;
using Yavsc.Models; using Yavsc.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using System.IO;
using rules;
namespace Yavsc.Services namespace Yavsc.Services
{ {
@ -12,10 +15,20 @@ namespace Yavsc.Services
readonly ApplicationDbContext _dbContext; readonly ApplicationDbContext _dbContext;
readonly ILogger _logger; readonly ILogger _logger;
public FileSystemAuthManager(ApplicationDbContext dbContext, ILoggerFactory loggerFactory) readonly SiteSettings SiteSettings;
readonly string aclfileName;
readonly RuleSetParser ruleSetParser;
public FileSystemAuthManager(ApplicationDbContext dbContext, ILoggerFactory loggerFactory,
IOptions<SiteSettings> sitesOptions)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_logger = loggerFactory.CreateLogger<FileSystemAuthManager>(); _logger = loggerFactory.CreateLogger<FileSystemAuthManager>();
SiteSettings = sitesOptions.Value;
aclfileName = SiteSettings.AccessListFileName;
ruleSetParser = new RuleSetParser(true);
} }
public FileAccessRight GetFilePathAccess(ClaimsPrincipal user, string normalizedFullPath) public FileAccessRight GetFilePathAccess(ClaimsPrincipal user, string normalizedFullPath)
@ -25,38 +38,45 @@ namespace Yavsc.Services
var parts = normalizedFullPath.Split('/'); var parts = normalizedFullPath.Split('/');
// below 4 parts, no file name. // below 4 parts, no file name.
if (parts.Length<4) return FileAccessRight.None; if (parts.Length < 4) return FileAccessRight.None;
var filePath = string.Join("/",parts.Skip(3)); var fileDir = string.Join("/", parts.Take(parts.Length - 1));
var firstFileNamePart = parts[3]; var firstFileNamePart = parts[3];
if (firstFileNamePart == "pub") if (firstFileNamePart == "pub")
{ {
_logger.LogInformation("Serving public file."); _logger.LogInformation("Serving public file.");
return FileAccessRight.Read; return FileAccessRight.Read;
} }
var funame = parts[2]; var funame = parts[2];
_logger.LogInformation($"{normalizedFullPath} from {funame}"); _logger.LogInformation($"Accessing {normalizedFullPath} from {funame}");
if (funame == user?.GetUserName())
{
_logger.LogInformation("Serving file to owner.");
return FileAccessRight.Read | FileAccessRight.Write;
}
if (funame == user?.GetUserName())
{
_logger.LogInformation("Serving file to owner.");
return FileAccessRight.Read | FileAccessRight.Write;
}
var aclfi = new FileInfo(Path.Combine(Environment.CurrentDirectory, fileDir, aclfileName));
// TODO default user scoped file access policy
if (!aclfi.Exists) return FileAccessRight.Read;
ruleSetParser.Reset();
ruleSetParser.ParseFile(aclfi.FullName);
if (ruleSetParser.Rules.Allow(user.GetUserName()))
return FileAccessRight.Read;
var ucl = user.Claims.Where(c => c.Type == YavscClaimTypes.CircleMembership).Select(c => long.Parse(c.Value)).Distinct().ToArray(); var ucl = user.Claims.Where(c => c.Type == YavscClaimTypes.CircleMembership).Select(c => long.Parse(c.Value)).Distinct().ToArray();
var uclString = string.Join(",", ucl); var uclString = string.Join(",", ucl);
_logger.LogInformation($"{uclString} "); _logger.LogInformation($"{uclString} ");
foreach ( foreach (
var cid in ucl var cid in ucl
) { )
var ok = _dbContext.CircleAuthorizationToFile.Any(a => a.CircleId == cid && a.FullPath == filePath); {
var ok = _dbContext.CircleAuthorizationToFile.Any(a => a.CircleId == cid && a.FullPath == fileDir);
if (ok) return FileAccessRight.Read; if (ok) return FileAccessRight.Read;
} }
return FileAccessRight.None; return FileAccessRight.None;
} }

@ -26,7 +26,6 @@ namespace Yavsc.Services
readonly IHubContext _hubContext; readonly IHubContext _hubContext;
private readonly ILogger _logger; private readonly ILogger _logger;
readonly ApplicationDbContext _dbContext; readonly ApplicationDbContext _dbContext;
public PathString LiveCastingPath { get; set; } = Constants.LivePath;
public ConcurrentDictionary<string, LiveCastHandler> Casters { get; } = new ConcurrentDictionary<string, LiveCastHandler>(); public ConcurrentDictionary<string, LiveCastHandler> Casters { get; } = new ConcurrentDictionary<string, LiveCastHandler>();
@ -38,23 +37,12 @@ namespace Yavsc.Services
_logger = loggerFactory.CreateLogger<LiveProcessor>(); _logger = loggerFactory.CreateLogger<LiveProcessor>();
} }
public async Task<bool> AcceptStream(HttpContext context) public async Task<bool> AcceptStream(HttpContext context, ApplicationUser user, string destDir, string fileName)
{ {
// TODO defer request handling // TODO defer request handling
var liveId = long.Parse(context.Request.Path.Value.Substring(LiveCastingPath.Value.Length + 1));
var userId = context.User.GetUserId();
var user = await _dbContext.Users.FirstAsync(u => u.Id == userId);
var uname = user.UserName;
var flow = _dbContext.LiveFlow.Include(f => f.Owner).SingleOrDefault(f => (f.OwnerId == userId && f.Id == liveId));
if (flow == null)
{
_logger.LogWarning("Aborting. Flow info was not found.");
context.Response.StatusCode = 400;
return false;
}
_logger.LogInformation("flow : " + flow.Title + " for " + uname);
string uname = user.UserName;
LiveCastHandler liveHandler = null; LiveCastHandler liveHandler = null;
if (Casters.ContainsKey(uname)) if (Casters.ContainsKey(uname))
{ {
@ -100,35 +88,15 @@ namespace Yavsc.Services
_logger.LogInformation($"Received bytes : {received.Count}"); _logger.LogInformation($"Received bytes : {received.Count}");
_logger.LogInformation($"Is the end : {received.EndOfMessage}"); _logger.LogInformation($"Is the end : {received.EndOfMessage}");
const string livePath = "live";
string destDir = context.User.InitPostToFileSystem(livePath);
_logger.LogInformation($"Saving flow to {destDir}");
string fileName = flow.GetFileName();
FileInfo destFileInfo = new FileInfo(Path.Combine(destDir, fileName));
// this should end :-)
while (destFileInfo.Exists)
{
flow.SequenceNumber++;
fileName = flow.GetFileName();
destFileInfo = new FileInfo(Path.Combine(destDir, fileName));
}
var fsInputQueue = new Queue<ArraySegment<byte>>(); var fsInputQueue = new Queue<ArraySegment<byte>>();
bool endOfInput = false; bool endOfInput = false;
fsInputQueue.Enqueue(sBuffer); fsInputQueue.Enqueue(sBuffer);
var taskWritingToFs = liveHandler.ReceiveUserFile(user, _logger, destDir, fsInputQueue, fileName, flow.MediaType, () => endOfInput); var taskWritingToFs = liveHandler.ReceiveUserFile(user, _logger, destDir, fsInputQueue, fileName, () => endOfInput);
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
hubContext.Clients.All.addPublicStream(new PublicStreamInfo
{
id = flow.Id,
sender = flow.Owner.UserName,
title = flow.Title,
url = flow.GetFileUrl(),
mediaType = flow.MediaType
}, $"{flow.Owner.UserName} is starting a stream!");
Stack<string> ToClose = new Stack<string>(); Stack<string> ToClose = new Stack<string>();
@ -136,7 +104,6 @@ namespace Yavsc.Services
{ {
do do
{ {
_logger.LogInformation($"Echoing {received.Count} bytes received in a {received.MessageType} message; Fin={received.EndOfMessage}"); _logger.LogInformation($"Echoing {received.Count} bytes received in a {received.MessageType} message; Fin={received.EndOfMessage}");
// Echo anything we receive // Echo anything we receive
// and send to all listner found // and send to all listner found

@ -24,12 +24,14 @@ using Newtonsoft.Json;
namespace Yavsc namespace Yavsc
{ {
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Net; using System.Net;
using System.Security.Claims; using System.Security.Claims;
using Formatters; using Formatters;
using Google.Apis.Util.Store; using Google.Apis.Util.Store;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity;
using Microsoft.AspNet.SignalR;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Models; using Models;
@ -37,6 +39,7 @@ namespace Yavsc
using Yavsc.Abstract.FileSystem; using Yavsc.Abstract.FileSystem;
using Yavsc.AuthorizationHandlers; using Yavsc.AuthorizationHandlers;
using Yavsc.Helpers; using Yavsc.Helpers;
using Yavsc.Models.Messaging;
using static System.Environment; using static System.Environment;
public partial class Startup public partial class Startup
@ -59,12 +62,12 @@ namespace Yavsc
/// generating reset password and confirmation tokens /// generating reset password and confirmation tokens
/// </summary> /// </summary>
public IUserTokenProvider<ApplicationUser> UserTokenProvider { get; set; } public IUserTokenProvider<ApplicationUser> UserTokenProvider { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{ {
AppDomain.CurrentDomain.UnhandledException += OnUnHandledException; AppDomain.CurrentDomain.UnhandledException += OnUnHandledException;
var devtag = env.IsDevelopment() ? "D" : ""; var devtag = env.IsDevelopment() ? "D" : "";
var prodtag = env.IsProduction() ? "P" : ""; var prodtag = env.IsProduction() ? "P" : "";
var stagetag = env.IsStaging() ? "S" : ""; var stagetag = env.IsStaging() ? "S" : "";
@ -103,7 +106,7 @@ namespace Yavsc
GServiceAccount = JsonConvert.DeserializeObject<GoogleServiceAccount>(safile.OpenText().ReadToEnd()); GServiceAccount = JsonConvert.DeserializeObject<GoogleServiceAccount>(safile.OpenText().ReadToEnd());
} }
} }
// never hit ... // never hit ...
private void OnUnHandledException(object sender, UnhandledExceptionEventArgs e) private void OnUnHandledException(object sender, UnhandledExceptionEventArgs e)
{ {
@ -141,8 +144,9 @@ namespace Yavsc
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<GoogleAuthSettings>), typeof(OptionsManager<GoogleAuthSettings>))); services.Add(ServiceDescriptor.Singleton(typeof(IOptions<GoogleAuthSettings>), typeof(OptionsManager<GoogleAuthSettings>)));
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<CompanyInfoSettings>), typeof(OptionsManager<CompanyInfoSettings>))); services.Add(ServiceDescriptor.Singleton(typeof(IOptions<CompanyInfoSettings>), typeof(OptionsManager<CompanyInfoSettings>)));
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<RequestLocalizationOptions>), typeof(OptionsManager<RequestLocalizationOptions>))); services.Add(ServiceDescriptor.Singleton(typeof(IOptions<RequestLocalizationOptions>), typeof(OptionsManager<RequestLocalizationOptions>)));
services.Add(ServiceDescriptor.Singleton(typeof(IDiskUsageTracker), typeof(DiskUsageTracker)));
services.Configure<RequestLocalizationOptions>(options => services.Configure<RequestLocalizationOptions>(options =>
{ {
var supportedCultures = new[] var supportedCultures = new[]
@ -430,7 +434,8 @@ namespace Yavsc
_logger.LogInformation("LocalApplicationData: " + Environment.GetFolderPath(SpecialFolder.LocalApplicationData, SpecialFolderOption.DoNotVerify)); _logger.LogInformation("LocalApplicationData: " + Environment.GetFolderPath(SpecialFolder.LocalApplicationData, SpecialFolderOption.DoNotVerify));
app.Use(async (context, next) => app.Use(async (context, next) =>
{ {
var liveCasting = context.Request.Path.StartsWithSegments(_liveProcessor.LiveCastingPath); const string livePath = "live";
var liveCasting = context.Request.Path.StartsWithSegments(Constants.LivePath);
if (liveCasting) if (liveCasting)
{ {
@ -441,10 +446,49 @@ namespace Yavsc
context.Response.StatusCode = 403; context.Response.StatusCode = 403;
else else
{ {
await _liveProcessor.AcceptStream(context); var liveId = long.Parse(context.Request.Path.Value.Substring(Constants.LivePath.Length + 1));
var userId = context.User.GetUserId();
var user = await _dbContext.Users.FirstAsync(u => u.Id == userId);
var uname = user.UserName;
var flow = _dbContext.LiveFlow.Include(f => f.Owner).SingleOrDefault(f => (f.OwnerId == userId && f.Id == liveId));
if (flow == null)
{
_logger.LogWarning("Aborting. Flow info was not found.");
context.Response.StatusCode = 400;
return;
}
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
hubContext.Clients.All.addPublicStream(new PublicStreamInfo
{
id = flow.Id,
sender = flow.Owner.UserName,
title = flow.Title,
url = flow.GetFileUrl(),
mediaType = flow.MediaType
}, $"{flow.Owner.UserName} is starting a stream!");
string destDir = context.User.InitPostToFileSystem(livePath);
_logger.LogInformation($"Saving flow to {destDir}");
string fileName = flow.GetFileName();
_logger.LogInformation("flow : " + flow.Title + " for " + uname);
FileInfo destFileInfo = new FileInfo(Path.Combine(destDir, fileName));
// this should end :-)
while (destFileInfo.Exists)
{
flow.SequenceNumber++;
fileName = flow.GetFileName();
destFileInfo = new FileInfo(Path.Combine(destDir, fileName));
}
await _liveProcessor.AcceptStream(context, user, destDir, fileName);
} }
} }
else { else
{
context.Response.StatusCode = 400; context.Response.StatusCode = 400;
} }
} }
@ -454,7 +498,7 @@ namespace Yavsc
} }
}); });
CheckApp( env, loggerFactory); CheckApp(env, loggerFactory);
} }
// Entry point for the application. // Entry point for the application.

@ -13,12 +13,14 @@ using Yavsc.Models.FileSystem;
namespace Yavsc.ViewModels.Streaming namespace Yavsc.ViewModels.Streaming
{ {
public class LiveCastClient { public class LiveCastClient
{
public string UserName { get; set; } public string UserName { get; set; }
public WebSocket Socket { get; set; } public WebSocket Socket { get; set; }
} }
public class LiveEntryViewModel { public class LiveEntryViewModel
{
public string UserName { get; set; } public string UserName { get; set; }
public string FlowId { get; set; } public string FlowId { get; set; }
} }
@ -29,22 +31,21 @@ namespace Yavsc.ViewModels.Streaming
public WebSocket Socket { get; set; } public WebSocket Socket { get; set; }
public ConcurrentDictionary<string, WebSocket> Listeners { get; set; } = new ConcurrentDictionary<string, WebSocket>(); public ConcurrentDictionary<string, WebSocket> Listeners { get; set; } = new ConcurrentDictionary<string, WebSocket>();
public CancellationTokenSource TokenSource { get; set; } = new CancellationTokenSource(); public CancellationTokenSource TokenSource { get; set; } = new CancellationTokenSource();
public void Dispose() public void Dispose()
{ {
} }
public async Task<FileRecievedInfo> ReceiveUserFile(ApplicationUser user, ILogger logger, string root, Queue<ArraySegment<byte>> queue, string destFileName, string contentType, Func<bool> isEndOfInput) public async Task<FileRecievedInfo> ReceiveUserFile(ApplicationUser user, ILogger logger, string root, Queue<ArraySegment<byte>> queue, string destFileName, Func<bool> isEndOfInput)
{ {
// TODO lock user's disk usage for this scope, // TODO lock user's disk usage for this scope,
// this process is not safe at concurrent access. // this process is not safe at concurrent access.
long usage = user.DiskUsage; long usage = user.DiskUsage;
var item = new FileRecievedInfo var item = new FileRecievedInfo
{ {
FileName = AbstractFileSystemHelpers.FilterFileName(destFileName), FileName = AbstractFileSystemHelpers.FilterFileName(destFileName),
MimeType = contentType,
DestDir = root DestDir = root
}; };
var fi = new FileInfo(Path.Combine(root, item.FileName)); var fi = new FileInfo(Path.Combine(root, item.FileName));
@ -52,36 +53,39 @@ namespace Yavsc.ViewModels.Streaming
{ {
item.Overriden = true; item.Overriden = true;
usage -= fi.Length; usage -= fi.Length;
} }
logger.LogInformation("Opening the file"); logger.LogInformation("Opening the file");
using (var dest = fi.Open(FileMode.Create, FileAccess.Write, FileShare.Read)) using (var dest = fi.Open(FileMode.Create, FileAccess.Write, FileShare.Read))
{ {
logger.LogInformation("Appening to file"); logger.LogInformation("Appening to file");
while (!isEndOfInput() || queue.Count>0) while (!isEndOfInput() || queue.Count > 0)
{
if (queue.Count > 0)
{ {
if (queue.Count>0) { var buffer = queue.Dequeue();
var buffer = queue.Dequeue();
logger.LogInformation($"writing {buffer.Array.Length} bytes...");
logger.LogInformation($"writing {buffer.Array.Length} bytes...");
await dest.WriteAsync(buffer.Array, buffer.Offset, buffer.Count); await dest.WriteAsync(buffer.Array, buffer.Offset, buffer.Count);
logger.LogInformation($"done."); logger.LogInformation($"done.");
usage += buffer.Count; usage += buffer.Count;
}
if (usage >= user.DiskQuota) break;
if (queue.Count==0 && !isEndOfInput()) {
await Task.Delay(100);
}
} }
user.DiskUsage = usage; if (usage >= user.DiskQuota) break;
dest.Close(); if (queue.Count == 0 && !isEndOfInput())
{
await Task.Delay(100);
}
}
user.DiskUsage = usage;
dest.Close();
} }
if (usage >= user.DiskQuota) { if (usage >= user.DiskQuota)
{
item.QuotaOffensed = true; item.QuotaOffensed = true;
} }
user.DiskUsage = usage; user.DiskUsage = usage;
return item; return item;
} }
} }

@ -37,12 +37,12 @@
"compile": { "compile": {
"include": "*.cs", "include": "*.cs",
"exclude": [ "exclude": [
"wwwroot", "wwwroot",
"node_modules", "node_modules",
"bower_components", "bower_components",
"contrib", "contrib",
"Blog-Dev", "Blog-Dev",
"Temp-Dev" "Temp-Dev"
] ]
}, },
"embed": [ "embed": [
@ -152,7 +152,8 @@
"Yavsc.Server": { "Yavsc.Server": {
"target": "project", "target": "project",
"type": "build" "type": "build"
} },
"rules": "1.1.0"
}, },
"commands": { "commands": {
"ef": "EntityFramework.Commands", "ef": "EntityFramework.Commands",

@ -156,7 +156,7 @@ if (typeof XMLHttpRequest === 'undefined') {
} }
} }
}; };
xmlhttp.open('DELETE', '/api/fs/' + dfilep, true); xmlhttp.open('DELETE', '/api/fs/' + encodeURIComponent(dfilep), true);
xmlhttp.send(); xmlhttp.send();
}); });
}, },

Loading…