WorkspaceSyncCommand.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.ComponentModel.Design;
  5. using System.IO.Abstractions;
  6. using System.Linq;
  7. using BO.AppServer.Metadata.Dto;
  8. using BO.AppServer.Metadata.Enums;
  9. using BO.Console.Commands.Base;
  10. using BO.Console.Commands.Workspace.Sync;
  11. using BO.Console.Commands.Workspace.Sync.Diff;
  12. using Quadarax.Foundation.Core.Data.Diff;
  13. using Quadarax.Foundation.Core.IO;
  14. using Quadarax.Foundation.Core.QConsole;
  15. using Quadarax.Foundation.Core.QConsole.Argument;
  16. using Quadarax.Foundation.Core.QConsole.Attributes;
  17. using Quadarax.Foundation.Core.QConsole.Value;
  18. using Quadarax.Foundation.Core.Value;
  19. namespace BO.Console.Commands.Workspace
  20. {
  21. [CommandDefinition]
  22. internal class WorkspaceSyncCommand : AbstractWorkspaceCommand
  23. {
  24. #region *** Constants ***
  25. private const string CS_NEW_IN = ".in";
  26. private const string CS_NEW_OUT = ".out";
  27. private const string CS_NOTES = "Directory structure:\n" +
  28. "["+CS_NEW_IN + "]\t- new artifacts directory for Input type\n" +
  29. "\t\t<doc_name>.<artifact_name>.<artifact_ext> - new artifacts file\n" +
  30. "\t\t...\n" +
  31. "[" +CS_NEW_OUT + "]\t- new artifacts directory for Output type\n" +
  32. "[<documentId:8>.<document_name_normalized>]\t- document directory\n" +
  33. "\t\t<arifact_id>.<artifact_type>.<artifact_name>.<artifaxt_ext> - artifact file\n" +
  34. "\t\t...\n" +
  35. "...\n" +
  36. "\n" +
  37. "Process sequence:\n" +
  38. "0. If init flag set, sync clean directory\n" +
  39. "1. Get workspace documents with artifacts -> srv_arts\n" +
  40. "2. Get sync directory documents with artifacts (skip not well formatted, process incomming also) -> loac_arts\n" +
  41. "3. Resolve differences srv_arts and loc_ars -> changed_arts\n" +
  42. "4. Push changes changed_arts to database (if delete flag set removes documents in database)\n" +
  43. "5. Pull changes changed_arts from database (if delete flag set removes documents in sync directory)\n" +
  44. "6. Cleanup incommings\n" +
  45. "7. If repeat set go to step 1.\n";
  46. private const string CS_CMD_WRKSPSYNC_NAME = "workspace_sync";
  47. private const string CS_CMD_WRKSPSYNC_DESCR = "Download or upload documents from local directory from/to workspace. Can be run as contignous process.";
  48. private const string CS_ARG_NAME_DIR = "directory";
  49. private const string CS_ARG_HINT_DIR = "<sync_directory>";
  50. private const string CS_ARG_DESC_DIR = "Defines sync directory, if not defined workspace directory will be created as workspace name.";
  51. private const string CS_ARG_NAME_WD = "repeat";
  52. private const string CS_ARG_HINT_WD = "<is_repeat>";
  53. private const string CS_ARG_DESC_WD = "Flag if defined, enables contignous monitoring on sync directory for changes. If not defined process will be run once.";
  54. private const string CS_ARG_NAME_DELETE = "delete";
  55. private const string CS_ARG_HINT_DELETE = "<is_delete_allowed>";
  56. private const string CS_ARG_DESC_DELETE = "Flag if defined, deletes documents in application server when document is deleted in sync directory.";
  57. private const string CS_ARG_NAME_INIT = "init";
  58. private const string CS_ARG_HINT_INIT = "<is_initialization>";
  59. private const string CS_ARG_DESC_INIT = "Flag if defined, reset sync directory during initialization (all content in sync directory will be deleted on start).";
  60. private const string CS_ARG_NAME_INT = "interval";
  61. private const string CS_ARG_HINT_INT = "<repeat_interval>";
  62. private const string CS_ARG_DESC_INT = "Timespan interval between two iterations. Default is 00:30:00.";
  63. #endregion
  64. #region *** Properties ***
  65. public override string Name => CS_CMD_WRKSPSYNC_NAME;
  66. public override string Description => CS_CMD_WRKSPSYNC_DESCR;
  67. public override string Notes => CS_NOTES;
  68. private string SyncDir { get; set; }
  69. private bool IsRepeat { get; set; }
  70. private bool IsInit { get; set; }
  71. private bool IsDeleteAllowed { get; set; }
  72. private TimeSpan Interval { get; set; }
  73. #endregion
  74. #region *** Constructor ***
  75. public WorkspaceSyncCommand(Engine engine) : base(engine)
  76. {
  77. }
  78. #endregion
  79. #region *** EXECUTE ***
  80. protected override Result OnExecute()
  81. {
  82. bool isExitSignal = false;
  83. int nCnt = 0;
  84. while (!isExitSignal)
  85. {
  86. if (!IsRepeat)
  87. isExitSignal = true;
  88. var workspace = Client.GetWorkspaceAsync(WorkspaceIdentificationTypeEnum.ApiKey, ApiKey).Result;
  89. if (workspace == null)
  90. return new Result(new Exception($"Workspace with API-KEY: {ApiKey} not found."));
  91. var documents = Client.GetWorkspaceDocumentsAsync(DocumentsScopeEnums.All, ApiKey, ApiKeyPassword, UserName).Result;
  92. var dirInfo = OpenDirectory(workspace);
  93. var factory = new DocumentEntryComparer();
  94. foreach (var dir in dirInfo.EnumerateDirectories())
  95. {
  96. if (string.Equals(dir.Name, CS_NEW_IN, StringComparison.CurrentCultureIgnoreCase))
  97. {
  98. foreach (var file in dir.GetFiles())
  99. factory.AddLocalDocumentNew(file.Name,true);
  100. continue;
  101. }
  102. if (string.Equals(dir.Name, CS_NEW_OUT, StringComparison.CurrentCultureIgnoreCase))
  103. {
  104. foreach (var file in dir.GetFiles())
  105. factory.AddLocalDocumentNew(file.Name,false);
  106. continue;
  107. }
  108. if (factory.ValidateDocumentDirectory(dir.Name))
  109. {
  110. foreach (var file in dir.GetFiles())
  111. {
  112. if (factory.ValidateArtifactFileName(file.Name))
  113. {
  114. factory.AddLocalDocument(dir.Name, file.Name, file.Length);
  115. }
  116. else
  117. {
  118. WriteWarning($"Invalid artifact file '{file.Name}' name format! Expects '<arifact_id>.<artifact_type>.<artifact_name>.<artifaxt_ext>'. Skip");
  119. }
  120. }
  121. }
  122. else
  123. {
  124. WriteWarning($"Invalid document directory '{dir.Name}' name format! Expects '<documentId:8>.<document_name_normalized>'. Skip");
  125. }
  126. }
  127. foreach (var document in documents)
  128. {
  129. factory.AddRemoteDocument(document);
  130. }
  131. var diff = factory.GetComparator();
  132. var locals = diff.CompareLeftSide().Where(x => x.CompareState != DiffEntry.CompareStateEnum.Equals);
  133. foreach (var local in locals)
  134. {
  135. var item = local.GetItem<DocumentItem>();
  136. if (local.CompareState == DiffEntry.CompareStateEnum.CurrentNull ||
  137. local.CompareState == DiffEntry.CompareStateEnum.CurrentSmaller)
  138. {
  139. WriteInfo($"Artifact '{item.ArtName}' will be downloaded");
  140. }
  141. else if (local.CompareState == DiffEntry.CompareStateEnum.CurrentGrater ||
  142. local.CompareState == DiffEntry.CompareStateEnum.OtherNull)
  143. {
  144. WriteInfo($"Artifact '{item.ArtName}' will be uploaded");
  145. }
  146. }
  147. }
  148. return new Result();
  149. }
  150. private IDirectoryInfo OpenDirectory(WorkspaceRDto workspace)
  151. {
  152. if (workspace == null)
  153. throw new ArgumentNullException(nameof(workspace));
  154. if (string.IsNullOrEmpty(SyncDir))
  155. {
  156. // Current dir
  157. SyncDir = FileSystem.Path.Combine(FileSystem.Directory.GetCurrentDirectory(), FileUtils.SanitizedFileName(FileSystem, workspace.Name));
  158. }
  159. if (IsInit)
  160. {
  161. if (FileSystem.Directory.Exists(SyncDir))
  162. {
  163. FileSystem.Directory.Delete(SyncDir,true);
  164. WriteDebugInfo($"Directory '{SyncDir}' deleted due 'init' mode.");
  165. }
  166. IsInit = false;
  167. }
  168. if (!FileSystem.Directory.Exists(SyncDir))
  169. {
  170. FileSystem.Directory.CreateDirectory(SyncDir);
  171. WriteInfo($"Sync directory '{SyncDir}' created.");
  172. var inDir = FileSystem.Path.Combine(SyncDir, CS_NEW_IN);
  173. FileSystem.Directory.CreateDirectory(inDir);
  174. WriteDebugInfo($"Directory '{inDir}' created.");
  175. inDir = FileSystem.Path.Combine(SyncDir, CS_NEW_OUT);
  176. FileSystem.Directory.CreateDirectory(inDir);
  177. WriteDebugInfo($"Directory '{inDir}' created.");
  178. }
  179. var di = FileSystem.DirectoryInfo.FromDirectoryName(SyncDir);
  180. WriteCaption($"Sync directory '{SyncDir}' opened.");
  181. return di;
  182. }
  183. #endregion
  184. #region *** Private operations ***
  185. protected override void OnValidateArguments()
  186. {
  187. base.OnValidateArguments();
  188. SyncDir = GetArgumentValueOrDefault<string>(CS_ARG_NAME_DIR);
  189. IsRepeat = GetArgumentValueOrDefault<bool>(CS_ARG_NAME_WD);
  190. IsInit = GetArgumentValueOrDefault<bool>(CS_ARG_NAME_INIT);
  191. IsDeleteAllowed = GetArgumentValueOrDefault<bool>(CS_ARG_NAME_DELETE);
  192. Interval = GetArgumentValueOrDefault<TimeSpan>(CS_ARG_NAME_INT);
  193. }
  194. protected override IEnumerable<AbstractArgument> OnSetupArguments()
  195. {
  196. var args = base.OnSetupArguments().ToList();
  197. args.Add(new NamedArgument(CS_ARG_NAME_DIR, CS_ARG_DESC_DIR, CS_ARG_HINT_DIR, TypeValuesEnum.String, string.Empty, false));
  198. args.Add(new FlagArgument(CS_ARG_NAME_WD, CS_ARG_DESC_WD, CS_ARG_HINT_WD, false));
  199. args.Add(new NamedArgument(CS_ARG_NAME_INT, CS_ARG_DESC_INT, CS_ARG_HINT_INT, TypeValuesEnum.TimeSpan, TimeSpan.FromSeconds(30).ToString(), false));
  200. args.Add(new FlagArgument(CS_ARG_NAME_DELETE, CS_ARG_DESC_DELETE, CS_ARG_HINT_DELETE, false));
  201. args.Add(new FlagArgument(CS_ARG_NAME_INIT, CS_ARG_DESC_INIT, CS_ARG_HINT_INIT, false));
  202. return args;
  203. }
  204. #endregion
  205. }
  206. }