aboutsummaryrefslogtreecommitdiff
path: root/Timeline/Controllers/TimelineController.cs
blob: b376bce5056be78575590f22b1106be9ab90b15e (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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Timeline.Filters;
using Timeline.Helpers;
using Timeline.Models;
using Timeline.Models.Http;
using Timeline.Models.Validation;
using Timeline.Services;
using Timeline.Services.Exceptions;

namespace Timeline.Controllers
{
    /// <summary>
    /// Operations about timeline.
    /// </summary>
    [ApiController]
    [CatchTimelineNotExistException]
    [ProducesErrorResponseType(typeof(CommonResponse))]
    public class TimelineController : Controller
    {
        private readonly ILogger<TimelineController> _logger;

        private readonly IUserService _userService;
        private readonly ITimelineService _service;

        private readonly IMapper _mapper;

        /// <summary>
        /// 
        /// </summary>
        public TimelineController(ILogger<TimelineController> logger, IUserService userService, ITimelineService service, IMapper mapper)
        {
            _logger = logger;
            _userService = userService;
            _service = service;
            _mapper = mapper;
        }

        /// <summary>
        /// List all timelines.
        /// </summary>
        /// <param name="relate">A username. If set, only timelines related to the user will return.</param>
        /// <param name="relateType">Specify the relation type, may be 'own' or 'join'. If not set, both type will return.</param>
        /// <param name="visibility">"Private" or "Register" or "Public". If set, only timelines whose visibility is specified one will return.</param>
        /// <response code="200">Succeeded to get timelines.</response>
        /// <response code="400">Model is invalid. Or user specified by "relate" param does not exist.</response>
        [HttpGet("timelines")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<ActionResult<List<TimelineInfo>>> TimelineList([FromQuery][Username] string? relate, [FromQuery][RegularExpression("(own)|(join)")] string? relateType, [FromQuery] string? visibility)
        {
            List<TimelineVisibility>? visibilityFilter = null;
            if (visibility != null)
            {
                visibilityFilter = new List<TimelineVisibility>();
                var items = visibility.Split('|');
                foreach (var item in items)
                {
                    if (item.Equals(nameof(TimelineVisibility.Private), StringComparison.OrdinalIgnoreCase))
                    {
                        if (!visibilityFilter.Contains(TimelineVisibility.Private))
                            visibilityFilter.Add(TimelineVisibility.Private);
                    }
                    else if (item.Equals(nameof(TimelineVisibility.Register), StringComparison.OrdinalIgnoreCase))
                    {
                        if (!visibilityFilter.Contains(TimelineVisibility.Register))
                            visibilityFilter.Add(TimelineVisibility.Register);
                    }
                    else if (item.Equals(nameof(TimelineVisibility.Public), StringComparison.OrdinalIgnoreCase))
                    {
                        if (!visibilityFilter.Contains(TimelineVisibility.Public))
                            visibilityFilter.Add(TimelineVisibility.Public);
                    }
                    else
                    {
                        return BadRequest(ErrorResponse.Common.CustomMessage_InvalidModel(Resources.Messages.TimelineController_QueryVisibilityUnknown, item));
                    }
                }
            }

            TimelineUserRelationship? relationship = null;
            if (relate != null)
            {
                try
                {
                    var relatedUserId = await _userService.GetUserIdByUsername(relate);

                    relationship = new TimelineUserRelationship(relateType switch
                    {
                        "own" => TimelineUserRelationshipType.Own,
                        "join" => TimelineUserRelationshipType.Join,
                        _ => TimelineUserRelationshipType.Default
                    }, relatedUserId);
                }
                catch (UserNotExistException)
                {
                    return BadRequest(ErrorResponse.TimelineController.QueryRelateNotExist());
                }
            }

            var timelines = await _service.GetTimelines(relationship, visibilityFilter);
            var result = _mapper.Map<List<TimelineInfo>>(timelines);
            return result;
        }

        /// <summary>
        /// Get info of a timeline.
        /// </summary>
        /// <param name="name">The timeline name.</param>
        /// <param name="checkUniqueId">A unique id. If specified and if-modified-since is also specified, the timeline info will return when unique id is not the specified one even if it is not modified.</param>
        /// <param name="queryIfModifiedSince">Same effect as If-Modified-Since header and take precedence than it.</param>
        /// <param name="headerIfModifiedSince">If specified, will return 304 if not modified.</param>
        /// <response code="200">Succeeded to get timeline info.</response>
        /// <response code="304">Timeline not change.</response>
        /// <response code="404">Timeline does not exist.</response>
        [HttpGet("timelines/{name}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status304NotModified)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<TimelineInfo>> TimelineGet([FromRoute][GeneralTimelineName] string name, [FromQuery] string? checkUniqueId, [FromQuery(Name = "ifModifiedSince")] DateTime? queryIfModifiedSince, [FromHeader(Name = "If-Modified-Since")] DateTime? headerIfModifiedSince)
        {
            DateTime? ifModifiedSince = null;
            if (queryIfModifiedSince.HasValue)
            {
                ifModifiedSince = queryIfModifiedSince.Value;
            }
            else if (headerIfModifiedSince != null)
            {
                ifModifiedSince = headerIfModifiedSince.Value;
            }

            bool returnNotModified = false;

            if (ifModifiedSince.HasValue)
            {
                var lastModified = await _service.GetTimelineLastModifiedTime(name);
                if (lastModified < ifModifiedSince.Value)
                {
                    if (checkUniqueId != null)
                    {
                        var uniqueId = await _service.GetTimelineUniqueId(name);
                        if (uniqueId == checkUniqueId)
                        {
                            returnNotModified = true;
                        }
                    }
                    else
                    {
                        returnNotModified = true;
                    }
                }
            }

            if (returnNotModified)
            {
                return StatusCode(StatusCodes.Status304NotModified);
            }
            else
            {
                var timeline = await _service.GetTimeline(name);
                var result = _mapper.Map<TimelineInfo>(timeline);
                return result;
            }
        }

        /// <summary>
        /// Get posts of a timeline. You need to have permission.
        /// </summary>
        /// <param name="name">The name of the timeline.</param>
        /// <param name="modifiedSince">If set, only posts modified since the time will return.</param>
        /// <param name="includeDeleted">If set to true, deleted post will also return.</param>
        /// <response code="200">Succeeded to get posts.</response>
        /// <response code="403">You have no permission.</response>
        /// <response code="404">The timeline does not exist.</response>
        [HttpGet("timelines/{name}/posts")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<List<TimelinePostInfo>>> PostListGet([FromRoute][GeneralTimelineName] string name, [FromQuery] DateTime? modifiedSince, [FromQuery] bool? includeDeleted)
        {
            if (!this.IsAdministrator() && !await _service.HasReadPermission(name, this.GetOptionalUserId()))
            {
                return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
            }

            List<TimelinePost> posts = await _service.GetPosts(name, modifiedSince, includeDeleted ?? false);

            var result = _mapper.Map<List<TimelinePostInfo>>(posts);
            return result;
        }

        /// <summary>
        /// Get the data of a post. Usually a image post. You need to have permission.
        /// </summary>
        /// <param name="name">Timeline name.</param>
        /// <param name="id">The id of the post.</param>
        /// <param name="ifNoneMatch">If-None-Match header.</param>
        /// <response code="200">Succeeded to get data.</response>
        /// <response code="304">Data not changed.</response>
        /// <response code="400">Error code is 11040502 if post has no data.</response>
        /// <response code="403">You have no permission.</response>
        /// <response code="404">Timeline or post does not exist.</response>
        [HttpGet("timelines/{name}/posts/{id}/data")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(void), StatusCodes.Status304NotModified)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> PostDataGet([FromRoute][GeneralTimelineName] string name, [FromRoute] long id, [FromHeader(Name = "If-None-Match")] string? ifNoneMatch)
        {
            _ = ifNoneMatch;
            if (!this.IsAdministrator() && !await _service.HasReadPermission(name, this.GetOptionalUserId()))
            {
                return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
            }

            try
            {
                return await DataCacheHelper.GenerateActionResult(this, () => _service.GetPostDataETag(name, id), async () =>
                {
                    var data = await _service.GetPostData(name, id);
                    return data;
                });
            }
            catch (TimelinePostNotExistException)
            {
                return NotFound(ErrorResponse.TimelineController.PostNotExist());
            }
            catch (TimelinePostNoDataException)
            {
                return BadRequest(ErrorResponse.TimelineController.PostNoData());
            }
        }

        /// <summary>
        /// Create a new post. You need to have permission.
        /// </summary>
        /// <param name="name">Timeline name.</param>
        /// <param name="body"></param>
        /// <returns>Info of new post.</returns>
        /// <response code="200">Succeeded to create post and return info of new post.</response>
        /// <response code="400">Body model is invalid.</response>
        /// <response code="401">You have not logged in.</response>
        /// <response code="403">You have no permission.</response>
        [HttpPost("timelines/{name}/posts")]
        [Authorize]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<ActionResult<TimelinePostInfo>> PostPost([FromRoute][GeneralTimelineName] string name, [FromBody] TimelinePostCreateRequest body)
        {
            var id = this.GetUserId();
            if (!this.IsAdministrator() && !await _service.IsMemberOf(name, id))
            {
                return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
            }

            var content = body.Content;

            TimelinePost post;

            if (content.Type == TimelinePostContentTypes.Text)
            {
                var text = content.Text;
                if (text == null)
                {
                    return BadRequest(ErrorResponse.Common.CustomMessage_InvalidModel(Resources.Messages.TimelineController_TextContentTextRequired));
                }
                post = await _service.CreateTextPost(name, id, text, body.Time);
            }
            else if (content.Type == TimelinePostContentTypes.Image)
            {
                var base64Data = content.Data;
                if (base64Data == null)
                {
                    return BadRequest(ErrorResponse.Common.CustomMessage_InvalidModel(Resources.Messages.TimelineController_ImageContentDataRequired));
                }
                byte[] data;
                try
                {
                    data = Convert.FromBase64String(base64Data);
                }
                catch (FormatException)
                {
                    return BadRequest(ErrorResponse.Common.CustomMessage_InvalidModel(Resources.Messages.TimelineController_ImageContentDataNotBase64));
                }

                try
                {
                    post = await _service.CreateImagePost(name, id, data, body.Time);
                }
                catch (ImageException)
                {
                    return BadRequest(ErrorResponse.Common.CustomMessage_InvalidModel(Resources.Messages.TimelineController_ImageContentDataNotImage));
                }
            }
            else
            {
                return BadRequest(ErrorResponse.Common.CustomMessage_InvalidModel(Resources.Messages.TimelineController_ContentUnknownType));
            }

            var result = _mapper.Map<TimelinePostInfo>(post);
            return result;
        }

        /// <summary>
        /// Delete a post.
        /// </summary>
        /// <param name="name">Timeline name.</param>
        /// <param name="id">Post id.</param>
        /// <response code="200">Succeeded to delete post. Or post does not exist.</response>
        /// <response code="401">You have not logged in.</response>
        /// <response code="403">You have no permission.</response>
        [HttpDelete("timelines/{name}/posts/{id}")]
        [Authorize]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<ActionResult<CommonDeleteResponse>> PostDelete([FromRoute][GeneralTimelineName] string name, [FromRoute] long id)
        {
            if (!this.IsAdministrator() && !await _service.HasPostModifyPermission(name, id, this.GetUserId()))
            {
                return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
            }
            try
            {
                await _service.DeletePost(name, id);
                return CommonDeleteResponse.Delete();
            }
            catch (TimelinePostNotExistException)
            {
                return CommonDeleteResponse.NotExist();
            }
        }

        /// <summary>
        /// Change properties of a timeline.
        /// </summary>
        /// <param name="name">Timeline name.</param>
        /// <param name="body"></param>
        /// <returns>The new info.</returns>
        /// <response code="200">Succeeded to change properties of timeline. Return the new info.</response>
        /// <response code="401">You have not logged in.</response>
        /// <response code="403">You have no permission.</response>
        [HttpPatch("timelines/{name}")]
        [Authorize]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<ActionResult<TimelineInfo>> TimelinePatch([FromRoute][GeneralTimelineName] string name, [FromBody] TimelinePatchRequest body)
        {
            if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId())))
            {
                return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
            }
            await _service.ChangeProperty(name, _mapper.Map<TimelineChangePropertyRequest>(body));
            var timeline = await _service.GetTimeline(name);
            var result = _mapper.Map<TimelineInfo>(timeline);
            return result;
        }

        /// <summary>
        /// Add a member to timeline.
        /// </summary>
        /// <param name="name">Timeline name.</param>
        /// <param name="member">The new member's username.</param>
        /// <response code="200">Succeeded.</response>
        /// <response code="400">User does not exist.</response>
        /// <response code="401">You have not logged in.</response>
        /// <response code="403">You have no permission.</response>
        [HttpPut("timelines/{name}/members/{member}")]
        [Authorize]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<ActionResult> TimelineMemberPut([FromRoute][GeneralTimelineName] string name, [FromRoute][Username] string member)
        {
            if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId())))
            {
                return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
            }

            try
            {
                await _service.ChangeMember(name, new List<string> { member }, null);
                return Ok();
            }
            catch (UserNotExistException)
            {
                return BadRequest(ErrorResponse.TimelineController.MemberPut_NotExist());
            }
        }

        /// <summary>
        /// Remove a member from timeline.
        /// </summary>
        /// <param name="name">Timeline name.</param>
        /// <param name="member">The member's username.</param>
        /// <response code="200">Succeeded. Or the user is not a member.</response>
        /// <response code="401">You have not logged in.</response>
        /// <response code="403">You have no permission.</response>
        [HttpDelete("timelines/{name}/members/{member}")]
        [Authorize]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<ActionResult> TimelineMemberDelete([FromRoute][GeneralTimelineName] string name, [FromRoute][Username] string member)
        {
            if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId())))
            {
                return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
            }

            try
            {
                await _service.ChangeMember(name, null, new List<string> { member });
                return Ok(CommonDeleteResponse.Delete());
            }
            catch (UserNotExistException)
            {
                return Ok(CommonDeleteResponse.NotExist());
            }
        }

        /// <summary>
        /// Create a timeline.
        /// </summary>
        /// <param name="body"></param>
        /// <returns>Info of new timeline.</returns>
        /// <response code="200">Succeeded and return info of new timeline.</response>
        /// <response code="400">Timeline name is conflict.</response>
        /// <response code="401">You have not logged in.</response>
        [HttpPost("timelines")]
        [Authorize]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        public async Task<ActionResult<TimelineInfo>> TimelineCreate([FromBody] TimelineCreateRequest body)
        {
            var userId = this.GetUserId();

            try
            {
                var timeline = await _service.CreateTimeline(body.Name, userId);
                var result = _mapper.Map<TimelineInfo>(timeline);
                return result;
            }
            catch (EntityAlreadyExistException e) when (e.EntityName == EntityNames.Timeline)
            {
                return BadRequest(ErrorResponse.TimelineController.NameConflict());
            }
        }

        /// <summary>
        /// Delete a timeline.
        /// </summary>
        /// <param name="name">Timeline name.</param>
        /// <response code="200">Succeeded. Or timeline does not exist.</response>
        /// <response code="401">You have not logged in.</response>
        /// <response code="403">You have no permission.</response>
        [HttpDelete("timelines/{name}")]
        [Authorize]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<ActionResult<CommonDeleteResponse>> TimelineDelete([FromRoute][TimelineName] string name)
        {
            if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId())))
            {
                return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
            }

            try
            {
                await _service.DeleteTimeline(name);
                return CommonDeleteResponse.Delete();
            }
            catch (TimelineNotExistException)
            {
                return CommonDeleteResponse.NotExist();
            }
        }
    }
}