aboutsummaryrefslogtreecommitdiff
path: root/back-end/src/Endpoints/ContentEndpoint.cs
blob: 2427cf0797cd875b2916b38347958032bdaaed18 (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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: CMNext
* Package: Content.Publishing.Blog.Admin
* File: ContentEndpoint.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.IO;
using System.Net;
using System.Threading.Tasks;

using FluentValidation;

using VNLib.Utils.IO;
using VNLib.Net.Http;
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;

using Content.Publishing.Blog.Admin.Model;

namespace Content.Publishing.Blog.Admin.Endpoints
{

    [ConfigurationName("content_endpoint")]
    internal sealed class ContentEndpoint : ProtectedWebEndpoint
    {
        private static readonly IValidator<ContentMeta> MetaValidator = ContentMeta.GetValidator();

        private readonly ContentManager _content;
        private readonly IChannelContextManager _blogContextManager;

        private readonly int MaxContentLength;

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

            InitPathAndLog(path, plugin.Log);

            //Get the max content length
            MaxContentLength = (int)config["max_content_length"].GetUInt32();

            _content = plugin.GetOrCreateSingleton<ContentManager>();
            _blogContextManager = plugin.GetOrCreateSingleton<ChannelManager>();
        }


        protected override async ValueTask<VfReturnType> GetAsync(HttpEntity entity)
        {
            if (!entity.Session.CanRead())
            {
                return VfReturnType.Forbidden;
            }

            //Get the channel id 
            if (!entity.QueryArgs.TryGetNonEmptyValue("channel", out string? channelId))
            {
                return VirtualClose(entity, HttpStatusCode.BadRequest);
            }

            //Get the channel
            IChannelContext? channel = await _blogContextManager.GetChannelAsync(channelId, entity.EventCancellation);

            if (channel == null)
            {
                return VfReturnType.NotFound;
            }

            //Get the content id, if not set get all content meta items
            if (!entity.QueryArgs.TryGetNonEmptyValue("id", out string? contentId))
            {
                //Get all content items
                ContentMeta[] items = await _content.GetAllContentItemsAsync(channel, entity.EventCancellation);

                //Return the items
                return VirtualCloseJson(entity, items, HttpStatusCode.OK);
            }

            //See if the user wants to get a link to the content
            if (entity.QueryArgs.IsArgumentSet("getlink", "true"))
            {
                WebMessage webm = new()
                {
                    //Get the content link
                    Result = await _content.GetExternalPathForItemAsync(channel, contentId, entity.EventCancellation)
                };

                //Set success if the link exists
                webm.Success = webm.Result != null;
                webm.Result ??= "The requested content item was not found in the database";

                //Return the link in webmessage result
                return VirtualOk(entity, webm);
            }
            else
            {
                //Get content for single item
                VnMemoryStream vms = new();
                try
                {
                    //Get the content from the store
                    ContentMeta? meta = await _content.GetContentAsync(channel, contentId, vms, entity.EventCancellation);

                    //it may not exist, cleanuup
                    if (meta?.ContentType == null)
                    {
                        vms.Dispose();
                        return VfReturnType.NotFound;
                    }
                    else
                    {
                        //rewind the stream
                        vms.Seek(0, SeekOrigin.Begin);

                        //Return the content stream
                        return VirtualClose(entity, HttpStatusCode.OK, HttpHelpers.GetContentType(meta.ContentType), vms);
                    }
                }
                catch
                {
                    vms.Dispose();
                    throw;
                }
            }
        }

        /*
         * Patch allows updating content meta data without having to upload the content again
         */
        protected override async ValueTask<VfReturnType> PatchAsync(HttpEntity entity)
        {

            //Get channel id
            if (!entity.QueryArgs.TryGetNonEmptyValue("channel", out string? channelId))
            {
                return VfReturnType.NotFound;
            }

            ValErrWebMessage webm = new();

            if (webm.Assert(entity.Session.CanWrite(), "You do not have permissions to update content"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.Forbidden);
            }

            //Make sure there is content attached
            if (webm.Assert(entity.Files.Count > 0, "No content was attached to the entity body"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.BadRequest);
            }

            //Get the channel
            IChannelContext? channel = await _blogContextManager.GetChannelAsync(channelId, entity.EventCancellation);

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

            //Read meta from request
            ContentMeta? requestedMeta = await entity.GetJsonFromFileAsync<ContentMeta>();

            if (webm.Assert(requestedMeta?.Id != null, "You must supply a content id"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.BadRequest);
            }

            //Validate the meta
            if (!MetaValidator.Validate(requestedMeta, webm))
            {
                return VirtualClose(entity, webm, HttpStatusCode.UnprocessableEntity);
            }

            //Get the original content meta
            ContentMeta? meta = await _content.GetMetaAsync(channel, requestedMeta.Id, entity.EventCancellation);
            if (webm.Assert(meta != null, "The requested content item does not exist"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.NotFound);
            }

            //Currently only allow chaning the file name
            meta.FileName = requestedMeta.FileName;

            //Set the meta item
            await _content.SetMetaAsync(channel, meta, entity.EventCancellation);

            //Return the updated meta
            webm.Result = meta;
            webm.Success = true;

            return VirtualOk(entity, webm);
        }

        /*
         * Put adds or updates content
         */
        protected override async ValueTask<VfReturnType> PutAsync(HttpEntity entity)
        {
            //Get channel id
            if (!entity.QueryArgs.TryGetNonEmptyValue("channel", out string? channelId))
            {
                return VfReturnType.NotFound;
            }

            ValErrWebMessage webm = new();

            if (webm.Assert(entity.Session.CanWrite(), "You do not have permissions to update content"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.Forbidden);
            }

            //Make sure there is content attached
            if (webm.Assert(entity.Files.Count > 0, "No content was attached to the entity body"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.BadRequest);
            }

            //Get the first file
            FileUpload file = entity.Files[0];

            //Check content length
            if (webm.Assert(file.FileData.Length <= MaxContentLength, $"The content length is too long, max length is {MaxContentLength} bytes"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.BadRequest);
            }

            //the http layer should protect from this but just in case
            if(webm.Assert(file.ContentType != ContentType.NonSupported, "The uploaded file is not a supported system content type"))
            {
                return VirtualClose(entity, webm, HttpStatusCode.BadRequest);
            }

            //Get the channel
            IChannelContext? channel = await _blogContextManager.GetChannelAsync(channelId, entity.EventCancellation);

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

            ContentMeta? meta;

            //Get the content id if its an update
            if (entity.QueryArgs.TryGetNonEmptyValue("id", out string? contentId))
            {
                //Get the original content meta
                meta = await _content.GetMetaAsync(channel, contentId, entity.EventCancellation);

                if (webm.Assert(meta != null, "The request item does not exist"))
                {
                    return VirtualClose(entity, webm, HttpStatusCode.NotFound);
                }

                //May want to change the content name
                meta.FileName = entity.Server.Headers["X-Content-Name"];
            }
            else
            {
                //Get the content name, may be null
                string? cName = entity.Server.Headers["X-Content-Name"];

                //New item
                meta = _content.GetNewMetaObject(file.FileData.Length, cName, file.ContentType);
            }

            //Validate the meta after updating file name
            if (!MetaValidator.Validate(meta, webm))
            {
                return VirtualClose(entity, webm, HttpStatusCode.UnprocessableEntity);
            }

            //Add or update the content
            await _content.SetContentAsync(channel, meta, file.FileData, file.ContentType, entity.EventCancellation);

            //Return the meta
            webm.Result = meta;
            webm.Success = true;

            return VirtualOk(entity, webm);
        }

        protected override async ValueTask<VfReturnType> DeleteAsync(HttpEntity entity)
        {
            if (!entity.Session.CanRead())
            {
                return VfReturnType.Forbidden;
            }

            //Get the channel id
            if (!entity.QueryArgs.TryGetNonEmptyValue("channel", out string? channelId))
            {
                return VfReturnType.BadRequest;
            }

            //get the content id
            if (!entity.QueryArgs.TryGetNonEmptyValue("id", out string? contentId))
            {
                return VfReturnType.BadRequest;
            }

            //Get channel
            IChannelContext? channel = await _blogContextManager.GetChannelAsync(channelId, entity.EventCancellation);
            if (channel == null)
            {
                return VfReturnType.NotFound;
            }

            //Try to delete the content
            bool deleted = await _content.DeleteContentAsync(channel, contentId, entity.EventCancellation);

            return deleted ? VirtualOk(entity) : VfReturnType.NotFound;
        }
    }

}