summaryrefslogtreecommitdiff
path: root/PublishMedia.cs
blob: 523b00f3fdf019ee4deb170d6f31de0dbc3dc18e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using HyperBooru.ApiClient;
using System.Management.Automation;

namespace HyperBooru.PowerShell;

[Alias("pbhbm")]
[Cmdlet(VerbsData.Publish, "HyperBooruMedia")]
public class PublishMediaCmdlet : PSCmdlet {
    [Parameter(Position = 0, Mandatory = true)]
    public HBSession Session { get; set; }

    [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true)]
    public string Path { get; set; }

    [Parameter(Position = 2)]
    public SwitchParameter Delete { get; set; }

    [Parameter(Position = 3)]
    public Guid[] TagId { get; set; } = Array.Empty<Guid>();

    protected override void ProcessRecord() {
        Path = System.IO.Path.GetFullPath(
            Path,
            SessionState.Path.CurrentLocation.Path);

        ApiModels.Media media;

        try {
            media = Session.Media.UploadAsync(Path, TagId, !TagId.Any())
                .GetAwaiter()
                .GetResult();
        } catch(Exception e) {
            ThrowTerminatingError(
                new ErrorRecord(
                    e,
                    "UploadFile",
                    ErrorCategory.WriteError,
                    Path));
            return;
        }

        WriteVerbose($"Uploaded file: {Path}");

        WriteObject(media);

        if(!Delete)
            return;

        try {
            File.Delete(Path);
            WriteVerbose($"Deleted file: {Path}");
        } catch(Exception e) {
            ThrowTerminatingError(
                new ErrorRecord(
                    e,
                    "DeleteFile",
                    ErrorCategory.InvalidResult,
                    Path));
        }
    }
}