aboutsummaryrefslogtreecommitdiff
path: root/back-end/src/Endpoints/PostsEndpoint.cs
blob: 152b95a72d1be90edd23b9d342818f3bde4f0c83 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: CMNext
* Package: Content.Publishing.Blog.Admin
* File: PostsEndpoint.cs 
*
* CMNext is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* CMNext is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.Net;
using System.Threading.Tasks;
using Content.Publishing.Blog.Admin.Model;

using FluentValidation;

using VNLib.Plugins;
using VNLib.Plugins.Essentials;
using VNLib.Plugins.Essentials.Accounts;
using VNLib.Plugins.Essentials.Endpoints;
using VNLib.Plugins.Essentials.Extensions;
using VNLib.Plugins.Extensions.Loading;
using VNLib.Plugins.Extensions.Validation;

namespace Content.Publishing.Blog.Admin.Endpoints
{

    [ConfigurationName("post_endpoint")]
    internal sealed class PostsEndpoint : ProtectedWebEndpoint
    {
        private static readonly IValidator<BlogPost> PostValidator = BlogPost.GetValidator();

        private readonly IBlogPostManager PostManager;
        private readonly IChannelContextManager ContentManager;

        public PostsEndpoint(PluginBase plugin, IConfigScope config)
        {
            string? path = config["path"].GetString();

            InitPathAndLog(path, plugin.Log);

            //Get post manager and context manager
            PostManager = plugin.GetOrCreateSingleton<PostManager>();
            ContentManager = plugin.GetOrCreateSingleton<ChannelManager>();
        }

        protected override async ValueTask<VfReturnType> GetAsync(HttpEntity entity)
        {
            //Check for read permissions
            if (!entity.Session.CanRead())
            {
                WebMessage webm = new()
                {
                    Result = "You do not have permission to read content"
                };
                return VirtualClose(entity, webm, HttpStatusCode.Forbidden);
            }

            //Try to get the blog id from the query
            if (!entity.QueryArgs.TryGetNonEmptyValue("channel", out string? contextId))
            {
                return VfReturnType.BadRequest;
            }

            //Try to get the blog context from the id
            IChannelContext? context = await ContentManager.GetChannelAsync(contextId, entity.EventCancellation);
            if (context == null)
            {
                return VfReturnType.NotFound;
            }

            //Try to get the post id from the query
            if (entity.QueryArgs.TryGetNonEmptyValue("post", out string? postId))
            {
                //Try to get single post
                PostMeta? post = await PostManager.GetPostAsync(context, postId, entity.EventCancellation);

                return post != null ? VirtualOkJson(entity, post) : VfReturnType.NotFound;
            }

            //Get the post meta list
            PostMeta[] posts = await PostManager.GetPostsAsync(context, entity.EventCancellation);
            return VirtualOkJson(entity, posts);
        }

        protected override async ValueTask<VfReturnType> PostAsync(HttpEntity entity)
        {
            ValErrWebMessage webm = new();

            //Check for write permissions
            if (webm.Assert(entity.Session.CanWrite() == true, "You do not have permission to publish posts"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.Forbidden);
            }

            if (!entity.QueryArgs.TryGetNonEmptyValue("channel", out string? contextId))
            {
                webm.Result = "No blog channel was selected";
                return VirtualClose(entity, webm, HttpStatusCode.BadRequest);
            }

            //Try to get the blog context from the id
            IChannelContext? context = await ContentManager.GetChannelAsync(contextId, entity.EventCancellation);

            if (webm.Assert(context != null, "A blog with the given id does not exist"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.NotFound);
            }

            //Get the post from the request body
            BlogPost? post = await entity.GetJsonFromFileAsync<BlogPost>();

            if (webm.Assert(post != null, "Message body was empty"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.BadRequest);
            }

            //Validate post
            if (!PostValidator.Validate(post, webm))
            {
                return VirtualClose(entity, webm, HttpStatusCode.UnprocessableEntity);
            }

            //Publish post to the blog
            await PostManager.PublishPostAsync(context, post, entity.EventCancellation);

            //Success
            webm.Result = post;
            webm.Success = true;

            //Return updated post to client
            return VirtualOk(entity, webm);
        }

        protected override async ValueTask<VfReturnType> PatchAsync(HttpEntity entity)
        {
            ValErrWebMessage webm = new();

            //Check for write permissions
            if (webm.Assert(entity.Session.CanWrite() == true, "You do not have permissions to update posts"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.Forbidden);
            }

            //Try to get the blog id from the query
            if (!entity.QueryArgs.TryGetNonEmptyValue("channel", out string? contextId))
            {
                webm.Result = "You must select a blog channel to update posts";
                return VirtualClose(entity, webm, HttpStatusCode.BadRequest);
            }

            //Try to get the blog context from the id
            IChannelContext? channel = await ContentManager.GetChannelAsync(contextId, entity.EventCancellation);

            if (webm.Assert(channel != null, "The channel you selected does not exist"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.NotFound);
            }

            //Get the blog post object
            BlogPost? post = await entity.GetJsonFromFileAsync<BlogPost>();

            if (webm.Assert(post != null, "Message body was empty"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.BadRequest);
            }

            //Validate post
            if (!PostValidator.Validate(post, webm))
            {
                return VirtualClose(entity, webm, HttpStatusCode.UnprocessableEntity);
            }

            //Update post against manager
            bool result = await PostManager.UpdatePostAsync(channel, post, entity.EventCancellation);

            if (webm.Assert(result, "Failed to update post because it does not exist or the blog channel was not found"))
            {
                return VirtualOk(entity, webm);
            }

            //Success
            webm.Result = post;
            webm.Success = true;

            return VirtualOk(entity, webm);
        }

        protected override async ValueTask<VfReturnType> DeleteAsync(HttpEntity entity)
        {
            //Check for delete permissions
            if (!entity.Session.CanDelete())
            {
                WebMessage webm = new()
                {
                    Result = "You do not have permission to delete content"
                };
                return VirtualClose(entity, webm, HttpStatusCode.Forbidden);
            }

            //Try to get the blog id from the query
            if (!entity.QueryArgs.TryGetNonEmptyValue("channel", out string? contextId))
            {
                return VfReturnType.BadRequest;
            }

            //Try to get the blog context from the id
            IChannelContext? context = await ContentManager.GetChannelAsync(contextId, entity.EventCancellation);
            if (context == null)
            {
                return VfReturnType.NotFound;
            }

            //Try to get the post id from the query
            if (!entity.QueryArgs.TryGetNonEmptyValue("post", out string? postId))
            {
                return VfReturnType.NotFound;
            }

            //Delete post
            await PostManager.DeletePostAsync(context, postId, entity.EventCancellation);

            //Success
            return VirtualOk(entity);
        }

    }
}