Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate from System.CommandLine to Spectre.Console. #189

Merged
merged 9 commits into from
Oct 30, 2023
Merged
46 changes: 24 additions & 22 deletions Solutions/Stacker.Cli/BufferClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

using Newtonsoft.Json;
using Spectre.Console;

using Stacker.Cli.Configuration;
using Stacker.Cli.Contracts.Buffer;
Expand Down Expand Up @@ -44,35 +45,36 @@ public IEnumerable<KeyValuePair<string, string>> ConvertToPayload(string content
return postData;
}

public async Task UploadAsync(IEnumerable<string> content, string profileId)
public async Task UploadAsync(IEnumerable<string> content, string profileId, bool whatIf)
{
using (HttpClient client = this.httpClientFactory.CreateClient())
{
client.BaseAddress = new(BaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new("application/x-www-form-urlencoded"));
using HttpClient client = this.httpClientFactory.CreateClient();
client.BaseAddress = new Uri(BaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

StackerSettings settings = this.settingsManager.LoadSettings(nameof(StackerSettings));
string updateOperationUrl = $"{UpdateOperation}?access_token={settings.BufferAccessToken}";

StackerSettings settings = this.settingsManager.LoadSettings(nameof(StackerSettings));
string updateOperationUrl = $"{UpdateOperation}?access_token={settings.BufferAccessToken}";
foreach (string item in content)
{
AnsiConsole.MarkupLineInterpolated($"[chartreuse3_1]Buffering:[/] {item}");

foreach (string item in content)
if (whatIf)
{
HttpContent payload = new FormUrlEncodedContent(this.ConvertToPayload(item, new string[] { profileId }));
continue;
}

Console.WriteLine($"Buffering: {item}");
HttpContent payload = new FormUrlEncodedContent(this.ConvertToPayload(item, new string[] { profileId }));

HttpResponseMessage response = await client.PostAsync(updateOperationUrl, payload).ConfigureAwait(false);
HttpResponseMessage response = await client.PostAsync(updateOperationUrl, payload).ConfigureAwait(false);

if (!response.IsSuccessStatusCode)
{
string errorContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
BufferError error = JsonConvert.DeserializeObject<BufferError>(errorContent);
if (!response.IsSuccessStatusCode)
{
string errorContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
BufferError error = JsonSerializer.Deserialize<BufferError>(errorContent);

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Buffering Failed: {error.Message}");
Console.WriteLine();
Console.ResetColor();
}
AnsiConsole.MarkupLineInterpolated($"[red]Buffering Failed:[/] {error.Message}");
AnsiConsole.WriteLine();
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions Solutions/Stacker.Cli/BufferError.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,21 @@
// </copyright>

using System.Collections.Generic;
using Newtonsoft.Json;
using System.Text.Json.Serialization;

namespace Stacker.Cli;

public class BufferError
{
[JsonProperty("success")]
[JsonPropertyName("success")]
public bool Success { get; set; }

[JsonProperty("message")]
[JsonPropertyName("message")]
public string Message { get; set; }

[JsonProperty("code")]
[JsonPropertyName("code")]
public int Code { get; set; }

[JsonProperty("errored_profiles")]
[JsonPropertyName("errored_profiles")]
public IEnumerable<Profiles> ErroredProfiles { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

using System;
using System.Text.RegularExpressions;

using Flurl;

using Stacker.Cli.Domain.Universal;

namespace Stacker.Cli.Cleaners;
Expand Down
2 changes: 2 additions & 0 deletions Solutions/Stacker.Cli/Cleaners/ContentItemCleaner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.Extensions.DependencyInjection;

using Stacker.Cli.Domain.Universal;

namespace Stacker.Cli.Cleaners;
Expand Down
1 change: 1 addition & 0 deletions Solutions/Stacker.Cli/Cleaners/EnsureEndjinHttpsInBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System;
using System.Text.RegularExpressions;

using Stacker.Cli.Domain.Universal;

namespace Stacker.Cli.Cleaners;
Expand Down
1 change: 1 addition & 0 deletions Solutions/Stacker.Cli/Cleaners/RemoveHostNamesFromBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System;
using System.Text.RegularExpressions;

using Stacker.Cli.Domain.Universal;

namespace Stacker.Cli.Cleaners;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// </copyright>

using System.Text.RegularExpressions;

using Stacker.Cli.Domain.Universal;

namespace Stacker.Cli.Cleaners;
Expand Down
27 changes: 0 additions & 27 deletions Solutions/Stacker.Cli/Commands/EnvironmentCommandFactory.cs

This file was deleted.

56 changes: 56 additions & 0 deletions Solutions/Stacker.Cli/Commands/EnvironmentInitCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// <copyright file="EnvironmentInitCommand.cs" company="Endjin Limited">
// Copyright (c) Endjin Limited. All rights reserved.
// </copyright>

#nullable enable annotations

using System.Collections.Generic;

using Spectre.Console;
using Spectre.Console.Cli;

using Stacker.Cli.Configuration;
using Stacker.Cli.Contracts.Configuration;

namespace Stacker.Cli.Commands;

public class EnvironmentInitCommand : Command
{
private readonly IAppEnvironment appEnvironment;
private readonly IStackerSettingsManager settingsManager;

public EnvironmentInitCommand(IAppEnvironment appEnvironment, IStackerSettingsManager settingsManager)
{
this.appEnvironment = appEnvironment;
this.settingsManager = settingsManager;
}

public override int Execute(CommandContext context)
{
this.appEnvironment.Initialize();
this.settingsManager.SaveSettings(
new StackerSettings
{
BufferAccessToken = "<ADD YOUR ACCESS TOKEN>",
BufferProfiles = new Dictionary<string, string>
{
{ "facebook|<ACCOUNT NAME>", "<BUFFER CHANNEL ID>" },
{ "linkedin|<ACCOUNT NAME>", "<BUFFER CHANNEL ID>" },
{ "twitter|<ACCOUNT NAME>", "<BUFFER CHANNEL ID>" },
},
Users = new List<User>
{
new()
{
Email = string.Empty,
IsActive = true,
},
},
},
nameof(StackerSettings));

AnsiConsole.WriteLine($"Environment Initialized {this.appEnvironment.AppPath}");

return 0;
}
}
58 changes: 0 additions & 58 deletions Solutions/Stacker.Cli/Commands/EnvironmentInitCommandFactory.cs

This file was deleted.

87 changes: 87 additions & 0 deletions Solutions/Stacker.Cli/Commands/FacebookBufferCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// <copyright file="FacebookBufferCommand.cs" company="Endjin Limited">
// Copyright (c) Endjin Limited. All rights reserved.
// </copyright>

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;

using Spectre.Console.Cli;
using Spectre.IO;

using Stacker.Cli.Contracts.Tasks;
using Stacker.Cli.Domain.Publication;
using Stacker.Cli.Formatters;

namespace Stacker.Cli.Commands;

public class FacebookBufferCommand : AsyncCommand<FacebookBufferCommand.Settings>
{
private readonly IContentTasks contentTasks;
private readonly string profilePrefix = "facebook|";

public FacebookBufferCommand(IContentTasks contentTasks)
{
this.contentTasks = contentTasks;
}

/// <inheritdoc/>
public override async Task<int> ExecuteAsync([NotNull] CommandContext context, [NotNull] Settings settings)
{
await this.contentTasks.BufferContentItemsAsync<FacebookFormatter>(
settings.ContentFilePath,
this.profilePrefix,
settings.ProfileName,
settings.PublicationPeriod,
settings.FromDate,
settings.ToDate,
settings.ItemCount,
settings.FilterByTag,
settings.WhatIf).ConfigureAwait(false);

return 0;
}

/// <summary>
/// The settings for the command.
/// </summary>
public class Settings : CommandSettings
{
#nullable disable annotations

[CommandOption("-c|--content-file-path <ContentFilePath>")]
[Description("Content file path.")]
public FilePath ContentFilePath { get; init; }

[CommandOption("-n|--profile-name <ProfileName>")]
[Description("Facebook profile to Buffer.")]
public string ProfileName { get; init; }

[CommandOption("-g|--filter-by-tag <FilterByTag>")]
[Description("Tag to filter the content items by.")]
public string FilterByTag { get; init; }

[CommandOption("-i|--item-count <ItemCount>")]
[Description("Number of content items to buffer. If omitted all content is buffered.")]
public int ItemCount { get; init; }

[CommandOption("-p|--publication-period <PublicationPeriod>")]
[Description("Publication period to filter content items by. <LastMonth|LastWeek|LastYear|None|ThisMonth|ThisWeek|ThisYear> If specified --from-date and --to-date are ignored.")]
public PublicationPeriod PublicationPeriod { get; init; }

[CommandOption("-f|--from-date <FromDate>")]
[Description("Include content items published on, or after this date. Use YYYY/MM/DD Format. If omitted DateTime.MinValue is used.")]
public DateTime FromDate { get; init; }

[CommandOption("-t|--to-date <ToDate>")]
[Description("Include content items published on, or before this date. Use YYYY/MM/DD Format. If omitted DateTime.MaxValue is used.")]
public DateTime ToDate { get; init; }

[CommandOption("-w|--what-if <WhatIf>")]
[Description("See what the command would do without submitting the content to Buffer.")]
public bool WhatIf { get; set; }

#nullable enable annotations
}
}
Loading
Loading