principalement du format de code

This commit is contained in:
Paul Schneider 2020-09-12 01:11:30 +01:00
commit ff1444d664
87 changed files with 510 additions and 550 deletions

View file

@ -13,7 +13,6 @@ namespace Yavsc.Services
public class BillingService : IBillingService
{
public ApplicationDbContext DbContext { get; private set; }
private ILogger logger;
public static Dictionary<string,Func<ApplicationDbContext,long,IDecidableQuery>> Billing =
new Dictionary<string,Func<ApplicationDbContext,long,IDecidableQuery>> ();
public static List<PropertyInfo> UserSettings = new List<PropertyInfo>();
@ -25,9 +24,8 @@ namespace Yavsc.Services
get { return GlobalBillingMap; }
}
public BillingService(ILoggerFactory loggerFactory, ApplicationDbContext dbContext)
public BillingService(ApplicationDbContext dbContext)
{
logger = loggerFactory.CreateLogger<BillingService>();
DbContext = dbContext;
}

View file

@ -31,24 +31,24 @@ namespace Yavsc.Services
/// <typeparam name="string"></typeparam>
/// <returns></returns>
static ConcurrentDictionary<string, string> ChatUserNames = new ConcurrentDictionary<string, string>();
static readonly ConcurrentDictionary<string, string> ChatUserNames = new ConcurrentDictionary<string, string>();
/// <summary>
/// by user name
/// </summary>
/// <returns></returns>
static ConcurrentDictionary<string, List<string>> ChatCxIds = new ConcurrentDictionary<string, List<string>>();
static readonly ConcurrentDictionary<string, List<string>> ChatCxIds = new ConcurrentDictionary<string, List<string>>();
/// <summary>
/// by user name,
/// the list of its chat rooms
/// </summary>
/// <returns></returns>
static ConcurrentDictionary<string, List<string>> ChatRoomPresence = new ConcurrentDictionary<string, List<string>>();
static ConcurrentDictionary<string, bool> _isCop = new ConcurrentDictionary<string, bool>();
static readonly ConcurrentDictionary<string, List<string>> ChatRoomPresence = new ConcurrentDictionary<string, List<string>>();
static readonly ConcurrentDictionary<string, bool> _isCop = new ConcurrentDictionary<string, bool>();
public static ConcurrentDictionary<string, ChatRoomInfo> Channels = new ConcurrentDictionary<string, ChatRoomInfo>();
ApplicationDbContext _dbContext;
IStringLocalizer _localizer;
readonly ApplicationDbContext _dbContext;
readonly IStringLocalizer _localizer;
public HubConnectionManager()
{
@ -97,7 +97,7 @@ namespace Yavsc.Services
return ChatRoomPresence[userName].Contains(roomName);
}
public bool isCop(string userName)
public bool IsCop(string userName)
{
return _isCop[userName];
}
@ -179,7 +179,7 @@ namespace Yavsc.Services
}
else
{
if (isCop(userName))
if (IsCop(userName))
{
chanInfo.Ops.Add(cxId);
}
@ -320,7 +320,7 @@ namespace Yavsc.Services
_errorHandler(roomName, _localizer.GetString(ChatHubConstants.HopWontKickOp).ToString());
return false;
}
if (isCop(userName))
if (IsCop(userName))
{
_errorHandler(roomName, _localizer.GetString(ChatHubConstants.NoKickOnCop).ToString());
return false;

View file

@ -27,14 +27,12 @@ namespace Yavsc.Lib
const string DefaultBaseClassName = "ATemplate";
const string DefaultBaseClass = nameof(UserOrientedTemplate);
const string DefaultNamespace = "CompiledRazorTemplates";
RazorTemplateEngine razorEngine;
IStringLocalizer<EMailer> stringLocalizer;
ApplicationDbContext dbContext;
IEmailSender mailSender;
RazorEngineHost host;
ILogger logger;
readonly RazorTemplateEngine razorEngine;
readonly IStringLocalizer<EMailer> stringLocalizer;
readonly ApplicationDbContext dbContext;
readonly IEmailSender mailSender;
readonly RazorEngineHost host;
readonly ILogger logger;
public EMailer(ApplicationDbContext context, IEmailSender sender,
IStringLocalizer<EMailer> localizer,

View file

@ -9,8 +9,8 @@ namespace Yavsc.Services
{
public class FileSystemAuthManager : IFileSystemAuthManager
{
ApplicationDbContext _dbContext;
ILogger _logger;
readonly ApplicationDbContext _dbContext;
readonly ILogger _logger;
public FileSystemAuthManager(ApplicationDbContext dbContext, ILoggerFactory loggerFactory)
{
@ -70,4 +70,4 @@ namespace Yavsc.Services
throw new NotImplementedException();
}
}
}
}

View file

@ -43,45 +43,22 @@ namespace Yavsc.Services
/// <summary>
/// Google Calendar API client.
/// </summary>
public class CalendarManager : ICalendarManager
public class CalendarManager : ICalendarManager
{
public class ExpiredTokenException : Exception { }
protected static string [] scopesCalendar =
protected static string[] scopesCalendar =
{ "https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events"
};
private string _ApiKey;
private IAuthorizationCodeFlow _flow;
ApplicationDbContext _dbContext;
readonly ILogger _logger;
readonly string _client_id;
readonly string _client_secret;
IDataStore _dataStore;
ILogger _logger;
string _client_id;
string _client_secret;
public CalendarManager(
ApplicationDbContext dbContext,
IDataStore dataStore,
ILoggerFactory loggerFactory,
IOptions<GoogleAuthSettings> settings)
public CalendarManager(ILoggerFactory loggerFactory)
{
_client_id = Startup.GoogleWebClientConfiguration["web:cient_id"];
_client_secret = Startup.GoogleWebClientConfiguration["web:cient_secret"];
_ApiKey = settings.Value.ApiKey;
_dbContext = dbContext;
_client_id = Startup.GoogleWebClientConfiguration["web:cient_id"];
_client_secret = Startup.GoogleWebClientConfiguration["web:cient_secret"];
_logger = loggerFactory.CreateLogger<CalendarManager>();
_dataStore = dataStore;
_flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = _client_id,
ClientSecret = _client_secret
},
Scopes = scopesCalendar ,
DataStore = dataStore
});
}
/// <summary>
@ -98,29 +75,27 @@ namespace Yavsc.Services
/// </summary>
/// <returns>The calendars.</returns>
/// <param name="userId">Yavsc user id</param>
public async Task<CalendarList> GetCalendarsAsync(string userId, string pageToken)
public async Task<CalendarList> GetCalendarsAsync(string pageToken)
{
if (string.IsNullOrWhiteSpace(userId))
throw new Exception("the user id is not specified");
var service = await CreateUserCalendarServiceAsync(userId);
var service = await CreateUserCalendarServiceAsync();
#if Debug
if (service==null) throw new Exception("Could not get service");
#endif
_logger.LogInformation("Got a service");
_logger.LogInformation("Got a service");
#if Debug
if (service.CalendarList==null) throw new Exception("Could not get calendar list");
#endif
CalendarListResource.ListRequest calListReq = service.CalendarList.List ();
CalendarListResource.ListRequest calListReq = service.CalendarList.List();
#if Debug
if (calListReq==null) throw new Exception ("list is null");
#endif
calListReq.PageToken = pageToken;
return calListReq.Execute ();
calListReq.PageToken = pageToken;
return calListReq.Execute();
}
/// <summary>
/// Gets a calendar event list, between the given dates.
/// </summary>
@ -158,16 +133,17 @@ namespace Yavsc.Services
foreach (var ev in eventList.Items)
{
if (ev.Start.DateTime.HasValue && ev.End.DateTime.HasValue ) {
DateTime start = ev.Start.DateTime.Value;
DateTime end = ev.End.DateTime.Value;
if (ev.Transparency == "transparent")
if (ev.Start.DateTime.HasValue && ev.End.DateTime.HasValue)
{
DateTime start = ev.Start.DateTime.Value;
DateTime end = ev.End.DateTime.Value;
free.Add(new Period { Start = start, End = end });
}
else busy.Add(new Period { Start = start, End = end });
if (ev.Transparency == "transparent")
{
free.Add(new Period { Start = start, End = end });
}
else busy.Add(new Period { Start = start, End = end });
}
}
@ -200,7 +176,7 @@ namespace Yavsc.Services
if (string.IsNullOrWhiteSpace(calid))
throw new Exception("the calendar identifier is not specified");
var service = await GetServiceAsync();
Event ev = new Event
{
@ -217,15 +193,16 @@ namespace Yavsc.Services
CalendarService _service = null;
public async Task<CalendarService> GetServiceAsync()
{
if (_service==null) {
if (_service == null)
{
GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();
var baseClientService = new BaseClientService.Initializer()
{
HttpClientInitializer = credential
};
{
HttpClientInitializer = credential
};
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped( scopesCalendar );
credential = credential.CreateScoped(scopesCalendar);
}/*
var credential = await GoogleHelpers.GetCredentialForApi(new string [] { scopeCalendar });
if (credential.IsCreateScopedRequired)
@ -239,26 +216,26 @@ namespace Yavsc.Services
});
}*/
_service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Yavsc"
});
{
HttpClientInitializer = credential,
ApplicationName = "Yavsc"
});
}
return _service;
}
/// <summary>
/// Creates Google User Credential
/// </summary>
/// <param name="userId">Yavsc use id</param>
/// <returns></returns>
public async Task<CalendarService> CreateUserCalendarServiceAsync(string userId)
/// <summary>
/// Creates Google User Credential
/// </summary>
/// <param name="userId">Yavsc use id</param>
/// <returns></returns>
public async Task<CalendarService> CreateUserCalendarServiceAsync()
{
GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped( scopesCalendar);
credential = credential.CreateScoped(scopesCalendar);
}
@ -268,25 +245,32 @@ namespace Yavsc.Services
ApplicationName = "yavsc-001"
});
return service;
}
return service;
}
public async Task<TokenResponse> RefreshToken(TokenResponse oldResponse)
{
string ep = " https://www.googleapis.com/oauth2/v4/token";
_logger.LogInformation($"rt:{oldResponse.RefreshToken}");
// refresh_token client_id client_secret grant_type=refresh_token
try {
using (var m = new SimpleJsonPostMethod(ep)) {
try
{
using (var m = new SimpleJsonPostMethod(ep))
{
return await m.Invoke<TokenResponse>(
new { refresh_token= oldResponse.RefreshToken, client_id=_client_id,
client_secret=_client_secret,
grant_type="refresh_token" }
new
{
refresh_token = oldResponse.RefreshToken,
client_id = _client_id,
client_secret = _client_secret,
grant_type = "refresh_token"
}
);
}
}
catch (Exception ex) {
throw new Exception ("Quelque chose s'est mal passé à l'envoi",ex);
catch (Exception ex)
{
throw new Exception("Quelque chose s'est mal passé à l'envoi", ex);
}
}
}

View file

@ -21,14 +21,15 @@ using Newtonsoft.Json;
namespace Yavsc.Services
{
public class LiveProcessor : ILiveProcessor {
IHubContext _hubContext;
private ILogger _logger;
ApplicationDbContext _dbContext;
public PathString LiveCastingPath {get; set;} = Constants.LivePath;
public class LiveProcessor : ILiveProcessor
{
readonly IHubContext _hubContext;
private readonly ILogger _logger;
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>();
public LiveProcessor(ApplicationDbContext dbContext, ILoggerFactory loggerFactory)
{
@ -37,7 +38,7 @@ namespace Yavsc.Services
_logger = loggerFactory.CreateLogger<LiveProcessor>();
}
public async Task<bool> AcceptStream (HttpContext context)
public async Task<bool> AcceptStream(HttpContext context)
{
// TODO defer request handling
var liveId = long.Parse(context.Request.Path.Value.Substring(LiveCastingPath.Value.Length + 1));
@ -51,22 +52,23 @@ namespace Yavsc.Services
context.Response.StatusCode = 400;
return false;
}
_logger.LogInformation("flow : "+flow.Title+" for "+uname);
_logger.LogInformation("flow : " + flow.Title + " for " + uname);
LiveCastHandler liveHandler = null;
if (Casters.ContainsKey(uname))
{
_logger.LogWarning($"Casters.ContainsKey({uname})");
liveHandler = Casters[uname];
if (liveHandler.Socket.State == WebSocketState.Open || liveHandler.Socket.State == WebSocketState.Connecting )
if (liveHandler.Socket.State == WebSocketState.Open || liveHandler.Socket.State == WebSocketState.Connecting)
{
_logger.LogWarning($"Closing cx");
_logger.LogWarning($"Closing cx");
// FIXME loosed connexion should be detected & disposed else where
await liveHandler.Socket.CloseAsync( WebSocketCloseStatus.EndpointUnavailable, "one by user", CancellationToken.None);
await liveHandler.Socket.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "one by user", CancellationToken.None);
}
if (!liveHandler.TokenSource.IsCancellationRequested) {
if (!liveHandler.TokenSource.IsCancellationRequested)
{
liveHandler.TokenSource.Cancel();
}
liveHandler.Socket.Dispose();
@ -81,7 +83,7 @@ namespace Yavsc.Services
}
_logger.LogInformation("Accepted web socket");
// Dispatch the flow
try
{
if (liveHandler.Socket != null && liveHandler.Socket.State == WebSocketState.Open)
@ -90,33 +92,33 @@ namespace Yavsc.Services
// TODO: Handle the socket here.
// Find receivers: others in the chat room
// send them the flow
var buffer = new byte[Constants.WebSocketsMaxBufLen+16];
var buffer = new byte[Constants.WebSocketsMaxBufLen];
var sBuffer = new ArraySegment<byte>(buffer);
_logger.LogInformation("Receiving bytes...");
WebSocketReceiveResult received = await liveHandler.Socket.ReceiveAsync(sBuffer, liveHandler.TokenSource.Token);
int count = (received.Count<4)? 0 : buffer[0]*256*1024 +buffer[1]*1024+buffer[2]*256 + buffer[3];
_logger.LogInformation($"Received bytes : {count}");
_logger.LogInformation($"Received bytes : {received.Count}");
_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();
string fileName = flow.GetFileName();
FileInfo destFileInfo = new FileInfo(Path.Combine(destDir, fileName));
// this should end :-)
while (destFileInfo.Exists) {
while (destFileInfo.Exists)
{
flow.SequenceNumber++;
fileName = flow.GetFileName();
fileName = flow.GetFileName();
destFileInfo = new FileInfo(Path.Combine(destDir, fileName));
}
var fsInputQueue = new Queue<ArraySegment<byte>>();
bool endOfInput=false;
bool endOfInput = false;
fsInputQueue.Enqueue(sBuffer);
var taskWritingToFs = liveHandler.ReceiveUserFile(user, _logger, destDir, fsInputQueue, fileName, flow.MediaType, ()=> endOfInput);
var taskWritingToFs = liveHandler.ReceiveUserFile(user, _logger, destDir, fsInputQueue, fileName, flow.MediaType, () => endOfInput);
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
hubContext.Clients.All.addPublicStream(new PublicStreamInfo
@ -132,15 +134,18 @@ namespace Yavsc.Services
try
{
do {
do
{
_logger.LogInformation($"Echoing {received.Count} bytes received in a {received.MessageType} message; Fin={received.EndOfMessage}");
// Echo anything we receive
// and send to all listner found
_logger.LogInformation($"{liveHandler.Listeners.Count} listeners");
foreach (var cliItem in liveHandler.Listeners)
{
var listenningSocket = cliItem.Value;
if (listenningSocket.State == WebSocketState.Open) {
if (listenningSocket.State == WebSocketState.Open)
{
_logger.LogInformation(cliItem.Key);
await listenningSocket.SendAsync(
sBuffer, received.MessageType, received.EndOfMessage, liveHandler.TokenSource.Token);
@ -150,43 +155,47 @@ namespace Yavsc.Services
ToClose.Push(cliItem.Key);
}
}
buffer = new byte[Constants.WebSocketsMaxBufLen+16];
if (!received.CloseStatus.HasValue)
{
_logger.LogInformation("try and receive new bytes");
buffer = new byte[Constants.WebSocketsMaxBufLen];
sBuffer = new ArraySegment<byte>(buffer);
received = await liveHandler.Socket.ReceiveAsync(sBuffer, liveHandler.TokenSource.Token);
count = (received.Count<4)? 0 : buffer[0]*256*1024 +buffer[1]*1024+buffer[2]*256 + buffer[3];
_logger.LogInformation($"Received bytes : {count}");
_logger.LogInformation($"Received bytes : {received.Count}");
_logger.LogInformation($"Is the end : {received.EndOfMessage}");
if (received.Count<=4 || count > Constants.WebSocketsMaxBufLen) {
if (received.CloseStatus.HasValue) {
_logger.LogInformation($"received a close status: {received.CloseStatus.Value.ToString()}: {received.CloseStatusDescription}");
}
else {
_logger.LogError("Wrong packet size: "+count.ToString());
_logger.LogError(JsonConvert.SerializeObject(received));
}
fsInputQueue.Enqueue(sBuffer);
if (received.CloseStatus.HasValue)
{
endOfInput=true;
_logger.LogInformation($"received a close status: {received.CloseStatus.Value}: {received.CloseStatusDescription}");
}
else fsInputQueue.Enqueue(sBuffer);
while (ToClose.Count >0)
}
else endOfInput=true;
while (ToClose.Count > 0)
{
string no = ToClose.Pop();
_logger.LogInformation("Closing follower connection");
WebSocket listenningSocket;
if (liveHandler.Listeners.TryRemove(no, out listenningSocket)) {
if (liveHandler.Listeners.TryRemove(no, out listenningSocket))
{
await listenningSocket.CloseAsync(WebSocketCloseStatus.EndpointUnavailable,
"State != WebSocketState.Open", CancellationToken.None);
listenningSocket.Dispose();
}
}
}
while (!received.CloseStatus.HasValue);
_logger.LogInformation("Closing connection");
endOfInput=true;
taskWritingToFs.Wait();
await liveHandler.Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, received.CloseStatusDescription,liveHandler.TokenSource.Token );
while (liveHandler.Socket.State == WebSocketState.Open);
_logger.LogInformation("Closing connection");
taskWritingToFs.Wait();
await liveHandler.Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, received.CloseStatusDescription, liveHandler.TokenSource.Token);
liveHandler.TokenSource.Cancel();
liveHandler.Dispose();
_logger.LogInformation("Resulting file : " +JsonConvert.SerializeObject(taskWritingToFs.Result));
_logger.LogInformation("Resulting file : " + JsonConvert.SerializeObject(taskWritingToFs.Result));
}
catch (Exception ex)
{
@ -200,16 +209,16 @@ namespace Yavsc.Services
else
{
// Socket was not accepted open ...
// not (meta.Socket != null && meta.Socket.State == WebSocketState.Open)
// not (meta.Socket != null && meta.Socket.State == WebSocketState.Open)
if (liveHandler.Socket != null)
{
_logger.LogError($"meta.Socket.State not Open: {liveHandler.Socket.State.ToString()} ");
_logger.LogError($"meta.Socket.State not Open: {liveHandler.Socket.State} ");
liveHandler.Socket.Dispose();
}
else
_logger.LogError("socket object is null");
}
RemoveLiveInfo(uname);
}
catch (IOException ex)
@ -231,11 +240,11 @@ namespace Yavsc.Services
void RemoveLiveInfo(string userName)
{
LiveCastHandler caster;
if (Casters.TryRemove(userName, out caster))
if (Casters.TryRemove(userName, out caster))
_logger.LogInformation("removed live info");
else
else
_logger.LogError("could not remove live info");
}
}
}
}

View file

@ -12,18 +12,14 @@ namespace Yavsc.Services
{
public class MailSender : IEmailSender
{
private ILogger _logger;
SiteSettings siteSettings;
SmtpSettings smtpSettings;
readonly SiteSettings siteSettings;
readonly SmtpSettings smtpSettings;
public MailSender(
ILoggerFactory loggerFactory,
IOptions<SiteSettings> sitesOptions,
IOptions<SmtpSettings> smtpOptions,
IOptions<GoogleAuthSettings> googleOptions
IOptions<SmtpSettings> smtpOptions
)
{
_logger = loggerFactory.CreateLogger<MailSender>();
siteSettings = sitesOptions?.Value;
smtpSettings = smtpOptions?.Value;
}

View file

@ -7,7 +7,7 @@ namespace Yavsc.Services
using Models.societe.com;
public class SIRENChecker
{
private CompanyInfoSettings _settings;
private readonly CompanyInfoSettings _settings;
public SIRENChecker(CompanyInfoSettings settings)
{
_settings = settings;

View file

@ -16,18 +16,16 @@ namespace Yavsc.Services
{
public class YavscMessageSender : IYavscMessageSender
{
private ILogger _logger;
IEmailSender _emailSender;
SiteSettings siteSettings;
private IHubContext hubContext;
ApplicationDbContext _dbContext;
IConnexionManager _cxManager;
private readonly ILogger _logger;
readonly IEmailSender _emailSender;
readonly SiteSettings siteSettings;
private readonly IHubContext hubContext;
readonly ApplicationDbContext _dbContext;
readonly IConnexionManager _cxManager;
public YavscMessageSender(
ILoggerFactory loggerFactory,
IOptions<SiteSettings> sitesOptions,
IOptions<SmtpSettings> smtpOptions,
IEmailSender emailSender,
ApplicationDbContext dbContext,
IConnexionManager cxManager
@ -67,8 +65,10 @@ namespace Yavsc.Services
foreach (var userId in raa)
{
_logger.LogDebug($"For performer id : {userId}");
MessageWithPayloadResponse.Result result = new MessageWithPayloadResponse.Result();
result.registration_id = userId;
MessageWithPayloadResponse.Result result = new MessageWithPayloadResponse.Result
{
registration_id = userId
};
var user = _dbContext.Users.FirstOrDefault(u => u.Id == userId);
if (user == null)
@ -125,8 +125,10 @@ namespace Yavsc.Services
{
// from usr asp.net Id : var hubClient = hubContext.Clients.User(userId);
var hubClient = hubContext.Clients.Client(cxid);
var data = new Dictionary<string, object>();
data["event"] = JsonConvert.SerializeObject(ev);
var data = new Dictionary<string, object>
{
["event"] = JsonConvert.SerializeObject(ev)
};
hubClient.push(ev.Topic, JsonConvert.SerializeObject(data));
}