aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/Social/SharingRepository.cs
blob: d6d7f021a39738d9ade0fd392b1394de37f20ac5 (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
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Social;
using MediaBrowser.Server.Implementations.Persistence;
using System;
using System.Data;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace MediaBrowser.Server.Implementations.Social
{
    public class SharingRepository : BaseSqliteRepository
    {
        private IDbConnection _connection;
        private IDbCommand _saveShareCommand;
        private readonly IApplicationPaths _appPaths;

        public SharingRepository(ILogManager logManager, IApplicationPaths appPaths)
            : base(logManager)
        {
            _appPaths = appPaths;
        }

        /// <summary>
        /// Opens the connection to the database
        /// </summary>
        /// <returns>Task.</returns>
        public async Task Initialize()
        {
            var dbFile = Path.Combine(_appPaths.DataPath, "shares.db");

            _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false);

            string[] queries = {

                                "create table if not exists Shares (Id GUID, ItemId TEXT, UserId TEXT, ExpirationDate DateTime, PRIMARY KEY (Id))",
                                "create index if not exists idx_Shares on Shares(Id)",

                                //pragmas
                                "pragma temp_store = memory",

                                "pragma shrink_memory"
                               };

            _connection.RunQueries(queries, Logger);

            PrepareStatements();
        }

        /// <summary>
        /// Prepares the statements.
        /// </summary>
        private void PrepareStatements()
        {
            _saveShareCommand = _connection.CreateCommand();
            _saveShareCommand.CommandText = "replace into Shares (Id, ItemId, UserId, ExpirationDate) values (@Id, @ItemId, @UserId, @ExpirationDate)";

            _saveShareCommand.Parameters.Add(_saveShareCommand, "@Id");
            _saveShareCommand.Parameters.Add(_saveShareCommand, "@ItemId");
            _saveShareCommand.Parameters.Add(_saveShareCommand, "@UserId");
            _saveShareCommand.Parameters.Add(_saveShareCommand, "@ExpirationDate");
        }

        public async Task CreateShare(SocialShareInfo info)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }
            if (string.IsNullOrWhiteSpace(info.Id))
            {
                throw new ArgumentNullException("info.Id");
            }

            var cancellationToken = CancellationToken.None;

            cancellationToken.ThrowIfCancellationRequested();

            await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false);

            IDbTransaction transaction = null;

            try
            {
                transaction = _connection.BeginTransaction();

                _saveShareCommand.GetParameter(0).Value = new Guid(info.Id);
                _saveShareCommand.GetParameter(1).Value = info.ItemId;
                _saveShareCommand.GetParameter(2).Value = info.UserId;
                _saveShareCommand.GetParameter(3).Value = info.ExpirationDate;

                _saveShareCommand.Transaction = transaction;

                _saveShareCommand.ExecuteNonQuery();

                transaction.Commit();
            }
            catch (OperationCanceledException)
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }

                throw;
            }
            catch (Exception e)
            {
                Logger.ErrorException("Failed to save share:", e);

                if (transaction != null)
                {
                    transaction.Rollback();
                }

                throw;
            }
            finally
            {
                if (transaction != null)
                {
                    transaction.Dispose();
                }

                WriteLock.Release();
            }
        }

        public SocialShareInfo GetShareInfo(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException("id");
            }

            var cmd = _connection.CreateCommand();
            cmd.CommandText = "select Id, ItemId, UserId, ExpirationDate from Shares where id = @id";

            cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value = new Guid(id);

            using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
            {
                if (reader.Read())
                {
                    return GetSocialShareInfo(reader);
                }
            }

            return null;
        }

        private SocialShareInfo GetSocialShareInfo(IDataReader reader)
        {
            var info = new SocialShareInfo();

            info.Id = reader.GetGuid(0).ToString("N");
            info.ItemId = reader.GetString(1);
            info.UserId = reader.GetString(2);
            info.ExpirationDate = reader.GetDateTime(3).ToUniversalTime();

            return info;
        }

        public async Task DeleteShare(string id)
        {
            
        }

        protected override void CloseConnection()
        {
            if (_connection != null)
            {
                if (_connection.IsOpen())
                {
                    _connection.Close();
                }

                _connection.Dispose();
                _connection = null;
            }
        }
    }
}