diff --git a/Plugins/RawCMS.Plugin.Core/CorePlugin.cs b/Plugins/RawCMS.Plugin.Core/CorePlugin.cs index 28170501..6194288d 100644 --- a/Plugins/RawCMS.Plugin.Core/CorePlugin.cs +++ b/Plugins/RawCMS.Plugin.Core/CorePlugin.cs @@ -39,10 +39,16 @@ public override void ConfigureServices(IServiceCollection services) Logger.LogInformation(configuration["MongoSettings:ConnectionString"]); + + var envConnectionString = Environment.GetEnvironmentVariable("MongoSettings:ConnectionString") ?? Environment.GetEnvironmentVariable("MongoSettingsConnectionString") ?? configuration["MongoSettings:ConnectionString"]; + var envDBName = Environment.GetEnvironmentVariable("MongoSettings:DBName") ?? Environment.GetEnvironmentVariable("MongoSettingsDBName")?? configuration["MongoSettings:DBName"]; + + + MongoSettings instance = new MongoSettings { - ConnectionString = configuration["MongoSettings:ConnectionString"], - DBName = configuration["MongoSettings:DBName"] + ConnectionString = envConnectionString, + DBName = envDBName }; IOptions settingsOptions = Options.Create(instance); diff --git a/Plugins/RawCMS.Plugin.Core/Data/UserPostSaveLambda.cs b/Plugins/RawCMS.Plugin.Core/Data/UserPostSaveLambda.cs index eec80655..49e8eabb 100644 --- a/Plugins/RawCMS.Plugin.Core/Data/UserPostSaveLambda.cs +++ b/Plugins/RawCMS.Plugin.Core/Data/UserPostSaveLambda.cs @@ -1,4 +1,12 @@ -using Newtonsoft.Json; +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Min� +// true +//****************************************************************************** +using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RawCMS.Library.Core; using RawCMS.Library.Core.Interfaces; diff --git a/Plugins/RawCMS.Plugin.Core/Data/UserPresaveLambda.cs b/Plugins/RawCMS.Plugin.Core/Data/UserPresaveLambda.cs index e6cfb0bb..48d5d33d 100644 --- a/Plugins/RawCMS.Plugin.Core/Data/UserPresaveLambda.cs +++ b/Plugins/RawCMS.Plugin.Core/Data/UserPresaveLambda.cs @@ -1,4 +1,12 @@ -using Newtonsoft.Json.Linq; +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Min� +// true +//****************************************************************************** +using Newtonsoft.Json.Linq; using RawCMS.Library.Core; using RawCMS.Library.Core.Interfaces; using RawCMS.Library.Service; diff --git a/Plugins/RawCMS.Plugins.GraphQL/Classes/GraphQLQuery.cs b/Plugins/RawCMS.Plugins.GraphQL/Classes/GraphQLQuery.cs index 16ecdab9..b4cc043f 100644 --- a/Plugins/RawCMS.Plugins.GraphQL/Classes/GraphQLQuery.cs +++ b/Plugins/RawCMS.Plugins.GraphQL/Classes/GraphQLQuery.cs @@ -20,8 +20,9 @@ public GraphQLQuery(GraphQLService graphQLService) foreach (var key in graphQLService.Collections.Keys) { Library.Schema.CollectionSchema metaColl = graphQLService.Collections[key]; - CollectionType type = new CollectionType(metaColl); + CollectionType type = new CollectionType(metaColl, graphQLService.Collections, graphQLService); ListGraphType listType = new ListGraphType(type); + AddField(new FieldType { Name = metaColl.CollectionName, diff --git a/Plugins/RawCMS.Plugins.GraphQL/Classes/GraphQLMiddleware.cs b/Plugins/RawCMS.Plugins.GraphQL/Controllers/GraphQLController.cs similarity index 58% rename from Plugins/RawCMS.Plugins.GraphQL/Classes/GraphQLMiddleware.cs rename to Plugins/RawCMS.Plugins.GraphQL/Controllers/GraphQLController.cs index 979c7acc..12dc9d92 100644 --- a/Plugins/RawCMS.Plugins.GraphQL/Classes/GraphQLMiddleware.cs +++ b/Plugins/RawCMS.Plugins.GraphQL/Controllers/GraphQLController.cs @@ -10,66 +10,61 @@ using GraphQL.Http; using GraphQL.Instrumentation; using GraphQL.Types; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; +using RawCMS.Library.Core.Attributes; +using RawCMS.Plugins.GraphQL.Classes; using System; using System.IO; -using System.Linq; -using System.Net; using System.Threading.Tasks; -namespace RawCMS.Plugins.GraphQL.Classes +namespace RawCMS.Plugins.GraphQL.Controllers { - public class GraphQLMiddleware + [AllowAnonymous] + [RawAuthentication] + [Route("api/graphql")] + public class GraphQLController : Controller { - private readonly RequestDelegate _next; private readonly IDocumentExecuter _executer; private readonly IDocumentWriter _writer; private readonly GraphQLService _service; + private readonly ISchema _schema; - public GraphQLMiddleware( - RequestDelegate next, - IDocumentExecuter executer, + public GraphQLController(IDocumentExecuter executer, IDocumentWriter writer, - GraphQLService graphQLService - ) + GraphQLService graphQLService, + ISchema schema) { - _next = next; _executer = executer; _writer = writer; _service = graphQLService; + _schema = schema; } - public async Task Invoke(HttpContext context, ISchema schema) + public static T Deserialize(Stream s) { - if (!IsGraphQLRequest(context)) + using (StreamReader reader = new StreamReader(s)) + using (JsonTextReader jsonReader = new JsonTextReader(reader)) { - await _next(context); - return; + JsonSerializer ser = new JsonSerializer(); + return ser.Deserialize(jsonReader); } - - await ExecuteAsync(context, schema); } - private bool IsGraphQLRequest(HttpContext context) - { - return context.Request.Path.StartsWithSegments(_service.Settings.Path) - && string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase); - } - - private async Task ExecuteAsync(HttpContext context, ISchema schema) + [HttpPost] + public async Task Post([FromBody]GraphQLRequest request) { + GraphQLRequest t = Deserialize(HttpContext.Request.Body); DateTime start = DateTime.UtcNow; - GraphQLRequest request = Deserialize(context.Request.Body); - ExecutionResult result = await _executer.ExecuteAsync(_ => { - _.Schema = schema; + _.Schema = _schema; _.Query = request.Query; _.OperationName = request.OperationName; _.Inputs = request.Variables.ToInputs(); - _.UserContext = _service.Settings.BuildUserContext?.Invoke(context); + _.UserContext = _service.Settings.BuildUserContext?.Invoke(HttpContext); _.EnableMetrics = _service.Settings.EnableMetrics; if (_service.Settings.EnableMetrics) { @@ -82,25 +77,7 @@ private async Task ExecuteAsync(HttpContext context, ISchema schema) result.EnrichWithApolloTracing(start); } - await WriteResponseAsync(context, result); - } - - private async Task WriteResponseAsync(HttpContext context, ExecutionResult result) - { - context.Response.ContentType = "application/json"; - context.Response.StatusCode = result.Errors?.Any() == true ? (int)HttpStatusCode.BadRequest : (int)HttpStatusCode.OK; - - await _writer.WriteAsync(context.Response.Body, result); - } - - public static T Deserialize(Stream s) - { - using (StreamReader reader = new StreamReader(s)) - using (JsonTextReader jsonReader = new JsonTextReader(reader)) - { - JsonSerializer ser = new JsonSerializer(); - return ser.Deserialize(jsonReader); - } + return result; } } } \ No newline at end of file diff --git a/Plugins/RawCMS.Plugins.GraphQL/GraphQLPlugin.cs b/Plugins/RawCMS.Plugins.GraphQL/GraphQLPlugin.cs index 096a387b..d93926aa 100644 --- a/Plugins/RawCMS.Plugins.GraphQL/GraphQLPlugin.cs +++ b/Plugins/RawCMS.Plugins.GraphQL/GraphQLPlugin.cs @@ -41,10 +41,8 @@ public override void ConfigureServices(IServiceCollection services) services.AddSingleton(s => new FuncDependencyResolver(s.GetRequiredService)); services.AddSingleton(); services.AddSingleton(); - //services.AddSingleton(); services.AddScoped(); services.AddSingleton(); - //services.AddSingleton(); services.AddSingleton(x => graphService); } @@ -60,16 +58,6 @@ public override void Configure(IApplicationBuilder app, AppEngine appEngine) base.Configure(app, appEngine); - app.UseMiddleware(); - //app.UseMiddleware(new GraphQLSettings - //{ - // BuildUserContext = ctx => new GraphQLUserContext - // { - // User = ctx.User - // }, - // EnableMetrics = this.config.EnableMetrics - //}); - app.UseGraphiQl(config.GraphiQLPath, config.Path); } diff --git a/Plugins/RawCMS.Plugins.GraphQL/Types/CollectionType.cs b/Plugins/RawCMS.Plugins.GraphQL/Types/CollectionType.cs index 55cc8eb2..6970439f 100644 --- a/Plugins/RawCMS.Plugins.GraphQL/Types/CollectionType.cs +++ b/Plugins/RawCMS.Plugins.GraphQL/Types/CollectionType.cs @@ -8,9 +8,12 @@ //****************************************************************************** using GraphQL; using GraphQL.Types; +using Newtonsoft.Json.Linq; using RawCMS.Library.Schema; +using RawCMS.Plugins.GraphQL.Classes; using System; using System.Collections.Generic; +using System.Linq; namespace RawCMS.Plugins.GraphQL.Types { @@ -36,7 +39,8 @@ protected IDictionary FieldTypeToSystemType { FieldBaseType.Float, typeof(float) }, { FieldBaseType.ID, typeof(Guid) }, { FieldBaseType.Int, typeof(int) }, - { FieldBaseType.String, typeof(string) } + { FieldBaseType.String, typeof(string) }, + { FieldBaseType.Object, typeof(JObject) } }; } @@ -54,26 +58,48 @@ private Type ResolveFieldMetaType(FieldBaseType type) return typeof(string); } - public CollectionType(CollectionSchema collectionSchema) + public CollectionType(CollectionSchema collectionSchema, Dictionary collections = null, GraphQLService graphQLService = null) { Name = collectionSchema.CollectionName; foreach (Field field in collectionSchema.FieldSettings) { - InitGraphField(field); + InitGraphField(field, collections, graphQLService); } } - private void InitGraphField(Field field) + private void InitGraphField(Field field, Dictionary collections = null, GraphQLService graphQLService = null) { - Type graphQLType = (ResolveFieldMetaType(field.BaseType)).GetGraphTypeFromType(!field.Required); - FieldType columnField = Field( + Type graphQLType; + if (field.BaseType == FieldBaseType.Object) + { + var relatedObject = collections[field.Type]; + var relatedCollection = new CollectionType(relatedObject, collections); + var listType = new ListGraphType(relatedCollection); + graphQLType = relatedCollection.GetType(); + FieldType columnField = Field( graphQLType, - field.Name - ); + relatedObject.CollectionName); - columnField.Resolver = new NameFieldResolver(); - FillArgs(field.Name, graphQLType); + columnField.Resolver = new NameFieldResolver(); + columnField.Arguments = new QueryArguments(relatedCollection.TableArgs); + foreach(var arg in columnField.Arguments.Where(x=>!(new string[] { "pageNumber", "pageSize", "rawQuery", "_id" }.Contains(x.Name))).ToList()) + { + arg.Name = $"{relatedObject.CollectionName}_{arg.Name}"; + TableArgs.Add(arg); + } + } + else + { + //graphQLType = (ResolveFieldMetaType(field.BaseType)).GetGraphTypeFromType(!field.Required); + graphQLType = (ResolveFieldMetaType(field.BaseType)).GetGraphTypeFromType(true); + FieldType columnField = Field( + graphQLType, + field.Name); + + columnField.Resolver = new NameFieldResolver(); + FillArgs(field.Name, graphQLType); + } } private void FillArgs(string name, Type graphType) diff --git a/Plugins/RawCMS.Plugins.GraphQL/Types/JObjectFieldResolver.cs b/Plugins/RawCMS.Plugins.GraphQL/Types/JObjectFieldResolver.cs index 417dea4a..3ad22629 100644 --- a/Plugins/RawCMS.Plugins.GraphQL/Types/JObjectFieldResolver.cs +++ b/Plugins/RawCMS.Plugins.GraphQL/Types/JObjectFieldResolver.cs @@ -103,11 +103,11 @@ private string BuildMongoQuery(Dictionary arguments) ["$regex"] = $"/*{arguments[key]}/*", ["$options"] = "si" }; - dictionary[key.ToPascalCase()] = reg; + dictionary[key.ToPascalCase().Replace("_",".")] = reg; } else { - dictionary[key.ToPascalCase()] = arguments[key]; + dictionary[key.ToPascalCase().Replace("_", ".")] = arguments[key]; } } query = JsonConvert.SerializeObject(dictionary, jSettings); diff --git a/RawCMS.Client/BLL/Core/ClientConfig.cs b/RawCMS.Client/BLL/Core/ClientConfig.cs new file mode 100644 index 00000000..71f1aebf --- /dev/null +++ b/RawCMS.Client/BLL/Core/ClientConfig.cs @@ -0,0 +1,41 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using Microsoft.Extensions.Configuration; +using System.IO; + +namespace RawCMS.Client.BLL.Core +{ + public class ClientConfig + { + private static IConfigurationBuilder _builder = null; + private static IConfigurationRoot _configuration = null; + + public static IConfigurationRoot Config + { + get + { + if (_configuration == null) + { + _builder = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); + + _configuration = _builder.Build(); + } + return _configuration; + } + set { } + } + + public static T GetValue(string key) + { + return Config.GetValue(key); + } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Core/ConfigFile.cs b/RawCMS.Client/BLL/Core/ConfigFile.cs new file mode 100644 index 00000000..391e0ede --- /dev/null +++ b/RawCMS.Client/BLL/Core/ConfigFile.cs @@ -0,0 +1,44 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using System; + +namespace RawCMS.Client.BLL.Core +{ + public class ConfigFile + { + public string Token { get; set; } + public string ServerUrl { get; set; } + public string User { get; set; } + public string CreatedTime { get; set; } + + public ConfigFile() + { + } + + public ConfigFile(string content) + { + try + { + ConfigFile cf = Newtonsoft.Json.JsonConvert.DeserializeObject(content); + Token = cf.Token; + ServerUrl = cf.ServerUrl; + User = cf.User; + CreatedTime = cf.CreatedTime; + } + catch (Exception) + { + } + } + + public override string ToString() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this); + } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Core/LogProvider.cs b/RawCMS.Client/BLL/Core/LogProvider.cs new file mode 100644 index 00000000..3fb06518 --- /dev/null +++ b/RawCMS.Client/BLL/Core/LogProvider.cs @@ -0,0 +1,43 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + +namespace RawCMS.Client.BLL.Core +{ + public class LogProvider + { + private static ServiceProvider _provider = null; + + public static Runner Runner + { + get + { + if (_provider == null) + { + _provider = new ServiceCollection() + .AddLogging(builder => + { + builder.SetMinimumLevel(LogLevel.Trace); + builder.AddNLog(new NLogProviderOptions + { + CaptureMessageTemplates = true, + CaptureMessageProperties = true + }); + }) + .AddTransient() + .BuildServiceProvider(); + } + + return _provider.GetRequiredService(); + } + } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Core/Runner.cs b/RawCMS.Client/BLL/Core/Runner.cs new file mode 100644 index 00000000..c1b20f80 --- /dev/null +++ b/RawCMS.Client/BLL/Core/Runner.cs @@ -0,0 +1,157 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; + +namespace RawCMS.Client.BLL.Core +{ + public class Runner + { + private readonly ILogger _logger; + + private bool _verbose { get; set; } + private bool _pretty { get; set; } + + public void SetVerbose(bool verbose) + { + _verbose = verbose; + if (_verbose) + { + _logger.LogInformation("verbose mode enabled."); + } + } + + public void SetPretty(bool pretty) + { + _pretty = pretty; + } + + public Runner(ILogger logger) + { + _logger = logger; + } + + public void Debug(int eventId, Exception e, string message, object[] args) + { + _logger.LogDebug(eventId, e, message, args); + } + + public void Debug(string message, object[] args) + { + _logger.LogDebug(message, args); + // to avoid duplicate log line. only in info level + if (_verbose && !_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogInformation(message, args); + } + } + + public void Debug(string message) + { + _logger.LogDebug(message); + // to avoid duplicate log line. only in info level + if (_verbose && !_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogInformation(message); + } + } + + public void Info(string message, object[] args) + { + _logger.LogInformation(message, args); + } + + public void Info(string message) + { + _logger.LogInformation(message); + } + + public void Warn(string message, object[] args) + { + _logger.LogWarning(message, args); + } + + public void Warn(string message) + { + _logger.LogWarning(message); + } + + public void Error(string message, object[] args) + { + _logger.LogError(message, args); + } + + public void Error(string message) + { + _logger.LogError(message); + } + + public void Error(string message, Exception e) + { + _logger.LogError(e, message); + } + + public void Trace(string message, object[] args) + { + _logger.LogTrace(message, args); + } + + public void Trace(string message) + { + _logger.LogTrace(message); + } + + public void Fatal(string message, object[] args) + { + _logger.LogCritical(message, args); + } + + public void Fatal(string message) + { + _logger.LogCritical(message); + } + + internal void Response(string contentResponse) + { + _logDataCall(contentResponse, "Response"); + } + + internal void Request(string contentRequest) + { + _logDataCall(contentRequest, "Request"); + } + + internal void _logDataCall(string content, string direction) + { + string ret = string.Empty; + + if (string.IsNullOrEmpty(content)) + { + Debug("Request has no data."); + return; + } + + if (_pretty) + { + try + { + object obj = JsonConvert.DeserializeObject(content); + ret = JsonConvert.SerializeObject(obj, Formatting.Indented); + } + catch (Exception e) + { + Warn($"error parsing reponse: {e.Message}"); + } + } + + Debug(string.Format("\n------------- {0} -------------\n\n{1}\n\n-------------------------------------\n", direction, ret)); + } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Helper/RawCmsHelper.cs b/RawCMS.Client/BLL/Helper/RawCmsHelper.cs new file mode 100644 index 00000000..14ddad47 --- /dev/null +++ b/RawCMS.Client/BLL/Helper/RawCmsHelper.cs @@ -0,0 +1,168 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RawCMS.Client.BLL.Core; +using RawCMS.Client.BLL.Model; +using RestSharp; +using System; +using System.Collections.Generic; +using System.IO; + +namespace RawCMS.Client.BLL.Helper +{ + public class RawCmsHelper + { + private static Runner log = LogProvider.Runner; + private static readonly string baseUrl = ClientConfig.GetValue("BaseUrl"); + + public static IRestResponse GetData(ListRequest req) + { + string url = $"{baseUrl}/api/CRUD/{req.Collection}"; + + log.Debug($"Service url: {url}"); + + RestClient client = new RestClient(url); + RestRequest request = new RestRequest(Method.GET) + { + //request headers + RequestFormat = DataFormat.Json + }; + request.AddHeader("Content-Type", "application/json"); + + //add parameters and token to request + request.Parameters.Clear(); + request.AddParameter("rawQuery", req.RawQuery); + request.AddParameter("pageNumber", req.PageNumber); + request.AddParameter("pageSize", req.PageSize); + + request.AddParameter("Authorization", "Bearer " + req.Token, ParameterType.HttpHeader); + + //make the API request and get a response + IRestResponse response = client.Execute(request); + + return response; + } + + public static IRestResponse CreateElement(CreateRequest req) + { + string url = $"{baseUrl}/api/CRUD/{req.Collection}"; + + log.Debug($"Server URL: {url}"); + RestClient client = new RestClient(url); + RestRequest request = new RestRequest(Method.POST) + { + //request headers + RequestFormat = DataFormat.Json + }; + request.AddHeader("Content-Type", "application/json"); + + //add parameters and token to request + request.Parameters.Clear(); + request.AddParameter("application/json", req.Data, ParameterType.RequestBody); + request.AddParameter("Authorization", "Bearer " + req.Token, ParameterType.HttpHeader); + + //make the API request and get a response + IRestResponse response = client.Execute(request); + + return response; + } + + public static void ProcessDirectory(bool recursive, Dictionary> fileList, string targetDirectory, string collection = null) + { + // Process the list of files found in the directory. + string[] fileEntries = Directory.GetFiles(targetDirectory); + foreach (string fileName in fileEntries) + { + if (!fileList.ContainsKey(collection)) + { + fileList.Add(collection, new List()); + } + fileList[collection].Add(fileName); + } + + if (recursive) + { + // Recurse into subdirectories of this directory. + // this is the main level, so take care of name + // of folder, thus is name of collection... + + string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory); + foreach (string subdirectory in subdirectoryEntries) + { + ProcessDirectory(recursive, fileList, subdirectory, collection); + } + } + } + + //public static void ProcessFile(Dictionary fileList, string filePath,string collection) + //{ + // fileList.Add(collection, filePath); + //} + + public static int CheckJSON(string filePath) + { + string content = File.ReadAllText(filePath); + if (string.IsNullOrEmpty(content)) + { + return 1; + } + + try + { + JObject obj = JObject.Parse(content); + } + catch (JsonReaderException jex) + { + //Exception in parsing json + log.Error(jex.Message); + return 2; + } + catch (Exception ex) //some other exception + { + log.Error(ex.ToString()); + return 2; + } + return 0; + } + + #region fun + + public static string Message + { + get + { + Random r = new Random(); + return messages[r.Next(messages.Length)]; + } + } + + private static string[] messages = new string[] { +@" +MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMWNMMMMMMMMMMMMMMMMMMMM ______ _____ _____ _ _ _ M +MWNXWMMMMMMKc,dXMMMMMMMMMMMMMMMMMM | ___ \ / __ \ / __ \| (_) | | M +MWXKXNMMMW0;...cKWMMMMMMMMMMMMMMMM | |_/ /__ ___ _| / \/_ __ ___ ___ | / \/| |_ ___ _ __ | |_ M +MWXKKXMMMNkoxd,.':o0WMMMMMMMWMWMWM | // _` \ \ /\ / / | | '_ ` _ \/ __| | | || | |/ _ \ '_ \| __| M +MMMMMMMMXkONN0; .lXMMMMMMKMKMKM | |\ \ (_| |\ V V /| \__/\ | | | | \__ \ | \__/\| | | __/ | | | |_ M +MMMMMMMK:.:kd,. . .dXNWMMMKMKMKM \_| \_\__,_| \_/\_/ \____/_| |_| |_|___/ \____/|_|_|\___|_| |_|\__| M +MMMMMMMO' ... . . .ll,dXMMKMKMKM _ _ _ M +MMMMMMM0' ...... ,o' .xWMKMKMKM | | | (_) M +MMMMMMMX: .;:;,. .l;. .xWMKMKMKM ___ ___ _ __ ___ _ __ ___ __ _ _ __ __| | | |_ _ __ ___ M +MMMMMMMWd. .dO, . .:;,' ,0WMKMKMKM / __/ _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` | | | | '_ \ / _ \ M +MMMMMMMMK; .dX: .,kl.;o'.lXMKMKMKM | (_| (_) | | | | | | | | | | | (_| | | | | (_| | | | | | | | __/ M +MMMMMMMMWO,.c0c .cKd,cOc .xMKMKMKM \___\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_| |_|_|_| |_|\___| M +MMMMMMMMMWk,;kd,,l0XXNXdcl0WKWKWKW M +MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM +" + }; + + #endregion fun + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Helper/TokenHelper.cs b/RawCMS.Client/BLL/Helper/TokenHelper.cs new file mode 100644 index 00000000..a9963466 --- /dev/null +++ b/RawCMS.Client/BLL/Helper/TokenHelper.cs @@ -0,0 +1,110 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using RawCMS.Client.BLL.Core; +using RawCMS.Client.BLL.Model; +using RawCMS.Client.BLL.Parser; +using RestSharp; +using System; +using System.IO; + +namespace RawCMS.Client.BLL.Helper +{ + public class TokenHelper + { + private static Runner log = LogProvider.Runner; + + public static string getToken(LoginOptions opts) + { + //string baseUrl = ClientConfig.GetValue("BaseUrl"); + + string url = $"{opts.ServerUrl}/connect/token"; + + log.Debug($"Server url: {url}"); + + //create RestSharp client and POST request object + RestClient client = new RestClient(url); + RestRequest request = new RestRequest(Method.POST); + + //add GetToken() API method parameters + request.Parameters.Clear(); + request.AddParameter("grant_type", "password"); + + request.AddParameter("username", opts.Username); + request.AddParameter("password", opts.Password); + + request.AddParameter("client_id", opts.ClientId); + request.AddParameter("client_secret", opts.ClientSecret); + request.AddParameter("scoope", "openid"); + + //make the API request and get the response + IRestResponse response = client.Execute(request); + TokenResponse res = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Content); + if (response.IsSuccessful) + { + log.Debug("Success response token"); + return res.access_token; + } + else + { + log.Warn("Unable to get valid token."); + throw new ExceptionToken(res.error, res.error_description); + } + } + + public static void SaveTokenToFile(string filePath, ConfigFile cf) + { + log.Debug("Save config to file..."); + + log.Debug($"FilePath: {filePath}"); + + try + { + using (StreamWriter outputFile = new StreamWriter(filePath)) + { + outputFile.Write(cf.ToString()); + } + } + catch (Exception e) + { + log.Error("The file could not be writed:", e); + } + } + + public static string getTokenFromFile() + { + string token = string.Empty; + log.Debug("get token from file..."); + + string filePath = Environment.GetEnvironmentVariable("RAWCMSCONFIG", EnvironmentVariableTarget.Process); + log.Debug($"Config file: {filePath}"); + + if (string.IsNullOrEmpty(filePath)) + { + log.Warn("Config file not found. Perform login."); + return null; + } + + try + { // Open the text file using a stream reader. + using (StreamReader sr = new StreamReader(filePath)) + { + string data = sr.ReadToEnd(); + ConfigFile config = new ConfigFile(data); + token = config.Token; + log.Debug($"Get token From file:\n---- TOKEN ------\n{token}\n-----------------"); + } + } + catch (Exception e) + { + log.Error("The file could not be read:", e); + } + return token; + } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Model/BaseRequest.cs b/RawCMS.Client/BLL/Model/BaseRequest.cs new file mode 100644 index 00000000..6d30d121 --- /dev/null +++ b/RawCMS.Client/BLL/Model/BaseRequest.cs @@ -0,0 +1,17 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +namespace RawCMS.Client.BLL.Model +{ + public class BaseRequest + { + public string Token { get; set; } + public string Collection { get; set; } + public string RawQuery { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Model/CreateRequest.cs b/RawCMS.Client/BLL/Model/CreateRequest.cs new file mode 100644 index 00000000..57098466 --- /dev/null +++ b/RawCMS.Client/BLL/Model/CreateRequest.cs @@ -0,0 +1,15 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +namespace RawCMS.Client.BLL.Model +{ + public class CreateRequest : BaseRequest + { + public string Data { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Model/ExceptionToken.cs b/RawCMS.Client/BLL/Model/ExceptionToken.cs new file mode 100644 index 00000000..2af0613a --- /dev/null +++ b/RawCMS.Client/BLL/Model/ExceptionToken.cs @@ -0,0 +1,31 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using System; + +namespace RawCMS.Client.BLL.Model +{ + public class ExceptionToken : Exception + { + public string Code { get; set; } + public string OriginalCode { get; set; } + public string Message { get; set; } + + public ExceptionToken(string Code, string message) : this(Code, message, null) + { + this.Code = Code; + Message = message; + } + + public ExceptionToken(string Code, string message, Exception inner) : base(message, inner) + { + this.Code = OriginalCode = Code; + Message = message; + } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Model/ListRequest.cs b/RawCMS.Client/BLL/Model/ListRequest.cs new file mode 100644 index 00000000..0d6a72ae --- /dev/null +++ b/RawCMS.Client/BLL/Model/ListRequest.cs @@ -0,0 +1,17 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +namespace RawCMS.Client.BLL.Model +{ + public class ListRequest : BaseRequest + { + public int PageNumber { get; set; } + public int PageSize { get; set; } + public string Id { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Model/TokenResponse.cs b/RawCMS.Client/BLL/Model/TokenResponse.cs new file mode 100644 index 00000000..b81088b2 --- /dev/null +++ b/RawCMS.Client/BLL/Model/TokenResponse.cs @@ -0,0 +1,20 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +namespace RawCMS.Client.BLL.Model +{ + public class TokenResponse + { + public string access_token { get; set; } + public int expires_in { get; set; } + public string token_type { get; set; } + + public string error { get; set; } + public string error_description { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Parser/ClientOptions.cs b/RawCMS.Client/BLL/Parser/ClientOptions.cs new file mode 100644 index 00000000..197e4183 --- /dev/null +++ b/RawCMS.Client/BLL/Parser/ClientOptions.cs @@ -0,0 +1,25 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using CommandLine; + +namespace RawCMS.Client.BLL.Parser +{ + [Verb("client", HelpText = "set client configuration")] + public class ClientOptions + { + //[Option('s', "syncronize", Required = false, HelpText = "File path to synchronize the db.")] + //public string SincronizationFile { get; set; } + + //[Option('r',"purge", Default = false, HelpText = "Remove data during syncronization. Only with syncronization (-s)")] + //public bool RemoveData { get; set; } + + //[Option('d', "data", Required = false, HelpText = "file path contains data. using with create, update")] + //public string DataFile { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Parser/DeleteOptions.cs b/RawCMS.Client/BLL/Parser/DeleteOptions.cs new file mode 100644 index 00000000..15b6f471 --- /dev/null +++ b/RawCMS.Client/BLL/Parser/DeleteOptions.cs @@ -0,0 +1,40 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using CommandLine; + +namespace RawCMS.Client.BLL.Parser +{ + [Verb("delete", HelpText = "delete data inside collection")] + public class DeleteOptions + { + [Option('v', "verbose", Default = false, HelpText = "Prints all messages to standard output.")] + public bool Verbose { get; set; } + + [Option('c', "collection", Required = true, HelpText = "Collection where to do the operation.")] + public string Collection { get; set; } + + [Option('i', "id", Required = false, HelpText = "object id to delete.")] + public string Id { get; set; } + + [Option('k', "key-id", Required = false, HelpText = "the name of key id instead of default id.")] + public string KeyId { get; set; } + + [Option('f', "file", SetName = "file", HelpText = "Fle contains data to delete into collection. it can be a json file well-formatted.")] + public string FilePath { get; set; } + + [Option('d', "folder", SetName = "file", HelpText = "Folder contains data to delete into collection. it can be a json file well-formatted.")] + public string FolderPath { get; set; } + + [Option('r', "recursive", Required = false, HelpText = "Fle path contains data to delete into collection. it can be a json file well-formatted.")] + public bool Recursive { get; set; } + + [Option('t', "dry-run", Required = false, HelpText = "do not perform any operations, just make a try.")] + public bool DryRun { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Parser/InsertOptions.cs b/RawCMS.Client/BLL/Parser/InsertOptions.cs new file mode 100644 index 00000000..9422e987 --- /dev/null +++ b/RawCMS.Client/BLL/Parser/InsertOptions.cs @@ -0,0 +1,37 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using CommandLine; + +namespace RawCMS.Client.BLL.Parser +{ + [Verb("insert", HelpText = "insert data inside collection")] + public class InsertOptions + { + [Option('v', "verbose", Default = false, HelpText = "Prints all messages to standard output.")] + public bool Verbose { get; set; } + + [Option('p', "pretty", Default = false, HelpText = "Format JSON output.")] + public bool Pretty { get; set; } + + [Option('c', "collection", Required = true, HelpText = "Collection where to do the operation.")] + public string Collection { get; set; } + + [Option('f', "file", SetName = "file", HelpText = "Fle contains data to insert into collection. it can be a json file well-formatted.")] + public string FilePath { get; set; } + + [Option('d', "folder", SetName = "file", HelpText = "Folder contains data to insert into collection. it can be a json file well-formatted.")] + public string FolderPath { get; set; } + + [Option('r', "recursive", Required = false, HelpText = "Fle path contains data to insert into collection. it can be a json file well-formatted.")] + public bool Recursive { get; set; } + + [Option('t', "dry-run", Required = false, HelpText = "do not perform any operations, just make a try.")] + public bool DryRun { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Parser/ListOptions.cs b/RawCMS.Client/BLL/Parser/ListOptions.cs new file mode 100644 index 00000000..f3e82259 --- /dev/null +++ b/RawCMS.Client/BLL/Parser/ListOptions.cs @@ -0,0 +1,44 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using CommandLine; + +namespace RawCMS.Client.BLL.Parser +{ + [Verb("list", HelpText = "list data from collection: with -id params, get element by id")] + public class ListOptions + { + [Verb("users", HelpText = "users collections")] + public class UsersOptions + { + [Option("id", Required = false, HelpText = "get user by id")] + public string Id { get; set; } + } + + [Option('v', "verbose", Default = false, HelpText = "Prints all messages to standard output.")] + public bool Verbose { get; set; } + + [Option('p', "pretty", Default = false, HelpText = "Format JSON output.")] + public bool Pretty { get; set; } + + [Option('c', "collection", Required = true, HelpText = "Collection where to do the operation.")] + public string Collection { get; set; } + + [Option('i', "id", Required = false, HelpText = "Element id to get.")] + public string Id { get; set; } + + [Option('s', "page-size", Required = false, HelpText = "Page Size, default 10")] + public int PageSize { get; set; } + + [Option('n', "page-number", Required = false, HelpText = "Page Number, default 1")] + public int PageNumber { get; set; } + + [Option('r', "raw-query", Required = false, HelpText = "Raw query.")] + public string RawQuery { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Parser/LoginOptions.cs b/RawCMS.Client/BLL/Parser/LoginOptions.cs new file mode 100644 index 00000000..5c9779eb --- /dev/null +++ b/RawCMS.Client/BLL/Parser/LoginOptions.cs @@ -0,0 +1,34 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using CommandLine; + +namespace RawCMS.Client.BLL.Parser +{ + [Verb("login", HelpText = "Login. Required also (-u) username, (-p) password, (-i) client id, (-t) client secret")] + public class LoginOptions + { + [Option('v', "verbose", Default = false, HelpText = "Prints all messages to standard output.")] + public bool Verbose { get; set; } + + [Option('u', "username", Required = true, HelpText = "Username")] + public string Username { get; set; } + + [Option('p', "password", Required = true, HelpText = "Password")] + public string Password { get; set; } + + [Option('i', "client-id", Required = true, HelpText = "Client id")] + public string ClientId { get; set; } + + [Option('t', "client-secret", Required = true, HelpText = "Client secret")] + public string ClientSecret { get; set; } + + [Option('s', "server-url", Required = true, HelpText = "Server URL")] + public string ServerUrl { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Parser/PatchOptions.cs b/RawCMS.Client/BLL/Parser/PatchOptions.cs new file mode 100644 index 00000000..bf94b593 --- /dev/null +++ b/RawCMS.Client/BLL/Parser/PatchOptions.cs @@ -0,0 +1,40 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using CommandLine; + +namespace RawCMS.Client.BLL.Parser +{ + [Verb("patch", HelpText = "patch data inside collection")] + public class PatchOptions + { + [Option('v', "verbose", Default = false, HelpText = "Prints all messages to standard output.")] + public bool Verbose { get; set; } + + [Option('c', "collection", Required = true, HelpText = "Collection where to do the operation.")] + public string Collection { get; set; } + + [Option('i', "id", Required = false, HelpText = "object id to patch.")] + public string Id { get; set; } + + [Option('k', "key-id", Required = false, HelpText = "the name of key id instead of default id.")] + public string KeyId { get; set; } + + [Option('f', "file", SetName = "file", HelpText = "Fle contains data to patch into collection. it can be a json file well-formatted.")] + public string FilePath { get; set; } + + [Option('d', "folder", SetName = "file", HelpText = "Folder contains data to patch into collection. it can be a json file well-formatted.")] + public string FolderPath { get; set; } + + [Option('r', "recursive", Required = false, HelpText = "Fle path contains data to patch into collection. it can be a json file well-formatted.")] + public bool Recursive { get; set; } + + [Option('t', "dry-run", Required = false, HelpText = "do not perform any operations, just make a try.")] + public bool DryRun { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/BLL/Parser/ReplaceOptions.cs b/RawCMS.Client/BLL/Parser/ReplaceOptions.cs new file mode 100644 index 00000000..82c286e7 --- /dev/null +++ b/RawCMS.Client/BLL/Parser/ReplaceOptions.cs @@ -0,0 +1,40 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using CommandLine; + +namespace RawCMS.Client.BLL.Parser +{ + [Verb("replace", HelpText = "replace data inside collection")] + public class ReplaceOptions + { + [Option('v', "verbose", Default = false, HelpText = "Prints all messages to standard output.")] + public bool Verbose { get; set; } + + [Option('c', "collection", Required = true, HelpText = "Collection where to do the operation.")] + public string Collection { get; set; } + + [Option('i', "id", Required = false, HelpText = "object id to replace.")] + public string Id { get; set; } + + [Option('k', "key-id", Required = false, HelpText = "the name of key id instead of default id.")] + public string KeyId { get; set; } + + [Option('f', "file", SetName = "file", HelpText = "Fle contains data to replace into collection. it can be a json file well-formatted.")] + public string FilePath { get; set; } + + [Option('d', "folder", SetName = "file", HelpText = "Folder contains data to replace into collection. it can be a json file well-formatted.")] + public string FolderPath { get; set; } + + [Option('r', "recursive", Required = false, HelpText = "Fle path contains data to replace into collection. it can be a json file well-formatted.")] + public bool Recursive { get; set; } + + [Option('t', "dry-run", Required = false, HelpText = "do not perform any operations, just make a try.")] + public bool DryRun { get; set; } + } +} \ No newline at end of file diff --git a/RawCMS.Client/Program.cs b/RawCMS.Client/Program.cs new file mode 100644 index 00000000..5806deb3 --- /dev/null +++ b/RawCMS.Client/Program.cs @@ -0,0 +1,345 @@ +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// true +//****************************************************************************** +using CommandLine; +using RawCMS.Client.BLL.Core; +using RawCMS.Client.BLL.Helper; +using RawCMS.Client.BLL.Model; +using RawCMS.Client.BLL.Parser; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace RawCMS.Client +{ + internal class Program + { + private static Runner log = LogProvider.Runner; + + private static int Main(string[] args) + { + Console.WriteLine(RawCmsHelper.Message); + + int ret = Parser.Default.ParseArguments(args) + .MapResult( + (ClientOptions opts) => RunClientOptionsCode(opts), + (LoginOptions opts) => RunLoginOptionsCode(opts), + (ListOptions opts) => RunListOptionsCode(opts), + (InsertOptions opts) => RunInsertOptionsCode(opts), + (ReplaceOptions opts) => RunReplacetOptionsCode(opts), + (DeleteOptions opts) => RunDeleteOptionsCode(opts), + (PatchOptions opts) => RunPatchOptionsCode(opts), + + errs => RunErrorCode(errs)); + + log.Info("Done."); + return ret; + } + + private static int RunPatchOptionsCode(PatchOptions opts) + { + throw new NotImplementedException(); + } + + private static int RunDeleteOptionsCode(DeleteOptions opts) + { + throw new NotImplementedException(); + } + + private static int RunReplacetOptionsCode(ReplaceOptions opts) + { + throw new NotImplementedException(); + } + + private static int RunErrorCode(IEnumerable errs) + { + //log.Warn("Some parameters are missing:"); + //foreach (MissingRequiredOptionError item in errs) + //{ + // log.Warn($"Missing: {item.NameInfo.NameText}"); + + //} + return 1; + } + + private static int RunInsertOptionsCode(InsertOptions opts) + { + bool Verbose = opts.Verbose; + bool Recursive = opts.Recursive; + bool DryRun = opts.DryRun; + bool Pretty = opts.Pretty; + string collection = opts.Collection; + string filePath = opts.FilePath; + string folderPath = opts.FolderPath; + + // setting log/console Output + log.SetVerbose(Verbose); + log.SetPretty(Pretty); + + // check token befare action.. + string token = TokenHelper.getTokenFromFile(); + + if (string.IsNullOrEmpty(token)) + { + log.Warn("No token found. Please login before continue."); + log.Warn("Program aborted."); + return 0; + }; + + log.Debug($"Working into collection: {collection}"); + + Dictionary> listFile = new Dictionary>(); + + // pass a file to options + if (!string.IsNullOrEmpty(filePath)) + { + // check if file exists + if (!File.Exists(filePath)) + { + log.Warn($"File not found: {filePath}"); + return 0; + } + + // check if file is valid json + + int check = RawCmsHelper.CheckJSON(filePath); + + if (check != 0) + { + log.Warn("Json is not well-formatted. Skip file."); + return 0; + } + List filelist = new List + { + filePath + }; + listFile.Add(collection, filelist); + } + else if (!string.IsNullOrEmpty(folderPath)) + { + string cwd = Directory.GetCurrentDirectory(); + log.Info($"Current working directory: {cwd}"); + + // get all file from folder + if (!Directory.Exists(folderPath)) + { + log.Warn($"File not found: {filePath}"); + return 0; + } + + // This path is a directory + // get first level path, + // folder => collection + DirectoryInfo dInfo = new DirectoryInfo(folderPath); + DirectoryInfo[] subdirs = dInfo.GetDirectories(); + + foreach (DirectoryInfo subDir in subdirs) + { + RawCmsHelper.ProcessDirectory(Recursive, listFile, subDir.FullName, subDir.Name); + } + } + else + { + log.Warn("At least one of the two options -f (file) or -d (folder) is mandatory."); + return 0; + } + + elaborateQueue(listFile, token, Pretty); + + log.Info($"Processing file complete."); + return 0; + } + + private static void elaborateQueue(Dictionary> listFile, string token, bool pretty) + { + int totalfile = listFile.Sum(x => x.Value.Count); + int partialOfTotal = 0; + + foreach (KeyValuePair> c in listFile) + { + int progress = 0; + + foreach (string item in c.Value) + { + log.Info($"Processing file {++progress} of {c.Value.Count} in collection: {c.Key}"); + + string contentFile = File.ReadAllText(item); + + log.Request(contentFile); + + RestSharp.IRestResponse responseRawCMS = RawCmsHelper.CreateElement(new CreateRequest + { + Collection = c.Key, + Data = contentFile, + Token = token + }); + + log.Debug($"RawCMS response code: {responseRawCMS.StatusCode}"); + + if (!responseRawCMS.IsSuccessful) + { + //log.Error($"Error occurred: \n{responseRawCMS.Content}"); + log.Error($"Error: {responseRawCMS.ErrorMessage}"); + } + else + { + log.Response(responseRawCMS.Content); + } + + //switch (responseRawCMS.ResponseStatus) + //{ + // case RestSharp.ResponseStatus.Completed: + // log.Response(responseRawCMS.Content); + + // break; + + // case RestSharp.ResponseStatus.None: + // case RestSharp.ResponseStatus.Error: + // case RestSharp.ResponseStatus.TimedOut: + // case RestSharp.ResponseStatus.Aborted: + + // default: + // log.Error($"Error response: {responseRawCMS.ErrorMessage}"); + // break; + //} + + log.Info($"File processed\n\tCollection progress: {progress} of {c.Value.Count}\n\tTotal progress: {++partialOfTotal} of {totalfile}\n\tFile: {item}\n\tCollection: {c.Key}"); + } + } + } + + private static int RunListOptionsCode(ListOptions opts) + { + bool Verbose = opts.Verbose; + log.SetVerbose(Verbose); + + bool Pretty = opts.Pretty; + log.SetPretty(Pretty); + + int PageSize = opts.PageSize; + int PageNumber = opts.PageNumber; + string RawQuery = opts.RawQuery; + + string id = opts.Id; + string collection = opts.Collection; + + // check token befare action.. + string token = TokenHelper.getTokenFromFile(); + + if (string.IsNullOrEmpty(token)) + { + log.Warn("No token found. Please login."); + return 0; + }; + + log.Debug($"Perform action in collection: {collection}"); + + ListRequest req = new ListRequest + { + Collection = collection, + Token = token, + PageNumber = PageNumber < 1 ? 1 : PageNumber, + PageSize = PageSize < 1 ? 10 : PageSize, + RawQuery = RawQuery, + }; + + if (!string.IsNullOrEmpty(id)) + { + req.Id = id; + } + + RestSharp.IRestResponse responseRawCMS = RawCmsHelper.GetData(req); + + log.Debug($"RawCMS response code: {responseRawCMS.StatusCode}"); + + if (!responseRawCMS.IsSuccessful) + { + //log.Error($"Error occurred: \n{responseRawCMS.Content}"); + log.Error($"Error: {responseRawCMS.ErrorMessage}"); + } + else + { + log.Response(responseRawCMS.Content); + } + + //switch (responseRawCMS.ResponseStatus) + //{ + // case RestSharp.ResponseStatus.Completed: + + // break; + + // case RestSharp.ResponseStatus.None: + // case RestSharp.ResponseStatus.Error: + // case RestSharp.ResponseStatus.TimedOut: + // case RestSharp.ResponseStatus.Aborted: + + // default: + // log.Error($"Error response: {responseRawCMS.ErrorMessage}"); + // break; + //} + + return 0; + } + + private static int RunLoginOptionsCode(LoginOptions opts) + { + bool Verbose = false; + log.SetVerbose(Verbose); + + string token = string.Empty; + + try + { + token = TokenHelper.getToken(opts); + log.Debug($"\n---- TOKEN ------\n{token}\n-----------------"); + } + catch (ExceptionToken e) + { + log.Error($"token error:"); + log.Error($"\t{e.Code}, {e.Message}"); + return 2; + } + catch (Exception e) + { + log.Error("token error", e); + return 2; + } + + if (string.IsNullOrEmpty(token)) + { + log.Warn("Unable to get token. check if data are correct and retry."); + return 2; + } + + string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + string fileconfigname = ClientConfig.GetValue("ConfigFile"); + fileconfigname = string.Format(fileconfigname, opts.Username); + string filePath = System.IO.Path.Combine(mydocpath, fileconfigname); + + ConfigFile cf = new ConfigFile + { + Token = token, + CreatedTime = DateTime.Now.ToShortDateString(), + ServerUrl = opts.ServerUrl, + User = opts.Username + }; + + TokenHelper.SaveTokenToFile(filePath, cf); + + log.Info($"set enviroinment configuration: (copy, paste and hit return in console):\nSET RAWCMSCONFIG={filePath}"); + + return 0; + } + + private static int RunClientOptionsCode(ClientOptions opts) + { + return 0; + } + } +} \ No newline at end of file diff --git a/RawCMS.Client/RawCMS.Client.csproj b/RawCMS.Client/RawCMS.Client.csproj new file mode 100644 index 00000000..a4b12c91 --- /dev/null +++ b/RawCMS.Client/RawCMS.Client.csproj @@ -0,0 +1,34 @@ + + + + Exe + netcoreapp2.0 + + + + + + + + + + Always + + + PreserveNewest + + + + + + + + + + + + + + + + diff --git a/RawCMS.Client/appsettings.json b/RawCMS.Client/appsettings.json new file mode 100644 index 00000000..9bed9235 --- /dev/null +++ b/RawCMS.Client/appsettings.json @@ -0,0 +1,4 @@ +{ + "BaseUrl": "http://localhost:49439", + "ConfigFile": "RawCMS.{0}.config" +} \ No newline at end of file diff --git a/RawCMS.Client/nlog.config b/RawCMS.Client/nlog.config new file mode 100644 index 00000000..8118f93f --- /dev/null +++ b/RawCMS.Client/nlog.config @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/RawCMS.Library/Schema/CollectionSchema.cs b/RawCMS.Library/Schema/CollectionSchema.cs index 8599a792..f8c22a0f 100644 --- a/RawCMS.Library/Schema/CollectionSchema.cs +++ b/RawCMS.Library/Schema/CollectionSchema.cs @@ -1,4 +1,12 @@ -using Newtonsoft.Json; +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Min� +// true +//****************************************************************************** +using Newtonsoft.Json; using Newtonsoft.Json.Converters; //****************************************************************************** diff --git a/RawCMS.Library/Schema/Field.cs b/RawCMS.Library/Schema/Field.cs index 32f44783..dae1d6d2 100644 --- a/RawCMS.Library/Schema/Field.cs +++ b/RawCMS.Library/Schema/Field.cs @@ -1,4 +1,12 @@ -using Newtonsoft.Json; +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Min� +// true +//****************************************************************************** +using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System; diff --git a/RawCMS.Library/Schema/FieldBaseType.cs b/RawCMS.Library/Schema/FieldBaseType.cs index 8eac33ea..9e052695 100644 --- a/RawCMS.Library/Schema/FieldBaseType.cs +++ b/RawCMS.Library/Schema/FieldBaseType.cs @@ -1,4 +1,12 @@ -using System; +//****************************************************************************** +// +// Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) +// RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . +// +// Daniele Fontani, Emanuele Bucarelli, Francesco Min� +// true +//****************************************************************************** +using System; using System.Collections.Generic; using System.Text; @@ -11,6 +19,7 @@ public enum FieldBaseType String, Boolean, ID, - Date + Date, + Object } } diff --git a/RawCMS.sln b/RawCMS.sln index 20f85cfb..1f17dcca 100644 --- a/RawCMS.sln +++ b/RawCMS.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.26730.10 +VisualStudioVersion = 15.0.27130.2027 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RawCMS", "RawCMS\RawCMS.csproj", "{0173DCCE-34BA-4988-BA6C-07880C3F71A0}" EndProject @@ -41,6 +41,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{18F5053A-6 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RawCMS.Plugins.GraphQL", "Plugins\RawCMS.Plugins.GraphQL\RawCMS.Plugins.GraphQL.csproj", "{2C443D9E-BDDE-4147-9EE4-7E93652EE7EC}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RawCMS.Client", "RawCMS.Client\RawCMS.Client.csproj", "{4F469A2E-821C-4604-B686-040E165082D8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -67,6 +69,10 @@ Global {2C443D9E-BDDE-4147-9EE4-7E93652EE7EC}.Debug|Any CPU.Build.0 = Debug|Any CPU {2C443D9E-BDDE-4147-9EE4-7E93652EE7EC}.Release|Any CPU.ActiveCfg = Release|Any CPU {2C443D9E-BDDE-4147-9EE4-7E93652EE7EC}.Release|Any CPU.Build.0 = Release|Any CPU + {4F469A2E-821C-4604-B686-040E165082D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4F469A2E-821C-4604-B686-040E165082D8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4F469A2E-821C-4604-B686-040E165082D8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4F469A2E-821C-4604-B686-040E165082D8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/RawCMS.sln.licenseheader b/RawCMS.sln.licenseheader index 4cbb9b0e..2ff1808c 100644 --- a/RawCMS.sln.licenseheader +++ b/RawCMS.sln.licenseheader @@ -5,7 +5,7 @@ extensions: .cs .cpp .h // Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) // RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . // -// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// Daniele Fontani, Emanuele Bucarelli, Francesco Mina' // true //****************************************************************************** extensions: .aspx .ascx @@ -16,7 +16,7 @@ extensions: .aspx .ascx // RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . // // true -// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// Daniele Fontani, Emanuele Bucarelli, Francesco Mina' //****************************************************************************** --%> extensions: .vb @@ -28,7 +28,7 @@ extensions: .xml .config .xsd // Copyright (c) 2019 RawCMS project (https://github.com/arduosoft/RawCMS) // RawCMS project is released under GPL3 terms, see LICENSE file on repository root at https://github.com/arduosoft/RawCMS . // -// Daniele Fontani, Emanuele Bucarelli, Francesco Minà +// Daniele Fontani, Emanuele Bucarelli, Francesco Mina' // true //****************************************************************************** --> \ No newline at end of file diff --git a/RawCMS/RawCMS.csproj b/RawCMS/RawCMS.csproj index be3835fa..fb3b2254 100644 --- a/RawCMS/RawCMS.csproj +++ b/RawCMS/RawCMS.csproj @@ -10,12 +10,18 @@ - + + + + + + + + - - + diff --git a/docs b/docs index 5a3a7994..f7ce2133 160000 --- a/docs +++ b/docs @@ -1 +1 @@ -Subproject commit 5a3a799475a632a0c260e3381a8c306a9e34580c +Subproject commit f7ce21333de260595556a487ec793e9354ae4677