Skip to content

Commit 780e122

Browse files
author
amgrobelny-box
committed
Added shared link commands, fixed UTF-8 issue with saving CSV reports, added autopaging for events and fixed faulty event get command. Added date options w for weeks and now. Bumped to v1.0.2
1 parent 6294c83 commit 780e122

17 files changed

+351
-124
lines changed

BoxCLI/BoxCLIInfo.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,6 @@ public class BoxCLIInfo
44
{
55
public const string ProductTitle = "Box CLI";
66

7-
public const string Version = "1.0.1";
7+
public const string Version = "1.0.2";
88
}
99
}

BoxCLI/BoxPlatform/Utilities/BoxCollectionsIterators.cs

Lines changed: 56 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.Threading.Tasks;
34
using Box.V2;
45
using Box.V2.Models;
@@ -23,13 +24,13 @@ public class BoxCollectionsIterators : IBoxCollectionsIterators
2324
Reporter.WriteInformation("Show next? Enter q to quit. ");
2425
return System.Console.ReadLine().Trim().ToLower();
2526
}
26-
public string PageInConsole(Action<BoxEnterpriseEvent> print, BoxEventCollection<BoxEnterpriseEvent> collection)
27-
{
28-
print(collection.Entries[0]);
29-
collection.Entries.RemoveAt(0);
30-
Reporter.WriteInformation("Show next? Enter q to quit. ");
31-
return System.Console.ReadLine().Trim().ToLower();
32-
}
27+
public string PageInConsole(Action<BoxEnterpriseEvent> print, BoxEventCollection<BoxEnterpriseEvent> collection)
28+
{
29+
print(collection.Entries[0]);
30+
collection.Entries.RemoveAt(0);
31+
Reporter.WriteInformation("Show next? Enter q to quit. ");
32+
return System.Console.ReadLine().Trim().ToLower();
33+
}
3334

3435
public async Task ListOffsetCollectionToConsole<T>(Func<uint, Task<BoxCollection<T>>> callBox, Action<T> print, int limit = -1) where T : BoxEntity, new()
3536
{
@@ -42,7 +43,7 @@ public string PageInConsole(Action<BoxEnterpriseEvent> print, BoxEventCollection
4243
{
4344
if (collection.Entries.Count > 0)
4445
{
45-
if(limit == 0)
46+
if (limit == 0)
4647
{
4748
break;
4849
}
@@ -83,29 +84,52 @@ public string PageInConsole(Action<BoxEnterpriseEvent> print, BoxEventCollection
8384
}
8485
while (keepGoing && showNext != "q");
8586
}
86-
public async Task ListEventCollectionToConsole(Func<string, Task<BoxEventCollection<BoxEnterpriseEvent>>> callBox, Action<BoxEnterpriseEvent> print)
87-
{
88-
var keepGoing = false;
89-
var showNext = "";
90-
do
91-
{
92-
string streamPosition = "";
93-
var collection = await callBox(streamPosition);
94-
if (collection.Entries.Count > 0)
95-
{
96-
while (collection.Entries.Count > 0 && showNext != "q")
97-
{
98-
showNext = PageInConsole(print, collection);
99-
}
100-
}
101-
else
102-
{
103-
streamPosition = collection.NextStreamPosition;
104-
collection = await callBox(streamPosition);
105-
}
106-
keepGoing = !string.IsNullOrEmpty(collection.NextStreamPosition);
107-
}
108-
while (keepGoing && showNext != "q");
109-
}
87+
public async Task ListEventCollectionToConsole(Func<string, Task<BoxEventCollection<BoxEnterpriseEvent>>> callBox, Action<BoxEnterpriseEvent> print)
88+
{
89+
var keepGoing = false;
90+
var showNext = "";
91+
do
92+
{
93+
string streamPosition = "";
94+
var collection = await callBox(streamPosition);
95+
if (collection.Entries.Count > 0)
96+
{
97+
while (collection.Entries.Count > 0 && showNext != "q")
98+
{
99+
showNext = PageInConsole(print, collection);
100+
}
101+
}
102+
else
103+
{
104+
streamPosition = collection.NextStreamPosition;
105+
collection = await callBox(streamPosition);
106+
}
107+
keepGoing = !string.IsNullOrEmpty(collection.NextStreamPosition);
108+
}
109+
while (keepGoing && showNext != "q");
110+
}
111+
112+
public async Task<BoxEventCollection<BoxEnterpriseEvent>> ReturnAllEvents(Func<string, Task<BoxEventCollection<BoxEnterpriseEvent>>> callBox)
113+
{
114+
var keepGoing = true;
115+
var fullCollection = new BoxEventCollection<BoxEnterpriseEvent>();
116+
fullCollection.Entries = new List<BoxEnterpriseEvent>();
117+
string streamPosition = "";
118+
do
119+
{
120+
var collection = await callBox(streamPosition);
121+
if (collection.Entries.Count > 0)
122+
{
123+
fullCollection.Entries.AddRange(collection.Entries);
124+
}
125+
if (collection != null && !string.IsNullOrEmpty(collection.NextStreamPosition))
126+
{
127+
streamPosition = collection.NextStreamPosition;
128+
}
129+
keepGoing = collection.Entries.Count != 0;
130+
}
131+
while (keepGoing);
132+
return fullCollection;
133+
}
110134
}
111135
}

BoxCLI/BoxPlatform/Utilities/IBoxCollectionsIterators.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Threading.Tasks;
3+
using Box.V2;
34
using Box.V2.Models;
45

56
namespace BoxCLI.BoxPlatform.Utilities
@@ -9,6 +10,7 @@ public interface IBoxCollectionsIterators
910
Task ListOffsetCollectionToConsole<T>(Func<uint, Task<BoxCollection<T>>> callBox, Action<T> print, int limit = -1) where T : BoxEntity, new();
1011
Task ListMarkerCollectionToConsole<T>(Func<string, Task<BoxCollectionMarkerBased<T>>> callBox, Action<T> print) where T : BoxEntity, new();
1112
Task ListEventCollectionToConsole(Func<string, Task<BoxEventCollection<BoxEnterpriseEvent>>> callBox, Action<BoxEnterpriseEvent> print);
13+
Task<BoxEventCollection<BoxEnterpriseEvent>> ReturnAllEvents(Func<string, Task<BoxEventCollection<BoxEnterpriseEvent>>> callBox);
1214
string PageInConsole<T>(Action<T> print, BoxCollection<T> collection) where T : class, new();
1315
}
1416
}

