Skip to content

Commit

Permalink
Added shared link commands, fixed UTF-8 issue with saving CSV reports…
Browse files Browse the repository at this point in the history
…, added autopaging for events and fixed faulty event get command. Added date options w for weeks and now. Bumped to v1.0.2
  • Loading branch information
amgrobelny-box committed Nov 1, 2017
1 parent 6294c83 commit 780e122
Show file tree
Hide file tree
Showing 17 changed files with 351 additions and 124 deletions.
2 changes: 1 addition & 1 deletion BoxCLI/BoxCLIInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ public class BoxCLIInfo
{
public const string ProductTitle = "Box CLI";

public const string Version = "1.0.1";
public const string Version = "1.0.2";
}
}
88 changes: 56 additions & 32 deletions BoxCLI/BoxPlatform/Utilities/BoxCollectionsIterators.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Box.V2;
using Box.V2.Models;
Expand All @@ -23,13 +24,13 @@ public class BoxCollectionsIterators : IBoxCollectionsIterators
Reporter.WriteInformation("Show next? Enter q to quit. ");
return System.Console.ReadLine().Trim().ToLower();
}
public string PageInConsole(Action<BoxEnterpriseEvent> print, BoxEventCollection<BoxEnterpriseEvent> collection)
{
print(collection.Entries[0]);
collection.Entries.RemoveAt(0);
Reporter.WriteInformation("Show next? Enter q to quit. ");
return System.Console.ReadLine().Trim().ToLower();
}
public string PageInConsole(Action<BoxEnterpriseEvent> print, BoxEventCollection<BoxEnterpriseEvent> collection)
{
print(collection.Entries[0]);
collection.Entries.RemoveAt(0);
Reporter.WriteInformation("Show next? Enter q to quit. ");
return System.Console.ReadLine().Trim().ToLower();
}

