aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline/Services/BookmarkTimelineService.cs
blob: 4c8bfdaedcaeb8de49894fd2626b50a44e429775 (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
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Timeline.Entities;
using Timeline.Services.Exceptions;

namespace Timeline.Services
{

    [Serializable]
    public class InvalidBookmarkException : Exception
    {
        public InvalidBookmarkException() { }
        public InvalidBookmarkException(string message) : base(message) { }
        public InvalidBookmarkException(string message, Exception inner) : base(message, inner) { }
        protected InvalidBookmarkException(
          System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
    }

    /// <summary>
    /// Service interface that manages timeline bookmarks.
    /// </summary>
    public interface IBookmarkTimelineService
    {
        /// <summary>
        /// Get bookmarks of a user.
        /// </summary>
        /// <param name="userId">User id of bookmark owner.</param>
        /// <returns>Id of Bookmark timelines in order.</returns>
        /// <exception cref="UserNotExistException">Thrown when user does not exist.</exception>
        Task<List<long>> GetBookmarks(long userId);

        /// <summary>
        /// Add a bookmark to tail to a user.
        /// </summary>
        /// <param name="userId">User id of bookmark owner.</param>
        /// <param name="timelineId">Timeline id.</param>
        /// <returns>True if timeline is added to bookmark. False if it already is.</returns>
        /// <exception cref="UserNotExistException">Thrown when user does not exist.</exception>
        /// <exception cref="TimelineNotExistException">Thrown when timeline does not exist.</exception>
        Task<bool> AddBookmark(long userId, long timelineId);

        /// <summary>
        /// Remove a bookmark from a user.
        /// </summary>
        /// <param name="userId">User id of bookmark owner.</param>
        /// <param name="timelineId">Timeline id.</param>
        /// <returns>True if deletion is performed. False if bookmark does not exist.</returns>
        /// <exception cref="UserNotExistException">Thrown when user does not exist.</exception>
        /// <exception cref="TimelineNotExistException">Thrown when timeline does not exist.</exception>
        Task<bool> RemoveBookmark(long userId, long timelineId);

        /// <summary>
        /// Move bookmark to a new position.
        /// </summary>
        /// <param name="userId">User id of bookmark owner.</param>
        /// <param name="timelineId">Timeline name.</param>
        /// <param name="newPosition">New position. Starts at 1.</param>
        /// <exception cref="UserNotExistException">Thrown when user does not exist.</exception>
        /// <exception cref="TimelineNotExistException">Thrown when timeline does not exist.</exception>
        /// <exception cref="InvalidBookmarkException">Thrown when the timeline is not a bookmark.</exception>
        Task MoveBookmark(long userId, long timelineId, long newPosition);
    }

    public class BookmarkTimelineService : IBookmarkTimelineService
    {
        private readonly DatabaseContext _database;
        private readonly IBasicUserService _userService;
        private readonly IBasicTimelineService _timelineService;

        public BookmarkTimelineService(DatabaseContext database, IBasicUserService userService, IBasicTimelineService timelineService)
        {
            _database = database;
            _userService = userService;
            _timelineService = timelineService;
        }

        public async Task<bool> AddBookmark(long userId, long timelineId)
        {
            if (!await _userService.CheckUserExistence(userId))
                throw new UserNotExistException(userId);

            if (!await _timelineService.CheckExistence(timelineId))
                throw new TimelineNotExistException(timelineId);

            if (await _database.BookmarkTimelines.AnyAsync(t => t.TimelineId == timelineId && t.UserId == userId))
                return false;

            _database.BookmarkTimelines.Add(new BookmarkTimelineEntity
            {
                TimelineId = timelineId,
                UserId = userId,
                Rank = (await _database.BookmarkTimelines.CountAsync(t => t.UserId == userId)) + 1
            });

            await _database.SaveChangesAsync();
            return true;
        }

        public async Task<List<long>> GetBookmarks(long userId)
        {
            if (!await _userService.CheckUserExistence(userId))
                throw new UserNotExistException(userId);

            var entities = await _database.BookmarkTimelines.Where(t => t.UserId == userId).OrderBy(t => t.Rank).Select(t => new { t.TimelineId }).ToListAsync();

            return entities.Select(e => e.TimelineId).ToList();
        }

        public async Task MoveBookmark(long userId, long timelineId, long newPosition)
        {
            if (!await _userService.CheckUserExistence(userId))
                throw new UserNotExistException(userId);

            if (!await _timelineService.CheckExistence(timelineId))
                throw new TimelineNotExistException(timelineId);

            var entity = await _database.BookmarkTimelines.SingleOrDefaultAsync(t => t.TimelineId == timelineId && t.UserId == userId);

            if (entity == null) throw new InvalidBookmarkException("You can't move a non-bookmark timeline.");

            var oldPosition = entity.Rank;

            if (newPosition < 1)
            {
                newPosition = 1;
            }
            else
            {
                var totalCount = await _database.BookmarkTimelines.CountAsync(t => t.UserId == userId);
                if (newPosition > totalCount) newPosition = totalCount;
            }

            if (oldPosition == newPosition) return;

            await using var transaction = await _database.Database.BeginTransactionAsync();

            if (newPosition > oldPosition)
            {
                await _database.Database.ExecuteSqlRawAsync("UPDATE `bookmark_timelines` SET `rank` = `rank` - 1 WHERE `rank` BETWEEN {0} AND {1} AND `user` = {2}", oldPosition + 1, newPosition, userId);
                await _database.Database.ExecuteSqlRawAsync("UPDATE `bookmark_timelines` SET `rank` = {0} WHERE `id` = {1}", newPosition, entity.Id);
            }
            else
            {
                await _database.Database.ExecuteSqlRawAsync("UPDATE `bookmark_timelines` SET `rank` = `rank` + 1 WHERE `rank` BETWEEN {0} AND {1} AND `user` = {2}", newPosition, oldPosition - 1, userId);
                await _database.Database.ExecuteSqlRawAsync("UPDATE `bookmark_timelines` SET `rank` = {0} WHERE `id` = {1}", newPosition, entity.Id);
            }

            await transaction.CommitAsync();
        }

        public async Task<bool> RemoveBookmark(long userId, long timelineId)
        {
            if (!await _userService.CheckUserExistence(userId))
                throw new UserNotExistException(userId);

            if (!await _timelineService.CheckExistence(timelineId))
                throw new TimelineNotExistException(timelineId);

            var entity = await _database.BookmarkTimelines.SingleOrDefaultAsync(t => t.UserId == userId && t.TimelineId == timelineId);

            if (entity == null) return false;

            await using var transaction = await _database.Database.BeginTransactionAsync();

            var rank = entity.Rank;

            _database.BookmarkTimelines.Remove(entity);
            await _database.SaveChangesAsync();

            await _database.Database.ExecuteSqlRawAsync("UPDATE `bookmark_timelines` SET `rank` = `rank` - 1 WHERE `rank` > {0}", rank);

            await transaction.CommitAsync();

            return true;
        }
    }
}