BoxCLI/CommandUtilities/GeneralUtilities.cs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,22 @@ public static DateTime ResolveTimeUnit(double span, char unit)
2323
return DateTime.Now.AddHours(span);
2424
case 'd':
2525
return DateTime.Now.AddDays(span);
26+
case 'w':
27+
return DateTime.Now.AddDays(span * 7);
2628
case 'M':
2729
return DateTime.Now.AddMonths(Convert.ToInt32(span));
30+
case 'n':
31+
return DateTime.Now;
2832
default:
2933
throw new Exception("Time format unrecognized.");
3034
}
3135
}
3236
public static DateTime GetDateTimeFromString(string t, bool allowNegativeTime = false)
3337
{
3438
t = t.Trim();
35-
var pattern = @"^[0-6][0-9]{1}[s,m,h,d,M]$";
36-
var negativePattern = @"^-[0-6][0-9]{1}[s,m,h,d,M]$";
39+
var now = "now";
40+
var pattern = @"^[0-6][0-9]{1}[s,m,h,d,w,M]$";
41+
var negativePattern = @"^-[0-6][0-9]{1}[s,m,h,d,w,M]$";
3742
var regex = new Regex(pattern);
3843
var negativeRegex = new Regex(negativePattern);
3944
if (regex.Match(t).Success)
@@ -50,6 +55,10 @@ public static DateTime GetDateTimeFromString(string t, bool allowNegativeTime =
5055
double.TryParse(t.Substring(0, 3), out span);
5156
return ResolveTimeUnit(span, unit);
5257
}
58+
else if (now == t)
59+
{
60+
return ResolveTimeUnit(0, 'n');
61+
}
5362
else
5463
{
5564
throw new Exception("Time format unrecognized.");
@@ -86,7 +95,7 @@ private static string ResolveContainerPath(string containerPath)
8695

8796
public static string ResolveItemName(string path)
8897
{
89-
if(path.Last() == Path.DirectorySeparatorChar)
98+
if (path.Last() == Path.DirectorySeparatorChar)
9099
{
91100
path = path.Substring(0, path.Length - 1);
92101
}

BoxCLI/Commands/BoxBaseCommand.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ protected virtual void PrintCollaboration(BoxCollaboration c, bool json = false)
6767
this.OutputJson(c);
6868
return;
6969
}
70-
else
70+
else
7171
{
7272
this.PrintCollaboration(c);
7373
}
@@ -217,7 +217,7 @@ protected virtual bool WriteResultsToReport<T>(T entity, string fileName, string
217217
{
218218
try
219219
{
220-
using (StreamWriter fs = File.CreateText(filePath))
220+
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
221221
using (var csv = new CsvWriter(fs))
222222
{
223223
csv.WriteRecord(entity);
@@ -258,7 +258,7 @@ protected virtual bool WriteMetadataCollectionResultsToReport(List<BoxMetadataFo
258258
{
259259
try
260260
{
261-
using (StreamWriter fs = File.CreateText(filePath))
261+
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
262262
using (var csv = new CsvWriter(fs))
263263
{
264264
csv.Configuration.RegisterClassMap(typeof(BoxMetadataMap));
@@ -329,13 +329,13 @@ protected virtual bool WriteMetadataTemplateCollectionResultsToReport(List<BoxMe
329329
}
330330
}
331331
}
332-
using (StreamWriter fs = File.CreateText(filePathTemplate))
332+
using (StreamWriter fs = new StreamWriter(File.Open(filePathTemplate, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
333333
using (var csv = new CsvWriter(fs))
334334
{
335335
csv.Configuration.RegisterClassMap(typeof(BoxMetadataTemplateMap));
336336
csv.WriteRecords(entity);
337337
}
338-
using (StreamWriter fs = File.CreateText(filePathFields))
338+
using (StreamWriter fs = new StreamWriter(File.Open(filePathFields, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
339339
using (var csv = new CsvWriter(fs))
340340
{
341341
csv.Configuration.RegisterClassMap(typeof(BoxMetadataTemplateFieldMap));
@@ -376,7 +376,7 @@ protected virtual bool WriteEventListResultsToReport(List<BoxEnterpriseEvent> en
376376
{
377377
try
378378
{
379-
using (StreamWriter fs = File.CreateText(filePath))
379+
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
380380
using (var csv = new CsvWriter(fs))
381381
{
382382
csv.Configuration.RegisterClassMap(typeof(BoxEventMap));
@@ -423,7 +423,7 @@ protected virtual bool WriteListResultsToReport<T, M>(List<T> entity, string fil
423423
{
424424
try
425425
{
426-
using (StreamWriter fs = File.CreateText(filePath))
426+
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
427427
using (var csv = new CsvWriter(fs))
428428
{
429429
csv.Configuration.RegisterClassMap(typeof(M));
@@ -465,7 +465,7 @@ protected virtual bool WriteOffsetCollectionResultsToReport<T, M>(BoxCollection<
465465
{
466466
try
467467
{
468-
using (StreamWriter fs = File.CreateText(filePath))
468+
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
469469
using (var csv = new CsvWriter(fs))
470470
{
471471
csv.Configuration.RegisterClassMap(typeof(M));
@@ -507,7 +507,7 @@ protected virtual bool WriteMarkerCollectionResultsToReport<T, M>(BoxCollectionM
507507
{
508508
try
509509
{
510-
using (StreamWriter fs = File.CreateText(filePath))
510+
using (StreamWriter fs = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), System.Text.Encoding.UTF8))
511511
using (var csv = new CsvWriter(fs))
512512
{
513513
csv.Configuration.RegisterClassMap(typeof(M));

BoxCLI/Commands/EventSubCommands/EventGetCommand.cs

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ public override void Configure(CommandLineApplication command)
3333
_app = command;
3434
command.Description = "Get events.";
3535
_enterprise = command.Option("-e|--enterprise", "Get enterprise events", CommandOptionType.NoValue);
36-
_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);
37-
_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);
36+
_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);
37+
_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);
3838
_save = SaveOption.ConfigureOption(command);
3939
_path = FilePathOption.ConfigureOption(command);
4040
_fileFormat = FileFormatOption.ConfigureOption(command);
@@ -85,15 +85,21 @@ private async Task RunGet()
8585
}
8686
if (this._save.HasValue())
8787
{
88-
var fileName = $"{base._names.CommandNames.Events}-{base._names.SubCommandNames.Get}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}";
88+
var fileName = $"{base._names.CommandNames.Events}-enterprise-{base._names.SubCommandNames.Get}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}";
8989
Reporter.WriteInformation("Saving file...");
90-
var events = await boxClient.EventsManager.EnterpriseEventsAsync(createdAfter: createdAfter, createdBefore: createdBefore);
90+
var events = await BoxCollectionsIterators.ReturnAllEvents((position) =>
91+
{
92+
return boxClient.EventsManager.EnterpriseEventsAsync(limit: 1000, createdAfter: createdAfter, createdBefore: createdBefore, streamPosition: position);
93+
});
9194
base.WriteEventListResultsToReport(events.Entries, fileName, _path.Value(), _fileFormat.Value());
9295
return;
9396
}
9497
if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting())
9598
{
96-
var events = await boxClient.EventsManager.EnterpriseEventsAsync(createdAfter: createdAfter, createdBefore: createdBefore);
99+
var events = await BoxCollectionsIterators.ReturnAllEvents((position) =>
100+
{
101+
return boxClient.EventsManager.EnterpriseEventsAsync(limit: 1000, createdAfter: createdAfter, createdBefore: createdBefore, streamPosition: position);
102+
});
97103
base.OutputJson(events);
98104
return;
99105
}
@@ -106,12 +112,24 @@ await BoxCollectionsIterators.ListEventCollectionToConsole((position) =>
106112
{
107113
if (this._save.HasValue())
108114
{
109-
var fileName = $"{base._names.CommandNames.Events}-{base._names.SubCommandNames.Get}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}";
115+
var fileName = $"{base._names.CommandNames.Events}-user-{base._names.SubCommandNames.Get}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}";
110116
Reporter.WriteInformation("Saving file...");
111-
var events = await boxClient.EventsManager.UserEventsAsync();
117+
var events = await BoxCollectionsIterators.ReturnAllEvents((position) =>
118+
{
119+
return boxClient.EventsManager.UserEventsAsync(limit: 1000, streamPosition: position);
120+
});
112121
base.WriteEventListResultsToReport(events.Entries, fileName, _path.Value(), _fileFormat.Value());
113122
return;
114123
}
124+
if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting())
125+
{
126+
var events = await BoxCollectionsIterators.ReturnAllEvents((position) =>
127+
{
128+
return boxClient.EventsManager.UserEventsAsync(limit: 1000, streamPosition: position);
129+
});
130+
base.OutputJson(events);
131+
return;
132+
}
115133
await BoxCollectionsIterators.ListEventCollectionToConsole((position) =>
116134
{
117135
return boxClient.EventsManager.UserEventsAsync(streamPosition: position);

BoxCLI/Commands/SharedLinkCommand.cs

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,10 @@ public override void Configure(CommandLineApplication command)
1515
_app = command;
1616
command.Description = "Manage your shared links.";
1717
command.ExtendedHelpText = "You can use this command to create, update, delete, and get information about shared links in your Enterprise.";
18-
if (this._t == BoxType.enterprise)
19-
{
20-
command.Command(base._names.SubCommandNames.Get, _subCommands.CreateSubCommand(_names.SubCommandNames.Get).Configure);
21-
}
22-
else
23-
{
24-
command.Command(base._names.SubCommandNames.Get, _subCommands.CreateSubCommand(_names.SubCommandNames.Get).Configure);
25-
command.Command(base._names.SubCommandNames.Create, _subCommands.CreateSubCommand(_names.SubCommandNames.Create).Configure);
26-
}
18+
command.Command(base._names.SubCommandNames.Get, _subCommands.CreateSubCommand(_names.SubCommandNames.Get).Configure);
19+
command.Command(base._names.SubCommandNames.Create, _subCommands.CreateSubCommand(_names.SubCommandNames.Create).Configure);
20+
command.Command(base._names.SubCommandNames.Update, _subCommands.CreateSubCommand(_names.SubCommandNames.Update).Configure);
21+
command.Command(base._names.SubCommandNames.Delete, _subCommands.CreateSubCommand(_names.SubCommandNames.Delete).Configure);
2722

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

43-
public SharedLinkCommand(IBoxPlatformServiceBuilder boxPlatformBuilder, IBoxHome boxHome, SubCommandFactory factory,
38+
public SharedLinkCommand(IBoxPlatformServiceBuilder boxPlatformBuilder, IBoxHome boxHome, SubCommandFactory factory,
4439
LocalizedStringsResource names, BoxType t = BoxType.enterprise)
4540
: base(boxPlatformBuilder, boxHome, names)
4641
{

0 commit comments

Comments
 (0)