public async Task ListOffsetCollectionToConsole<T>(Func<uint, Task<BoxCollection<T>>> callBox, Action<T> print, int limit = -1) where T : BoxEntity, new()
{
Expand All @@ -42,7 +43,7 @@ public string PageInConsole(Action<BoxEnterpriseEvent> print, BoxEventCollection
{
if (collection.Entries.Count > 0)
{
if(limit == 0)
if (limit == 0)
{
break;
}
Expand Down Expand Up @@ -83,29 +84,52 @@ public string PageInConsole(Action<BoxEnterpriseEvent> print, BoxEventCollection
}
while (keepGoing && showNext != "q");
}
public async Task ListEventCollectionToConsole(Func<string, Task<BoxEventCollection<BoxEnterpriseEvent>>> callBox, Action<BoxEnterpriseEvent> print)
{
var keepGoing = false;
var showNext = "";
do
{
string streamPosition = "";
var collection = await callBox(streamPosition);
if (collection.Entries.Count > 0)
{
while (collection.Entries.Count > 0 && showNext != "q")
{
showNext = PageInConsole(print, collection);
}
}
else
{
streamPosition = collection.NextStreamPosition;
collection = await callBox(streamPosition);
}
keepGoing = !string.IsNullOrEmpty(collection.NextStreamPosition);
}
while (keepGoing && showNext != "q");
}
public async Task ListEventCollectionToConsole(Func<string, Task<BoxEventCollection<BoxEnterpriseEvent>>> callBox, Action<BoxEnterpriseEvent> print)
{
var keepGoing = false;
var showNext = "";
do
{
string streamPosition = "";
var collection = await callBox(streamPosition);
if (collection.Entries.Count > 0)
{
while (collection.Entries.Count > 0 && showNext != "q")
{
showNext = PageInConsole(print, collection);
}
}
else
{
streamPosition = collection.NextStreamPosition;
collection = await callBox(streamPosition);
}
keepGoing = !string.IsNullOrEmpty(collection.NextStreamPosition);
}
while (keepGoing && showNext != "q");
}

public async Task<BoxEventCollection<BoxEnterpriseEvent>> ReturnAllEvents(Func<string, Task<BoxEventCollection<BoxEnterpriseEvent>>> callBox)
{
var keepGoing = true;
var fullCollection = new BoxEventCollection<BoxEnterpriseEvent>();
fullCollection.Entries = new List<BoxEnterpriseEvent>();
string streamPosition = "";
do
{
var collection = await callBox(streamPosition);
if (collection.Entries.Count > 0)
{
fullCollection.Entries.AddRange(collection.Entries);
}
if (collection != null && !string.IsNullOrEmpty(collection.NextStreamPosition))
{
streamPosition = collection.NextStreamPosition;
}
keepGoing = collection.Entries.Count != 0;
}
while (keepGoing);
return fullCollection;
}
}
}
2 changes: 2 additions & 0 deletions BoxCLI/BoxPlatform/Utilities/IBoxCollectionsIterators.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Box.V2;
using Box.V2.Models;

namespace BoxCLI.BoxPlatform.Utilities
Expand All @@ -9,6 +10,7 @@ public interface IBoxCollectionsIterators
Task ListOffsetCollectionToConsole<T>(Func<uint, Task<BoxCollection<T>>> callBox, Action<T> print, int limit = -1) where T : BoxEntity, new();
Task ListMarkerCollectionToConsole<T>(Func<string, Task<BoxCollectionMarkerBased<T>>> callBox, Action<T> print) where T : BoxEntity, new();
Task ListEventCollectionToConsole(Func<string, Task<BoxEventCollection<BoxEnterpriseEvent>>> callBox, Action<BoxEnterpriseEvent> print);
Task<BoxEventCollection<BoxEnterpriseEvent>> ReturnAllEvents(Func<string, Task<BoxEventCollection<BoxEnterpriseEvent>>> callBox);
string PageInConsole<T>(Action<T> print, BoxCollection<T> collection) where T : class, new();
}
}
15 changes: 12 additions & 3 deletions BoxCLI/CommandUtilities/GeneralUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,22 @@ public static DateTime ResolveTimeUnit(double span, char unit)
return DateTime.Now.AddHours(span);
case 'd':
return DateTime.Now.AddDays(span);
case 'w':
return DateTime.Now.AddDays(span * 7);
case 'M':
return DateTime.Now.AddMonths(Convert.ToInt32(span));
case 'n':
return DateTime.Now;
default:
throw new Exception("Time format unrecognized.");
}
}
public static DateTime GetDateTimeFromString(string t, bool allowNegativeTime = false)
{
t = t.Trim();
var pattern = @"^[0-6][0-9]{1}[s,m,h,d,M]$";
var negativePattern = @"^-[0-6][0-9]{1}[s,m,h,d,M]$";
var now = "now";
var pattern = @"^[0-6][0-9]{1}[s,m,h,d,w,M]$";
var negativePattern = @"^-[0-6][0-9]{1}[s,m,h,d,w,M]$";
var regex = new Regex(pattern);
var negativeRegex = new Regex(negativePattern);
if (regex.Match(t).Success)
Expand All @@ -50,6 +55,10 @@ public static DateTime GetDateTimeFromString(string t, bool allowNegativeTime =
double.TryParse(t.Substring(0, 3), out span);
return ResolveTimeUnit(span, unit);
}
else if (now == t)
{
return ResolveTimeUnit(0, 'n');
}
else
{
throw new Exception("Time format unrecognized.");
Expand Down Expand Up @@ -86,7 +95,7 @@ private static string ResolveContainerPath(string containerPath)

public static string ResolveItemName(string path)
{
if(path.Last() == Path.DirectorySeparatorChar)
if (path.Last() == Path.DirectorySeparatorChar)
{
path = path.Substring(0, path.Length - 1);
}
Expand Down
18 changes: 9 additions & 9 deletions BoxCLI/Commands/BoxBaseCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ protected virtual void PrintCollaboration(BoxCollaboration c, bool json = false)
this.OutputJson(c);
return;
}
else
else
{
this.PrintCollaboration(c);
}
Expand Down Expand Up @@ -217,7 +217,7 @@ protected virtual bool WriteResultsToReport<T>(T entity, string fileName, string
{
try
{
using (StreamWriter fs = File.CreateText(filePath))
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
using (var csv = new CsvWriter(fs))
{
csv.WriteRecord(entity);
Expand Down Expand Up @@ -258,7 +258,7 @@ protected virtual bool WriteMetadataCollectionResultsToReport(List<BoxMetadataFo
{
try
{
using (StreamWriter fs = File.CreateText(filePath))
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
using (var csv = new CsvWriter(fs))
{
csv.Configuration.RegisterClassMap(typeof(BoxMetadataMap));
Expand Down Expand Up @@ -329,13 +329,13 @@ protected virtual bool WriteMetadataTemplateCollectionResultsToReport(List<BoxMe
}
}
}
using (StreamWriter fs = File.CreateText(filePathTemplate))
using (StreamWriter fs = new StreamWriter(File.Open(filePathTemplate, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
using (var csv = new CsvWriter(fs))
{
csv.Configuration.RegisterClassMap(typeof(BoxMetadataTemplateMap));
csv.WriteRecords(entity);
}
using (StreamWriter fs = File.CreateText(filePathFields))
using (StreamWriter fs = new StreamWriter(File.Open(filePathFields, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
using (var csv = new CsvWriter(fs))
{
csv.Configuration.RegisterClassMap(typeof(BoxMetadataTemplateFieldMap));
Expand Down Expand Up @@ -376,7 +376,7 @@ protected virtual bool WriteEventListResultsToReport(List<BoxEnterpriseEvent> en
{
try
{
using (StreamWriter fs = File.CreateText(filePath))
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
using (var csv = new CsvWriter(fs))
{
csv.Configuration.RegisterClassMap(typeof(BoxEventMap));
Expand Down Expand Up @@ -423,7 +423,7 @@ protected virtual bool WriteListResultsToReport<T, M>(List<T> entity, string fil
{
try
{
using (StreamWriter fs = File.CreateText(filePath))
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
using (var csv = new CsvWriter(fs))
{
csv.Configuration.RegisterClassMap(typeof(M));
Expand Down Expand Up @@ -465,7 +465,7 @@ protected virtual bool WriteOffsetCollectionResultsToReport<T, M>(BoxCollection<
{
try
{
using (StreamWriter fs = File.CreateText(filePath))
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
using (var csv = new CsvWriter(fs))
{
csv.Configuration.RegisterClassMap(typeof(M));
Expand Down Expand Up @@ -507,7 +507,7 @@ protected virtual bool WriteMarkerCollectionResultsToReport<T, M>(BoxCollectionM
{
try
{
using (StreamWriter fs = File.CreateText(filePath))
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
using (var csv = new CsvWriter(fs))
{
csv.Configuration.RegisterClassMap(typeof(M));
Expand Down
32 changes: 25 additions & 7 deletions BoxCLI/Commands/EventSubCommands/EventGetCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ public override void Configure(CommandLineApplication command)
_app = command;
command.Description = "Get events.";
_enterprise = command.Option("-e|--enterprise", "Get enterprise events", CommandOptionType.NoValue);
_createdBefore = command.Option("--created-before", "Return enterprise events that occured before a time. Use a timestamp or shorthand syntax 00t, like 05w for 5 weeks", CommandOptionType.SingleValue);
_createdAfter = command.Option("--created-after", "Return enterprise events that occured before a time. Use a timestamp or shorthand syntax 00t, like 05w for 5 weeks", CommandOptionType.SingleValue);
_createdBefore = command.Option("--created-before", "Return enterprise events that occured before a time. Use a timestamp or shorthand syntax 00t, like 05w for 5 weeks. If not used, defaults to now.", CommandOptionType.SingleValue);
_createdAfter = command.Option("--created-after", "Return enterprise events that occured before a time. Use a timestamp or shorthand syntax 00t, like 05w for 5 weeks. If not used, defaults to 5 days ago.", CommandOptionType.SingleValue);
_save = SaveOption.ConfigureOption(command);
_path = FilePathOption.ConfigureOption(command);
_fileFormat = FileFormatOption.ConfigureOption(command);
Expand Down Expand Up @@ -85,15 +85,21 @@ private async Task RunGet()
}
if (this._save.HasValue())
{
var fileName = $"{base._names.CommandNames.Events}-{base._names.SubCommandNames.Get}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}";
var fileName = $"{base._names.CommandNames.Events}-enterprise-{base._names.SubCommandNames.Get}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}";
Reporter.WriteInformation("Saving file...");
var events = await boxClient.EventsManager.EnterpriseEventsAsync(createdAfter: createdAfter, createdBefore: createdBefore);
var events = await BoxCollectionsIterators.ReturnAllEvents((position) =>
{
return boxClient.EventsManager.EnterpriseEventsAsync(limit: 1000, createdAfter: createdAfter, createdBefore: createdBefore, streamPosition: position);
});
base.WriteEventListResultsToReport(events.Entries, fileName, _path.Value(), _fileFormat.Value());
return;
}
if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting())
{
var events = await boxClient.EventsManager.EnterpriseEventsAsync(createdAfter: createdAfter, createdBefore: createdBefore);
var events = await BoxCollectionsIterators.ReturnAllEvents((position) =>
{
return boxClient.EventsManager.EnterpriseEventsAsync(limit: 1000, createdAfter: createdAfter, createdBefore: createdBefore, streamPosition: position);
});
base.OutputJson(events);
return;
}
Expand All @@ -106,12 +112,24 @@ await BoxCollectionsIterators.ListEventCollectionToConsole((position) =>
{
if (this._save.HasValue())
{
var fileName = $"{base._names.CommandNames.Events}-{base._names.SubCommandNames.Get}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}";
var fileName = $"{base._names.CommandNames.Events}-user-{base._names.SubCommandNames.Get}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}";
Reporter.WriteInformation("Saving file...");
var events = await boxClient.EventsManager.UserEventsAsync();
var events = await BoxCollectionsIterators.ReturnAllEvents((position) =>
{
return boxClient.EventsManager.UserEventsAsync(limit: 1000, streamPosition: position);
});
base.WriteEventListResultsToReport(events.Entries, fileName, _path.Value(), _fileFormat.Value());
return;
}
if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting())
{
var events = await BoxCollectionsIterators.ReturnAllEvents((position) =>
{
return boxClient.EventsManager.UserEventsAsync(limit: 1000, streamPosition: position);
});
base.OutputJson(events);
return;
}
await BoxCollectionsIterators.ListEventCollectionToConsole((position) =>
{
return boxClient.EventsManager.UserEventsAsync(streamPosition: position);
Expand Down
15 changes: 5 additions & 10 deletions BoxCLI/Commands/SharedLinkCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,10 @@ public override void Configure(CommandLineApplication command)
_app = command;
command.Description = "Manage your shared links.";
command.ExtendedHelpText = "You can use this command to create, update, delete, and get information about shared links in your Enterprise.";
if (this._t == BoxType.enterprise)
{
command.Command(base._names.SubCommandNames.Get, _subCommands.CreateSubCommand(_names.SubCommandNames.Get).Configure);
}
else
{
command.Command(base._names.SubCommandNames.Get, _subCommands.CreateSubCommand(_names.SubCommandNames.Get).Configure);
command.Command(base._names.SubCommandNames.Create, _subCommands.CreateSubCommand(_names.SubCommandNames.Create).Configure);
}
command.Command(base._names.SubCommandNames.Get, _subCommands.CreateSubCommand(_names.SubCommandNames.Get).Configure);
command.Command(base._names.SubCommandNames.Create, _subCommands.CreateSubCommand(_names.SubCommandNames.Create).Configure);
command.Command(base._names.SubCommandNames.Update, _subCommands.CreateSubCommand(_names.SubCommandNames.Update).Configure);
command.Command(base._names.SubCommandNames.Delete, _subCommands.CreateSubCommand(_names.SubCommandNames.Delete).Configure);

command.OnExecute(async () =>
{
Expand All @@ -40,7 +35,7 @@ protected async override Task<int> Execute()
private readonly ISubCommandFactory _subCommands;
private readonly BoxType _t;

public SharedLinkCommand(IBoxPlatformServiceBuilder boxPlatformBuilder, IBoxHome boxHome, SubCommandFactory factory,
public SharedLinkCommand(IBoxPlatformServiceBuilder boxPlatformBuilder, IBoxHome boxHome, SubCommandFactory factory,
LocalizedStringsResource names, BoxType t = BoxType.enterprise)
: base(boxPlatformBuilder, boxHome, names)
{
Expand Down
Loading

0 comments on commit 780e122

Please sign in to comment.