├── .gitignore ├── InfuseSync.sln ├── InfuseSync ├── API │ ├── InfuseSyncController.cs │ └── InfuseSyncService.cs ├── Configuration │ ├── PluginConfiguration.cs │ ├── PluginOptions.cs │ └── configPage.html ├── EntryPoints │ ├── LibrarySyncManager.cs │ ├── Shared.cs │ └── UserSyncManager.cs ├── InfuseSync.Emby.csproj ├── InfuseSync.Jellyfin.csproj ├── Logging │ └── ILoggerExtensions.cs ├── Models │ ├── Checkpoint.cs │ ├── CheckpointId.cs │ ├── ItemRec.cs │ ├── RemovedItem.cs │ ├── SyncStats.cs │ └── UserInfoRec.cs ├── Plugin.cs ├── PluginServiceRegistrator.cs ├── ScheduledTasks │ └── HousekeepingTask.cs ├── Storage │ ├── Db.cs │ ├── Emby │ │ ├── BaseSqliteRepository.cs │ │ └── SqliteExtensions.cs │ ├── Jellyfin │ │ ├── BaseSqliteRepository.cs │ │ ├── SqliteExtensions.cs │ │ ├── SynchronousMode.cs │ │ └── TempStoreMode.cs │ ├── Migrations │ │ ├── DbVersionManager.cs │ │ ├── IDbMigration.cs │ │ ├── MigrationChangeUserDataPrimaryKey.cs │ │ └── MigrationDropBetaDatabase.cs │ └── ReaderWriterLockSlimExtensions.cs └── thumb.png ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.*~ 3 | project.lock.json 4 | .DS_Store 5 | *.pyc 6 | nupkg/ 7 | 8 | # Visual Studio 9 | .vs/ 10 | 11 | # Visual Studio Code 12 | .vscode 13 | 14 | # Rider 15 | .idea 16 | 17 | # User-specific files 18 | *.suo 19 | *.user 20 | *.userosscache 21 | *.sln.docstates 22 | 23 | # Build results 24 | [Dd]ebug/ 25 | [Dd]ebugPublic/ 26 | [Rr]elease/ 27 | [Rr]eleases/ 28 | x64/ 29 | x86/ 30 | build/ 31 | bld/ 32 | [Bb]in/ 33 | [Oo]bj/ 34 | [Oo]ut/ 35 | msbuild.log 36 | msbuild.err 37 | msbuild.wrn 38 | -------------------------------------------------------------------------------- /InfuseSync.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26124.0 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InfuseSync.Emby", "InfuseSync\InfuseSync.Emby.csproj", "{41CD3BB1-3523-4046-922B-BD83B012C65B}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InfuseSync.Jellyfin", "InfuseSync\InfuseSync.Jellyfin.csproj", "{054AE498-0E3F-40B2-BAD9-5646A2BE24ED}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(SolutionProperties) = preSolution 16 | HideSolutionNode = FALSE 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {41CD3BB1-3523-4046-922B-BD83B012C65B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {41CD3BB1-3523-4046-922B-BD83B012C65B}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {41CD3BB1-3523-4046-922B-BD83B012C65B}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {41CD3BB1-3523-4046-922B-BD83B012C65B}.Release|Any CPU.Build.0 = Release|Any CPU 23 | {054AE498-0E3F-40B2-BAD9-5646A2BE24ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {054AE498-0E3F-40B2-BAD9-5646A2BE24ED}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {054AE498-0E3F-40B2-BAD9-5646A2BE24ED}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {054AE498-0E3F-40B2-BAD9-5646A2BE24ED}.Release|Any CPU.Build.0 = Release|Any CPU 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /InfuseSync/API/InfuseSyncController.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Net.Mime; 6 | using InfuseSync.Models; 7 | using MediaBrowser.Common.Extensions; 8 | using MediaBrowser.Controller.Dto; 9 | using MediaBrowser.Controller.Library; 10 | using MediaBrowser.Model.Dto; 11 | using MediaBrowser.Model.Entities; 12 | using MediaBrowser.Model.Querying; 13 | using Microsoft.AspNetCore.Authorization; 14 | using Microsoft.AspNetCore.Http; 15 | using Microsoft.AspNetCore.Mvc; 16 | using Microsoft.Extensions.Logging; 17 | 18 | namespace InfuseSync.API 19 | { 20 | /// 21 | /// ASP.NET Core MVC controller for Jellyfin plugin. 22 | /// Wraps . 23 | /// 24 | [ApiController] 25 | #if EMBY 26 | [Authorize(Policy = "DefaultAuthorization")] 27 | #endif 28 | [Produces(MediaTypeNames.Application.Json)] 29 | public class InfuseSyncController : ControllerBase 30 | { 31 | private readonly InfuseSyncService _service; 32 | 33 | public InfuseSyncController( 34 | ILogger logger, 35 | IUserManager userManager, 36 | IUserDataManager userDataManager, 37 | ILibraryManager libraryManager, 38 | IDtoService dtoService) 39 | { 40 | _service = new InfuseSyncService 41 | ( 42 | logger, 43 | userManager, 44 | userDataManager, 45 | libraryManager, 46 | dtoService 47 | ); 48 | } 49 | 50 | /// 51 | /// Creates new synchronization checkpoint and removes previous device checkpoints. 52 | /// 53 | /// Unique device identifier. 54 | /// User identifier. 55 | /// A . 56 | [HttpPost("InfuseSync/Checkpoint")] 57 | public ActionResult CreateCheckpoint( 58 | [FromQuery] string deviceId, 59 | [FromQuery] string userId) 60 | { 61 | var request = new CreateCheckpoint 62 | { 63 | DeviceID = deviceId, 64 | UserID = userId 65 | }; 66 | return _service.Post(request); 67 | } 68 | 69 | /// 70 | /// Starts synchronization session for a checkpoint and returns items statistics. 71 | /// 72 | /// Checkpoint identifier. 73 | /// A . 74 | [HttpPost("InfuseSync/Checkpoint/{checkpointID}/StartSync")] 75 | public ActionResult StartCheckpointSync([FromRoute] Guid checkpointID) 76 | { 77 | var request = new StartCheckpointSync 78 | { 79 | CheckpointID = checkpointID 80 | }; 81 | return _service.Post(request); 82 | } 83 | 84 | /// 85 | /// Get updated items for {checkpointId}. 86 | /// 87 | /// The checkpoint ID. 88 | /// List of item types to include in the result. 89 | /// Additional fields of information to return in the output. This allows multiple, comma delimeted values. 90 | /// Offset for items to fetch. 91 | /// Maximum number of items to fetch. 92 | /// The with the list of for updated items. 93 | [HttpGet("InfuseSync/Checkpoint/{checkpointID}/UpdatedItems")] 94 | [ProducesResponseType(StatusCodes.Status200OK)] 95 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 96 | [ProducesResponseType(StatusCodes.Status404NotFound)] 97 | public ActionResult> GetUpdatedItemsQuery( 98 | [FromRoute] Guid checkpointID, 99 | [FromQuery] string? includeItemTypes, 100 | [FromQuery] string fields, 101 | [FromQuery] int? startIndex, 102 | [FromQuery] int? limit) 103 | { 104 | var request = new GetUpdatedItemsQuery 105 | { 106 | CheckpointID = checkpointID, 107 | IncludeItemTypes = includeItemTypes, 108 | Fields = fields, 109 | StartIndex = startIndex, 110 | Limit = limit 111 | }; 112 | 113 | try 114 | { 115 | return _service.Get(request); 116 | } 117 | catch (ArgumentException e) 118 | { 119 | return BadRequest(e.Message); 120 | } 121 | catch (ResourceNotFoundException e) 122 | { 123 | return NotFound(e.Message); 124 | } 125 | } 126 | 127 | /// 128 | /// Get removed item IDs for {checkpointID}. 129 | /// 130 | /// The checkpoint ID. 131 | /// List of item types to include in the result. 132 | /// Offset for items to fetch. 133 | /// Maximum number of items to fetch. 134 | /// The with the list of . 135 | [HttpGet("InfuseSync/Checkpoint/{checkpointID}/RemovedItems")] 136 | [ProducesResponseType(StatusCodes.Status200OK)] 137 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 138 | [ProducesResponseType(StatusCodes.Status404NotFound)] 139 | public ActionResult> GetRemovedItemsQuery( 140 | [FromRoute] Guid checkpointID, 141 | [FromQuery] string? includeItemTypes, 142 | [FromQuery] int? startIndex, 143 | [FromQuery] int? limit) 144 | { 145 | var request = new GetRemovedItemsQuery 146 | { 147 | CheckpointID = checkpointID, 148 | IncludeItemTypes = includeItemTypes, 149 | StartIndex = startIndex, 150 | Limit = limit 151 | }; 152 | 153 | try 154 | { 155 | return _service.Get(request); 156 | } 157 | catch (ArgumentException e) 158 | { 159 | return BadRequest(e.Message); 160 | } 161 | catch (ResourceNotFoundException e) 162 | { 163 | return NotFound(e.Message); 164 | } 165 | } 166 | 167 | /// 168 | /// Get updated user data for {checkpointID}. 169 | /// 170 | /// The checkpoint ID. 171 | /// List of item types to include in the result. 172 | /// Offset for items to fetch. 173 | /// Maximum number of items to fetch. 174 | /// The with the list of . 175 | [HttpGet("InfuseSync/Checkpoint/{checkpointID}/UserData")] 176 | [ProducesResponseType(StatusCodes.Status200OK)] 177 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 178 | [ProducesResponseType(StatusCodes.Status404NotFound)] 179 | public ActionResult> GetUserDataQuery( 180 | [FromRoute] Guid checkpointID, 181 | [FromQuery] string? includeItemTypes, 182 | [FromQuery] int? startIndex, 183 | [FromQuery] int? limit) 184 | { 185 | var request = new GetUserDataQuery 186 | { 187 | CheckpointID = checkpointID, 188 | IncludeItemTypes = includeItemTypes, 189 | StartIndex = startIndex, 190 | Limit = limit 191 | }; 192 | 193 | try 194 | { 195 | return _service.Get(request); 196 | } 197 | catch (ArgumentException e) 198 | { 199 | return BadRequest(e.Message); 200 | } 201 | catch (ResourceNotFoundException e) 202 | { 203 | return NotFound(e.Message); 204 | } 205 | } 206 | 207 | /// 208 | /// Returns the list of user libraries and folders. 209 | /// 210 | /// User identifier. 211 | /// List of . 212 | [HttpGet("InfuseSync/UserFolders/{userID}")] 213 | [ProducesResponseType(StatusCodes.Status200OK)] 214 | [ProducesResponseType(StatusCodes.Status404NotFound)] 215 | public ActionResult> GetUserFolders([FromRoute] string userID) 216 | { 217 | var request = new GetUserFolders 218 | { 219 | UserID = userID 220 | }; 221 | 222 | try 223 | { 224 | return _service.Get(request); 225 | } 226 | catch (ResourceNotFoundException e) 227 | { 228 | return NotFound(e.Message); 229 | } 230 | } 231 | } 232 | } -------------------------------------------------------------------------------- /InfuseSync/API/InfuseSyncService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using InfuseSync.Models; 5 | using MediaBrowser.Common.Extensions; 6 | using MediaBrowser.Controller.Entities; 7 | using MediaBrowser.Controller.Library; 8 | using MediaBrowser.Controller.Dto; 9 | using MediaBrowser.Model.Dto; 10 | using MediaBrowser.Model.Entities; 11 | using MediaBrowser.Model.Querying; 12 | 13 | #if EMBY 14 | using MediaBrowser.Model.Services; 15 | using MediaBrowser.Controller.Net; 16 | using InfuseSync.Logging; 17 | using ILogger = MediaBrowser.Model.Logging.ILogger; 18 | #else 19 | using Jellyfin.Data.Entities; 20 | using Microsoft.Extensions.Logging; 21 | using System.Globalization; 22 | #endif 23 | 24 | namespace InfuseSync.API 25 | { 26 | #if EMBY 27 | [Route("/InfuseSync/Checkpoint", "POST", Summary = "Create new synchronization checkpoint and remove previous device checkpoints")] 28 | [Authenticated] 29 | #endif 30 | public class CreateCheckpoint 31 | #if EMBY 32 | : IReturn 33 | #endif 34 | { 35 | #if EMBY 36 | [ApiMember(Name = "DeviceID", Description = "Unique device identifier", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] 37 | [ApiMember(Name = "UserID", Description = "User identifier", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] 38 | #endif 39 | public string DeviceID { get; set; } 40 | public string UserID { get; set; } 41 | } 42 | 43 | #if EMBY 44 | [Route("/InfuseSync/Checkpoint/{CheckpointID}/StartSync", "POST", Summary = "Start synchronization session for a checkpoint and return items statistics")] 45 | [Authenticated] 46 | #endif 47 | public class StartCheckpointSync 48 | #if EMBY 49 | : IReturn 50 | #endif 51 | { 52 | #if EMBY 53 | [ApiMember(Name = "CheckpointID", Description = "Checkpoint identifier", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] 54 | #endif 55 | public Guid CheckpointID { get; set; } 56 | } 57 | 58 | #if EMBY 59 | [Route("/InfuseSync/Checkpoint/{CheckpointID}/UpdatedItems", "GET", Summary = "Get updated items for {CheckpointID}")] 60 | [Authenticated] 61 | #endif 62 | public class GetUpdatedItemsQuery 63 | #if EMBY 64 | : IReturn> 65 | #endif 66 | { 67 | #if EMBY 68 | [ApiMember(Name = "CheckpointID", Description = "Checkpoint identifier", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] 69 | [ApiMember(Name = "IncludeItemTypes", Description = "Optional list of item types to include in the result", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")] 70 | [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted values.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)] 71 | [ApiMember(Name = "StartIndex", Description = "Offset for items to fetch", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] 72 | [ApiMember(Name = "Limit", Description = "Maximum number of items to fetch", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] 73 | #endif 74 | public Guid CheckpointID { get; set; } 75 | public string IncludeItemTypes { get; set; } 76 | public string Fields { get; set; } 77 | public int? StartIndex { get; set; } 78 | public int? Limit { get; set; } 79 | 80 | public ItemFields[] GetItemFields() 81 | { 82 | if (string.IsNullOrEmpty(Fields)) 83 | { 84 | return Array.Empty(); 85 | } 86 | 87 | return Fields.Split(',').Select(v => 88 | { 89 | if (Enum.TryParse(v, true, out ItemFields value)) 90 | { 91 | return (ItemFields?)value; 92 | } 93 | return null; 94 | }).Where(i => i.HasValue).Select(i => i.Value).ToArray(); 95 | } 96 | } 97 | 98 | #if EMBY 99 | [Route("/InfuseSync/Checkpoint/{CheckpointID}/RemovedItems", "GET", Summary = "Get removed item IDs for {CheckpointID}")] 100 | [Authenticated] 101 | #endif 102 | public class GetRemovedItemsQuery 103 | #if EMBY 104 | : IReturn> 105 | #endif 106 | { 107 | #if EMBY 108 | [ApiMember(Name = "CheckpointID", Description = "Checkpoint identifier", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] 109 | [ApiMember(Name = "IncludeItemTypes", Description = "Optional list of item types to include in the result", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")] 110 | [ApiMember(Name = "StartIndex", Description = "Offset for items to fetch", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] 111 | [ApiMember(Name = "Limit", Description = "Maximum number of items to fetch", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] 112 | #endif 113 | public Guid CheckpointID { get; set; } 114 | public string IncludeItemTypes { get; set; } 115 | public int? StartIndex { get; set; } 116 | public int? Limit { get; set; } 117 | } 118 | 119 | #if EMBY 120 | [Route("/InfuseSync/Checkpoint/{CheckpointID}/UserData", "GET", Summary = "Get updated user data for {CheckpointID}")] 121 | [Authenticated] 122 | #endif 123 | public class GetUserDataQuery 124 | #if EMBY 125 | : IReturn> 126 | #endif 127 | { 128 | #if EMBY 129 | [ApiMember(Name = "CheckpointID", Description = "Checkpoint identifier", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] 130 | [ApiMember(Name = "IncludeItemTypes", Description = "Optional list of item types to include in the result", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")] 131 | [ApiMember(Name = "StartIndex", Description = "Offset for items to fetch", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] 132 | [ApiMember(Name = "Limit", Description = "Maximum number of items to fetch", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] 133 | #endif 134 | public Guid CheckpointID { get; set; } 135 | public string IncludeItemTypes { get; set; } 136 | public int? StartIndex { get; set; } 137 | public int? Limit { get; set; } 138 | } 139 | 140 | #if EMBY 141 | [Route("/InfuseSync/UserFolders/{UserID}", "GET", Summary = "Get updated user data for {CheckpointID}")] 142 | [Authenticated] 143 | #endif 144 | public class GetUserFolders 145 | #if EMBY 146 | : IReturn> 147 | #endif 148 | { 149 | #if EMBY 150 | [ApiMember(Name = "UserID", Description = "User identifier", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] 151 | #endif 152 | public string UserID { get; set; } 153 | } 154 | 155 | public class InfuseSyncService 156 | #if EMBY 157 | : IService 158 | #endif 159 | { 160 | private readonly ILogger _logger; 161 | private readonly IUserManager _userManager; 162 | private readonly IUserDataManager _userDataManager; 163 | private readonly ILibraryManager _libraryManager; 164 | private readonly IDtoService _dtoService; 165 | 166 | public InfuseSyncService( 167 | ILogger logger, 168 | IUserManager userManager, 169 | IUserDataManager userDataManager, 170 | ILibraryManager libraryManager, 171 | IDtoService dtoService) 172 | { 173 | _logger = logger; 174 | _userManager = userManager; 175 | _userDataManager = userDataManager; 176 | _libraryManager = libraryManager; 177 | _dtoService = dtoService; 178 | } 179 | 180 | public CheckpointId Post(CreateCheckpoint request) 181 | { 182 | _logger.LogDebug($"InfuseSync: Create checkpoint request for DeviceID '{request.DeviceID}' UserID '{request.UserID}'"); 183 | 184 | var newCheckpoint = Plugin.Instance.Db.CreateCheckpoint(request.DeviceID, request.UserID); 185 | 186 | return new CheckpointId { Id = newCheckpoint.Guid }; 187 | } 188 | 189 | public SyncStats Post(StartCheckpointSync request) 190 | { 191 | _logger.LogDebug($"InfuseSync: Sync request for CheckpointID '{request.CheckpointID}'"); 192 | 193 | var checkpoint = Plugin.Instance.Db.GetCheckpoint(request.CheckpointID); 194 | if (checkpoint == null) 195 | { 196 | throw new ResourceNotFoundException($"Checkpoint with ID '{request.CheckpointID}' not found."); 197 | } 198 | 199 | var db = Plugin.Instance.Db; 200 | 201 | var syncTimestamp = DateTime.UtcNow.ToFileTime(); 202 | db.UpdateCheckpoint(request.CheckpointID, syncTimestamp); 203 | 204 | var folderTypes = new string [] {"Folder"}; 205 | var boxSetTypes = new string [] {"BoxSet"}; 206 | var playlistTypes = new string [] {"Playlist"}; 207 | var seriesTypes = new string [] {"Series"}; 208 | var seasonTypes = new string [] {"Season"}; 209 | var collectionFolderTypes = new string [] {"CollectionFolder"}; 210 | var videoTypes = new string [] {"Video", "MusicVideo", "Movie", "Episode"}; 211 | 212 | return new SyncStats { 213 | UpdatedFolders = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Updated, folderTypes), 214 | RemovedFolders = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Removed, folderTypes), 215 | UpdatedBoxSets = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Updated, boxSetTypes), 216 | RemovedBoxSets = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Removed, boxSetTypes), 217 | UpdatedPlaylists = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Updated, playlistTypes), 218 | RemovedPlaylists = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Removed, playlistTypes), 219 | UpdatedTvShows = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Updated, seriesTypes), 220 | RemovedTvShows = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Removed, seriesTypes), 221 | UpdatedSeasons = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Updated, seasonTypes), 222 | RemovedSeasons = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Removed, seasonTypes), 223 | UpdatedVideos = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Updated, videoTypes), 224 | RemovedVideos = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Removed, videoTypes), 225 | UpdatedCollectionFolders = db.ItemsCount(checkpoint.Timestamp, syncTimestamp, ItemStatus.Updated, collectionFolderTypes), 226 | UpdatedUserData = db.UserInfoCount(checkpoint.Timestamp, syncTimestamp, checkpoint.UserId, videoTypes) 227 | }; 228 | } 229 | 230 | public QueryResult Get(GetUpdatedItemsQuery request) 231 | { 232 | _logger.LogDebug($"InfuseSync: Updated items requested for CheckpointID '{request.CheckpointID}'"); 233 | 234 | var checkpoint = Plugin.Instance.Db.GetCheckpoint(request.CheckpointID); 235 | if (checkpoint == null) 236 | { 237 | throw new ResourceNotFoundException($"Checkpoint with ID '{request.CheckpointID}' not found."); 238 | } 239 | if (checkpoint.SyncTimestamp == null) 240 | { 241 | throw new ArgumentException($"Sync session should be started before using the checkpoint."); 242 | } 243 | 244 | var includeTypes = request.IncludeItemTypes?.Split(','); 245 | 246 | var itemsUpdated = Plugin.Instance.Db.GetItems( 247 | checkpoint.Timestamp, 248 | checkpoint.SyncTimestamp.Value, 249 | ItemStatus.Updated, 250 | includeTypes, 251 | request.StartIndex ?? 0, 252 | request.Limit ?? int.MaxValue 253 | ); 254 | 255 | var totalCount = Plugin.Instance.Db.ItemsCount( 256 | checkpoint.Timestamp, 257 | checkpoint.SyncTimestamp.Value, 258 | ItemStatus.Updated, 259 | includeTypes 260 | ); 261 | 262 | var user = _userManager.GetUserById(Guid.Parse(checkpoint.UserId)); 263 | if (user == null) 264 | { 265 | throw new ResourceNotFoundException($"User not found for checkpoint with ID '{request.CheckpointID}'."); 266 | } 267 | 268 | var items = GetUserItems(user, itemsUpdated); 269 | 270 | var options = new DtoOptions { Fields = request.GetItemFields() }; 271 | var itemDtos = _dtoService.GetBaseItemDtos(items, options, user); 272 | 273 | return new QueryResult { 274 | Items = itemDtos, 275 | #if JELLYFIN 276 | StartIndex = request.StartIndex ?? 0, 277 | #endif 278 | TotalRecordCount = totalCount 279 | }; 280 | } 281 | 282 | private BaseItem[] GetUserItems(User user, IEnumerable itemRecs) 283 | { 284 | List items = new List(); 285 | foreach (ItemRec rec in itemRecs) 286 | { 287 | var item = _libraryManager.GetItemById(rec.Guid); 288 | if (item != null 289 | && !(item is AggregateFolder) 290 | && item.IsVisibleStandalone(user)) 291 | { 292 | items.Add(item); 293 | } 294 | } 295 | 296 | return items.ToArray(); 297 | } 298 | 299 | public QueryResult Get(GetRemovedItemsQuery request) 300 | { 301 | _logger.LogDebug($"InfuseSync: Removed items requested for CheckpointID '{request.CheckpointID}'"); 302 | 303 | var checkpoint = Plugin.Instance.Db.GetCheckpoint(request.CheckpointID); 304 | if (checkpoint == null) 305 | { 306 | throw new ResourceNotFoundException($"Checkpoint with ID '{request.CheckpointID}' not found."); 307 | } 308 | if (checkpoint.SyncTimestamp == null) 309 | { 310 | throw new ArgumentException($"Sync session should be started before using the checkpoint."); 311 | } 312 | 313 | var includeTypes = request.IncludeItemTypes?.Split(','); 314 | 315 | var itemsRemoved = Plugin.Instance.Db.GetItems( 316 | checkpoint.Timestamp, 317 | checkpoint.SyncTimestamp.Value, 318 | ItemStatus.Removed, 319 | includeTypes, 320 | request.StartIndex ?? 0, 321 | request.Limit ?? int.MaxValue 322 | ); 323 | 324 | var totalCount = Plugin.Instance.Db.ItemsCount( 325 | checkpoint.Timestamp, 326 | checkpoint.SyncTimestamp.Value, 327 | ItemStatus.Removed, 328 | includeTypes 329 | ); 330 | 331 | var removedItems = itemsRemoved.Select(x => new RemovedItem { 332 | #if EMBY 333 | ItemId = x.ItemId, 334 | SeriesId = x.SeriesId?.ToString(), 335 | #else 336 | ItemId = x.Guid, 337 | SeriesId = x.SeriesId, 338 | #endif 339 | Season = x.Season 340 | }).ToArray(); 341 | 342 | return new QueryResult { 343 | Items = removedItems, 344 | #if JELLYFIN 345 | StartIndex = request.StartIndex ?? 0, 346 | #endif 347 | TotalRecordCount = totalCount 348 | }; 349 | } 350 | 351 | public QueryResult Get(GetUserDataQuery request) 352 | { 353 | _logger.LogDebug($"InfuseSync: User data requested for CheckpointID '{request.CheckpointID}'"); 354 | 355 | var checkpoint = Plugin.Instance.Db.GetCheckpoint(request.CheckpointID); 356 | if (checkpoint == null) 357 | { 358 | throw new ResourceNotFoundException($"Checkpoint with ID '{request.CheckpointID}' not found."); 359 | } 360 | if (checkpoint.SyncTimestamp == null) 361 | { 362 | throw new ArgumentException($"Sync session should be started before using the checkpoint."); 363 | } 364 | 365 | var includeTypes = request.IncludeItemTypes?.Split(','); 366 | 367 | var updatedUserData = Plugin.Instance.Db.GetUserInfos( 368 | checkpoint.Timestamp, 369 | checkpoint.SyncTimestamp.Value, 370 | checkpoint.UserId, 371 | includeTypes, 372 | request.StartIndex ?? 0, 373 | request.Limit ?? int.MaxValue 374 | ); 375 | 376 | var totalCount = Plugin.Instance.Db.UserInfoCount( 377 | checkpoint.Timestamp, 378 | checkpoint.SyncTimestamp.Value, 379 | checkpoint.UserId, 380 | includeTypes 381 | ); 382 | 383 | var user = _userManager.GetUserById(Guid.Parse(checkpoint.UserId)); 384 | if (user == null) 385 | { 386 | throw new ResourceNotFoundException($"User not found for checkpoint with ID '{request.CheckpointID}'."); 387 | } 388 | 389 | var userData = updatedUserData 390 | #if EMBY 391 | .Select(data => new KeyValuePair(data.ItemId, _libraryManager.GetItemById(data.Guid))) 392 | #else 393 | .Select(data => KeyValuePair.Create(data.Guid, _libraryManager.GetItemById(data.Guid))) 394 | #endif 395 | .Where(pair => pair.Value != null) 396 | .Select(pair => { 397 | var dto = _userDataManager.GetUserDataDto(pair.Value, user); 398 | 399 | dto.ItemId = pair.Key; 400 | 401 | return dto; 402 | }) 403 | .ToArray(); 404 | 405 | return new QueryResult { 406 | Items = userData, 407 | #if JELLYFIN 408 | StartIndex = request.StartIndex ?? 0, 409 | #endif 410 | TotalRecordCount = totalCount 411 | }; 412 | } 413 | 414 | public List Get(GetUserFolders request) 415 | { 416 | _logger.LogDebug($"InfuseSync: User folders requested for UserID '{request.UserID}'"); 417 | 418 | var user = _userManager.GetUserById(Guid.Parse(request.UserID)); 419 | if (user == null) 420 | { 421 | throw new ResourceNotFoundException($"User with ID '{request.UserID}' not found."); 422 | } 423 | 424 | return _libraryManager.GetVirtualFolders() 425 | .Where(f => 426 | { 427 | var item = _libraryManager.GetItemById(f.ItemId); 428 | return item != null && item.IsVisibleStandalone(user); 429 | }) 430 | .ToList(); 431 | } 432 | } 433 | } 434 | -------------------------------------------------------------------------------- /InfuseSync/Configuration/PluginConfiguration.cs: -------------------------------------------------------------------------------- 1 | using MediaBrowser.Model.Plugins; 2 | 3 | namespace InfuseSync.Configuration 4 | { 5 | public class PluginConfiguration: BasePluginConfiguration 6 | { 7 | public int CacheExpirationDays { get; set; } 8 | 9 | public PluginConfiguration() 10 | { 11 | CacheExpirationDays = 30; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /InfuseSync/Configuration/PluginOptions.cs: -------------------------------------------------------------------------------- 1 | namespace InfuseSync.Configuration 2 | { 3 | using System.ComponentModel; 4 | using Emby.Web.GenericEdit; 5 | 6 | public class PluginOptions : EditableOptionsBase 7 | { 8 | public override string EditorTitle => "Infuse Sync"; 9 | 10 | [DisplayName("Cache Expiration")] 11 | [Description("Maximum days to keep cached data")] 12 | public int CacheExpirationDays { get; set; } 13 | 14 | public PluginOptions() 15 | { 16 | CacheExpirationDays = 30; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /InfuseSync/Configuration/configPage.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Infuse Sync 6 | 7 | 8 |
9 |
10 |
11 |
12 |
13 | 14 | 15 |
Maximum days to keep cached data
16 |
17 |
18 | 21 |
22 |
23 |
24 |
25 | 49 |
50 | 51 | -------------------------------------------------------------------------------- /InfuseSync/EntryPoints/LibrarySyncManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading; 5 | using MediaBrowser.Controller.Entities; 6 | using MediaBrowser.Controller.Entities.TV; 7 | using MediaBrowser.Controller.Library; 8 | using MediaBrowser.Controller.Plugins; 9 | using InfuseSync.Models; 10 | 11 | #if EMBY 12 | using InfuseSync.Logging; 13 | using ILogger = MediaBrowser.Model.Logging.ILogger; 14 | #else 15 | using System.Threading.Tasks; 16 | using Microsoft.Extensions.Hosting; 17 | using Microsoft.Extensions.Logging; 18 | using ILogger = Microsoft.Extensions.Logging.ILogger; 19 | #endif 20 | 21 | namespace InfuseSync.EntryPoints 22 | { 23 | #if EMBY 24 | public class LibrarySyncManager: IServerEntryPoint 25 | #else 26 | public class LibrarySyncManager: IHostedService 27 | #endif 28 | { 29 | private readonly ILibraryManager _libraryManager; 30 | private readonly ILogger _logger; 31 | private readonly object _libraryChangedSyncLock = new object(); 32 | 33 | private readonly List _itemsUpdated = new List(); 34 | private readonly List _itemsRemoved = new List(); 35 | 36 | private Timer WriteTimer { get; set; } 37 | private const int WriteDelay = 5000; 38 | 39 | public LibrarySyncManager(ILibraryManager libraryManager, ILogger logger) 40 | { 41 | _libraryManager = libraryManager; 42 | _logger = logger; 43 | } 44 | 45 | public void Run() 46 | { 47 | _libraryManager.ItemAdded += ItemUpdated; 48 | _libraryManager.ItemUpdated += ItemUpdated; 49 | _libraryManager.ItemRemoved += ItemRemoved; 50 | } 51 | 52 | #if JELLYFIN 53 | public Task StartAsync(CancellationToken cancellationToken) 54 | { 55 | Run(); 56 | 57 | return Task.CompletedTask; 58 | } 59 | #endif 60 | 61 | void ItemUpdated(object sender, ItemChangeEventArgs e) 62 | { 63 | var message = $"InfuseSync received updated item '{e.Item.Name}' of type '{e.Item.GetClientTypeName()}' Guid '{e.Item.Id}'"; 64 | #if EMBY 65 | message += $" ItemID '{e.Item.GetClientId()}'"; 66 | #endif 67 | _logger.LogDebug(message); 68 | 69 | if (!Shared.ShouldSyncUpdatedItem(e.Item)) 70 | { 71 | return; 72 | } 73 | 74 | if (!Plugin.Instance.Db.HasCheckpoints()) 75 | { 76 | return; 77 | } 78 | 79 | ItemUpdated(e.Item); 80 | } 81 | 82 | private void ItemUpdated(BaseItem item) 83 | { 84 | lock (_libraryChangedSyncLock) 85 | { 86 | if (WriteTimer == null) 87 | { 88 | WriteTimer = new Timer(TimerCallback, null, WriteDelay, Timeout.Infinite); 89 | } 90 | else 91 | { 92 | WriteTimer.Change(WriteDelay, Timeout.Infinite); 93 | } 94 | 95 | var itemRec = new ItemRec 96 | { 97 | Guid = item.Id, 98 | #if EMBY 99 | ItemId = item.GetClientId(), 100 | #endif 101 | Status = ItemStatus.Updated, 102 | Type = item.GetClientTypeName() 103 | }; 104 | 105 | _logger.LogDebug($"InfuseSync saving updated item {item.Id}"); 106 | _itemsUpdated.Add(itemRec); 107 | } 108 | } 109 | 110 | void ItemRemoved(object sender, ItemChangeEventArgs e) 111 | { 112 | var message = $"InfuseSync received removed item '{e.Item.Name}' of type '{e.Item.GetClientTypeName()}' Guid '{e.Item.Id}'"; 113 | #if EMBY 114 | message += $" ItemID '{e.Item.GetClientId()}'"; 115 | #endif 116 | _logger.LogDebug(message); 117 | 118 | if (!Shared.ShouldSyncRemovedItem(e.Item)) 119 | { 120 | return; 121 | } 122 | 123 | if (!Plugin.Instance.Db.HasCheckpoints()) 124 | { 125 | return; 126 | } 127 | 128 | // Folder already have no content in it when it is removed. 129 | // So we have to re-fetch all affected libraries. 130 | if (e.Item.GetType() == typeof(Folder)) 131 | { 132 | var topFolder = e.Parent.GetParents().LastOrDefault(i => i.GetType() == typeof(Folder)); 133 | if (topFolder == null && e.Parent.GetType() == typeof(Folder)) 134 | { 135 | topFolder = e.Parent; 136 | } 137 | 138 | if (topFolder != null) 139 | { 140 | var libs = _libraryManager.GetVirtualFolders() 141 | .Where(vf => vf.Locations.Contains(topFolder.Path)) 142 | .Select(vf => _libraryManager.GetItemById(vf.ItemId)); 143 | 144 | foreach (var lib in libs) 145 | { 146 | ItemUpdated(lib); 147 | } 148 | } 149 | } 150 | 151 | ItemRemoved(e.Item); 152 | } 153 | 154 | private void ItemRemoved(BaseItem item) 155 | { 156 | lock (_libraryChangedSyncLock) 157 | { 158 | if (WriteTimer == null) 159 | { 160 | WriteTimer = new Timer(TimerCallback, null, WriteDelay, Timeout.Infinite); 161 | } 162 | else 163 | { 164 | WriteTimer.Change(WriteDelay, Timeout.Infinite); 165 | } 166 | 167 | #if EMBY 168 | long? seriesId; 169 | #else 170 | Guid? seriesId; 171 | #endif 172 | int? seasonNumber; 173 | if (item is Season season) 174 | { 175 | seriesId = season.SeriesId; 176 | seasonNumber = season.IndexNumber; 177 | } 178 | else 179 | { 180 | seriesId = null; 181 | seasonNumber = null; 182 | } 183 | 184 | var itemRec = new ItemRec 185 | { 186 | Guid = item.Id, 187 | #if EMBY 188 | ItemId = item.GetClientId(), 189 | #endif 190 | SeriesId = seriesId, 191 | Season = seasonNumber, 192 | Status = ItemStatus.Removed, 193 | Type = item.GetClientTypeName() 194 | }; 195 | 196 | _logger.LogDebug($"InfuseSync saving removed item {item.Id}"); 197 | _itemsRemoved.Add(itemRec); 198 | } 199 | } 200 | 201 | private void TimerCallback(object state) 202 | { 203 | lock (_libraryChangedSyncLock) 204 | { 205 | try 206 | { 207 | var itemsUpdated = _itemsUpdated 208 | #if EMBY 209 | .GroupBy(i => i.ItemId) 210 | #else 211 | .GroupBy(i => i.Guid) 212 | #endif 213 | .Select(grp => grp.First()) 214 | .Select(i => {i.LastModified = DateTime.UtcNow.ToFileTime(); return i;}) 215 | .ToList(); 216 | var itemsRemoved = _itemsRemoved 217 | #if EMBY 218 | .GroupBy(i => i.ItemId) 219 | #else 220 | .GroupBy(i => i.Guid) 221 | #endif 222 | .Select(grp => grp.First()) 223 | .Select(i => {i.LastModified = DateTime.UtcNow.ToFileTime(); return i;}) 224 | .ToList(); 225 | 226 | Plugin.Instance.Db.SaveItems(itemsUpdated); 227 | Plugin.Instance.Db.SaveItems(itemsRemoved); 228 | 229 | if (WriteTimer != null) 230 | { 231 | WriteTimer.Dispose(); 232 | WriteTimer = null; 233 | } 234 | } 235 | catch (Exception e) 236 | { 237 | _logger.LogError(e, $"An error in TimerCallback: {e}"); 238 | } 239 | 240 | _itemsRemoved.Clear(); 241 | _itemsUpdated.Clear(); 242 | } 243 | } 244 | 245 | private bool _disposed; 246 | 247 | protected virtual void Dispose(bool disposing) 248 | { 249 | if (_disposed) 250 | { 251 | return; 252 | } 253 | 254 | if (disposing) 255 | { 256 | if (WriteTimer != null) 257 | { 258 | WriteTimer.Dispose(); 259 | WriteTimer = null; 260 | } 261 | 262 | _libraryManager.ItemAdded -= ItemUpdated; 263 | _libraryManager.ItemUpdated -= ItemUpdated; 264 | _libraryManager.ItemRemoved -= ItemRemoved; 265 | } 266 | 267 | _disposed = true; 268 | } 269 | 270 | #if EMBY 271 | public void Dispose() 272 | { 273 | Dispose(true); 274 | GC.SuppressFinalize(this); 275 | } 276 | #else 277 | public Task StopAsync(CancellationToken cancellationToken) 278 | { 279 | Dispose(true); 280 | 281 | return Task.CompletedTask; 282 | } 283 | #endif 284 | } 285 | } 286 | -------------------------------------------------------------------------------- /InfuseSync/EntryPoints/Shared.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using MediaBrowser.Controller.Channels; 4 | using MediaBrowser.Controller.Entities; 5 | 6 | namespace InfuseSync.EntryPoints 7 | { 8 | public class Shared 9 | { 10 | private static string[] SyncTypes = 11 | { 12 | "Movie", 13 | "BoxSet", 14 | "Series", 15 | "Season", 16 | "Episode", 17 | "Video", 18 | "MusicVideo", 19 | "Folder", 20 | "Playlist" 21 | }; 22 | 23 | public static bool ShouldSyncUpdatedItem(BaseItem item) 24 | { 25 | return ShouldSyncItem(item, t => SyncTypes.Contains(t) || t == "CollectionFolder"); 26 | } 27 | 28 | public static bool ShouldSyncRemovedItem(BaseItem item) 29 | { 30 | return ShouldSyncItem(item, t => SyncTypes.Contains(t)); 31 | } 32 | 33 | private static bool ShouldSyncItem(BaseItem item, Func typeCheck) 34 | { 35 | if (item.LocationType == MediaBrowser.Model.Entities.LocationType.Virtual) 36 | { 37 | return false; 38 | } 39 | 40 | if (item.GetTopParent() is Channel) 41 | { 42 | return false; 43 | } 44 | 45 | var typeName = item.GetClientTypeName(); 46 | if (string.IsNullOrEmpty(typeName)) 47 | { 48 | return false; 49 | } 50 | 51 | return typeCheck(typeName); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /InfuseSync/EntryPoints/UserSyncManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Linq; 5 | using System.Threading; 6 | using MediaBrowser.Controller.Dto; 7 | using MediaBrowser.Controller.Entities; 8 | using MediaBrowser.Controller.Library; 9 | using MediaBrowser.Controller.Plugins; 10 | using MediaBrowser.Model.Entities; 11 | using InfuseSync.Models; 12 | 13 | #if EMBY 14 | using InfuseSync.Logging; 15 | using ILogger = MediaBrowser.Model.Logging.ILogger; 16 | #else 17 | using System.Threading.Tasks; 18 | using Microsoft.Extensions.Hosting; 19 | using Microsoft.Extensions.Logging; 20 | using ILogger = Microsoft.Extensions.Logging.ILogger; 21 | #endif 22 | 23 | namespace InfuseSync.EntryPoints 24 | { 25 | #if EMBY 26 | public class UserSyncManager: IServerEntryPoint 27 | #else 28 | public class UserSyncManager: IHostedService 29 | #endif 30 | { 31 | private readonly ILogger _logger; 32 | private readonly IUserDataManager _userDataManager; 33 | private readonly IUserManager _userManager; 34 | 35 | private readonly object _syncLock = new object(); 36 | private Timer UpdateTimer { get; set; } 37 | private const int UpdateDuration = 500; 38 | 39 | private readonly Dictionary> _changedItems = new Dictionary>(); 40 | 41 | public UserSyncManager(IUserDataManager userDataManager, ILogger logger, IUserManager userManager) 42 | { 43 | _userDataManager = userDataManager; 44 | _logger = logger; 45 | _userManager = userManager; 46 | } 47 | 48 | public void Run() 49 | { 50 | _userDataManager.UserDataSaved += UserDataSaved; 51 | } 52 | 53 | #if JELLYFIN 54 | public Task StartAsync(CancellationToken cancellationToken) 55 | { 56 | Run(); 57 | 58 | return Task.CompletedTask; 59 | } 60 | #endif 61 | 62 | void UserDataSaved(object sender, UserDataSaveEventArgs e) 63 | { 64 | if (e.SaveReason == UserDataSaveReason.PlaybackProgress) 65 | { 66 | return; 67 | } 68 | 69 | var message = $"InfuseSync received user data for item '{e.Item.Name}' of type '{e.Item.GetClientTypeName()}' Guid '{e.Item.Id}'"; 70 | #if EMBY 71 | message += $" ItemID '{e.Item.GetClientId()}'"; 72 | #endif 73 | _logger.LogDebug(message); 74 | 75 | lock (_syncLock) 76 | { 77 | if (e.Item != null) 78 | { 79 | if (!Shared.ShouldSyncUpdatedItem(e.Item)) 80 | { 81 | return; 82 | } 83 | 84 | if (UpdateTimer == null) 85 | { 86 | UpdateTimer = new Timer( 87 | TimerCallback, 88 | null, 89 | UpdateDuration, 90 | Timeout.Infinite 91 | ); 92 | } 93 | else 94 | { 95 | UpdateTimer.Change(UpdateDuration, Timeout.Infinite); 96 | } 97 | #if EMBY 98 | var userId = e.User.Id; 99 | #else 100 | var userId = e.UserId; 101 | #endif 102 | if (!_changedItems.TryGetValue(userId, out var keys)) 103 | { 104 | keys = new List(); 105 | _changedItems[userId] = keys; 106 | } 107 | 108 | keys.Add(e.Item); 109 | 110 | _logger.LogDebug($"InfuseSync will save user data for item {e.Item.Id} user {userId}"); 111 | } 112 | } 113 | } 114 | 115 | private void TimerCallback(object state) 116 | { 117 | lock (_syncLock) 118 | try 119 | { 120 | var changes = _changedItems.ToList(); 121 | _changedItems.Clear(); 122 | 123 | SendNotifications(changes); 124 | 125 | if (UpdateTimer != null) 126 | { 127 | UpdateTimer.Dispose(); 128 | UpdateTimer = null; 129 | } 130 | } 131 | catch (Exception e) 132 | { 133 | _logger.LogError(e, $"An Error Has Occurred in TimerCallback: {e}"); 134 | } 135 | } 136 | 137 | private void SendNotifications(IEnumerable>> changes) 138 | { 139 | var options = new DtoOptions(); 140 | var infoRecs = changes 141 | .SelectMany(change => change.Value 142 | .GroupBy(i => i.Id) 143 | .Select(i => i.First()) 144 | .Select(i => { 145 | return new UserInfoRec { 146 | Guid = i.Id, 147 | #if EMBY 148 | ItemId = i.GetClientId(), 149 | #endif 150 | UserId = change.Key.ToString("N", CultureInfo.InvariantCulture), 151 | LastModified = DateTime.UtcNow.ToFileTime(), 152 | Type = i.GetClientTypeName() 153 | }; 154 | }) 155 | ).ToList(); 156 | 157 | Plugin.Instance.Db.SaveUserInfo(infoRecs); 158 | } 159 | 160 | private bool _disposed; 161 | 162 | protected virtual void Dispose(bool disposing) 163 | { 164 | if (_disposed) 165 | { 166 | return; 167 | } 168 | 169 | if (disposing) 170 | { 171 | if (UpdateTimer != null) 172 | { 173 | UpdateTimer.Dispose(); 174 | UpdateTimer = null; 175 | } 176 | 177 | _userDataManager.UserDataSaved -= UserDataSaved; 178 | } 179 | 180 | _disposed = true; 181 | } 182 | 183 | #if EMBY 184 | public void Dispose() 185 | { 186 | Dispose(true); 187 | GC.SuppressFinalize(this); 188 | } 189 | #else 190 | public Task StopAsync(CancellationToken cancellationToken) 191 | { 192 | Dispose(true); 193 | 194 | return Task.CompletedTask; 195 | } 196 | #endif 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /InfuseSync/InfuseSync.Emby.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | obj/emby 4 | bin/emby 5 | 6 | 7 | 8 | 9 | 10 | netstandard2.0 11 | 1.5.1 12 | 1.5.1 13 | InfuseSync 14 | InfuseSync 15 | EMBY 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 | -------------------------------------------------------------------------------- /InfuseSync/InfuseSync.Jellyfin.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | obj/jellyfin 4 | bin/jellyfin 5 | 6 | 7 | 8 | 9 | 10 | net8.0 11 | 1.5.1 12 | 1.5.1 13 | InfuseSync 14 | InfuseSync 15 | JELLYFIN 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 | -------------------------------------------------------------------------------- /InfuseSync/Logging/ILoggerExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using MediaBrowser.Model.Logging; 3 | 4 | namespace InfuseSync.Logging 5 | { 6 | public static class ILoggerExtensions 7 | { 8 | public static void LogInformation(this ILogger logger, string message, params object[] paramList) 9 | { 10 | logger.Info(message, paramList); 11 | } 12 | 13 | public static void LogDebug(this ILogger logger, string message, params object[] paramList) 14 | { 15 | logger.Debug(message, paramList); 16 | } 17 | 18 | public static void LogError(this ILogger logger, Exception exception, string message, params object[] args) 19 | { 20 | logger.ErrorException(message, exception, args); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /InfuseSync/Models/Checkpoint.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace InfuseSync.Models 4 | { 5 | public class Checkpoint 6 | { 7 | public Guid Guid { get; set; } 8 | public string DeviceId { get; set; } 9 | public string UserId { get; set; } 10 | public long Timestamp { get; set; } 11 | public long? SyncTimestamp { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /InfuseSync/Models/CheckpointId.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace InfuseSync.Models 4 | { 5 | public class CheckpointId 6 | { 7 | public Guid Id { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /InfuseSync/Models/ItemRec.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace InfuseSync.Models 4 | { 5 | public enum ItemStatus 6 | { 7 | Updated = 0, 8 | Removed = 1 9 | } 10 | 11 | public class ItemRec 12 | { 13 | public Guid Guid { get; set; } 14 | #if EMBY 15 | public string ItemId { get; set; } 16 | public long? SeriesId { get; set; } 17 | #else 18 | public Guid? SeriesId { get; set; } 19 | #endif 20 | public int? Season { get; set; } 21 | public ItemStatus Status { get; set; } 22 | public long LastModified { get; set; } 23 | public string Type { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /InfuseSync/Models/RemovedItem.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace InfuseSync.Models 4 | { 5 | public class RemovedItem 6 | { 7 | #if EMBY 8 | public string ItemId { get; set; } 9 | public string SeriesId { get; set; } 10 | #else 11 | public Guid ItemId { get; set; } 12 | public Guid? SeriesId { get; set; } 13 | #endif 14 | public int? Season { get; set; } 15 | } 16 | } -------------------------------------------------------------------------------- /InfuseSync/Models/SyncStats.cs: -------------------------------------------------------------------------------- 1 | namespace InfuseSync.Models 2 | { 3 | public class SyncStats 4 | { 5 | public int UpdatedFolders { get; set; } 6 | public int RemovedFolders { get; set; } 7 | public int UpdatedBoxSets { get; set; } 8 | public int RemovedBoxSets { get; set; } 9 | public int UpdatedPlaylists { get; set; } 10 | public int RemovedPlaylists { get; set; } 11 | public int UpdatedTvShows { get; set; } 12 | public int RemovedTvShows { get; set; } 13 | public int UpdatedSeasons { get; set; } 14 | public int RemovedSeasons { get; set; } 15 | public int UpdatedVideos { get; set; } 16 | public int RemovedVideos { get; set; } 17 | public int UpdatedCollectionFolders { get; set; } 18 | public int UpdatedUserData { get; set; } 19 | } 20 | } -------------------------------------------------------------------------------- /InfuseSync/Models/UserInfoRec.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace InfuseSync.Models 3 | { 4 | public class UserInfoRec 5 | { 6 | public Guid Guid { get; set; } 7 | #if EMBY 8 | public string ItemId { get; set; } 9 | #endif 10 | public string UserId { get; set; } 11 | public long LastModified { get; set; } 12 | public string Type { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /InfuseSync/Plugin.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using MediaBrowser.Common.Configuration; 4 | using MediaBrowser.Common.Plugins; 5 | using MediaBrowser.Model.Plugins; 6 | using InfuseSync.Configuration; 7 | using InfuseSync.Storage; 8 | 9 | #if EMBY 10 | using System.IO; 11 | using MediaBrowser.Common; 12 | using MediaBrowser.Controller.Plugins; 13 | using MediaBrowser.Model.Drawing; 14 | using MediaBrowser.Model.Logging; 15 | using InfuseSync.Logging; 16 | #else 17 | using MediaBrowser.Model.Serialization; 18 | using Microsoft.Extensions.Logging; 19 | using ILogger = Microsoft.Extensions.Logging.ILogger; 20 | #endif 21 | 22 | namespace InfuseSync 23 | { 24 | #if EMBY 25 | public class Plugin: BasePluginSimpleUI, IHasThumbImage 26 | #else 27 | public class Plugin: BasePlugin, IHasWebPages 28 | #endif 29 | { 30 | #if EMBY 31 | public PluginOptions Configuration 32 | { 33 | get => GetOptions(); 34 | } 35 | 36 | public Plugin(IApplicationHost applicationHost, ILogManager logManager) : base(applicationHost) 37 | { 38 | Instance = this; 39 | 40 | var logger = logManager.GetLogger(this.Name); 41 | 42 | logger.LogInformation("InfuseSync is starting."); 43 | 44 | var applicationPaths = applicationHost.Resolve(); 45 | 46 | Db = new Db(applicationPaths.DataPath, logger); 47 | } 48 | #else 49 | public Plugin( 50 | IApplicationPaths applicationPaths, 51 | IXmlSerializer xmlSerializer, 52 | ILogger logger) : base(applicationPaths, xmlSerializer) 53 | { 54 | Instance = this; 55 | 56 | logger.LogInformation("InfuseSync is starting."); 57 | 58 | Db = new Db(applicationPaths.DataPath, logger); 59 | } 60 | #endif 61 | 62 | public Db Db { get; } 63 | 64 | public override string Name => "InfuseSync"; 65 | 66 | public override string Description 67 | => "Plugin for fast synchronization with Infuse."; 68 | 69 | public override Guid Id => Guid.Parse("022a3003-993f-45f1-8565-87d12af2e12a"); 70 | 71 | public static Plugin Instance { get; private set; } 72 | 73 | #if EMBY 74 | public Stream GetThumbImage() 75 | { 76 | var type = GetType(); 77 | return type.Assembly.GetManifestResourceStream(type.Namespace + ".thumb.png"); 78 | } 79 | 80 | public ImageFormat ThumbImageFormat 81 | { 82 | get 83 | { 84 | return ImageFormat.Png; 85 | } 86 | } 87 | #endif 88 | 89 | public IEnumerable GetPages() 90 | { 91 | return new[] 92 | { 93 | new PluginPageInfo 94 | { 95 | Name = "InfuseSyncConfigPage", 96 | EmbeddedResourcePath = GetType().Namespace + ".Configuration.configPage.html" 97 | } 98 | }; 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /InfuseSync/PluginServiceRegistrator.cs: -------------------------------------------------------------------------------- 1 | using InfuseSync.EntryPoints; 2 | using MediaBrowser.Controller; 3 | using MediaBrowser.Controller.Plugins; 4 | using Microsoft.Extensions.DependencyInjection; 5 | 6 | namespace InfuseSync 7 | { 8 | public class PluginServiceRegistrator: IPluginServiceRegistrator 9 | { 10 | public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost) 11 | { 12 | serviceCollection.AddHostedService(); 13 | serviceCollection.AddHostedService(); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /InfuseSync/ScheduledTasks/HousekeepingTask.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using MediaBrowser.Model.Tasks; 6 | 7 | #if EMBY 8 | using InfuseSync.Logging; 9 | using ILogger = MediaBrowser.Model.Logging.ILogger; 10 | #else 11 | using Microsoft.Extensions.Logging; 12 | using ILogger = Microsoft.Extensions.Logging.ILogger; 13 | #endif 14 | 15 | namespace InfuseSync.ScheduledTasks 16 | { 17 | public class HousekeepingTask : IScheduledTask 18 | { 19 | private readonly ILogger _logger; 20 | 21 | public HousekeepingTask(ILogger logger) 22 | { 23 | _logger = logger; 24 | _logger.LogInformation("Infuse housekeeping task scheduled."); 25 | } 26 | 27 | public string Key => "InfuseHousekeepingTask"; 28 | 29 | public IEnumerable GetDefaultTriggers() 30 | { 31 | return new[] { 32 | new TaskTriggerInfo 33 | { 34 | Type = TaskTriggerInfo.TriggerDaily, 35 | TimeOfDayTicks = TimeSpan.FromMinutes(1).Ticks 36 | } 37 | }; 38 | } 39 | 40 | public Task Execute(CancellationToken cancellationToken, IProgress progress) 41 | { 42 | var expirationDays = Plugin.Instance.Configuration.CacheExpirationDays; 43 | if (expirationDays == 0) { 44 | return Task.CompletedTask; 45 | } 46 | 47 | var dateTime = DateTime.UtcNow.AddDays(-expirationDays); 48 | Plugin.Instance.Db.DeleteOldData(dateTime.ToFileTime()); 49 | 50 | return Task.CompletedTask; 51 | } 52 | 53 | public Task ExecuteAsync(IProgress progress, CancellationToken cancellationToken) 54 | { 55 | return Execute(cancellationToken, progress); 56 | } 57 | 58 | public string Name => "Remove Old Cached Data"; 59 | public string Category => "Infuse Sync"; 60 | public string Description => "Removes old sync records based on 'Delete unused cache data' setting."; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /InfuseSync/Storage/Db.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using MediaBrowser.Model.Serialization; 6 | using InfuseSync.Models; 7 | 8 | #if EMBY 9 | using SQLitePCL.pretty; 10 | using MediaBrowser.Model.Logging; 11 | using Statement = SQLitePCL.pretty.IStatement; 12 | #else 13 | using Microsoft.Data.Sqlite; 14 | using Microsoft.Extensions.Logging; 15 | using Statement = Microsoft.Data.Sqlite.SqliteCommand; 16 | #endif 17 | 18 | namespace InfuseSync.Storage 19 | { 20 | public class Db: BaseSqliteRepository, IDisposable 21 | { 22 | private const string CheckpointsTable = "checkpoints"; 23 | private const string ItemsTable = "items"; 24 | private const string UserInfoTable = "user_info"; 25 | 26 | public Db(string path, ILogger logger) : base(logger) 27 | { 28 | Directory.CreateDirectory(path); 29 | DbFilePath = Path.Combine(path, $"infuse_sync.db"); 30 | Initialize(File.Exists(DbFilePath)); 31 | } 32 | 33 | public void Initialize(bool fileExists) 34 | { 35 | using (var connection = CreateConnection()) 36 | { 37 | using (var versionManager = new Migrations.DbVersionManager(_logger)) 38 | { 39 | versionManager.UpdateVersion(connection, !fileExists); 40 | } 41 | 42 | RunDefaultInitialization(connection); 43 | 44 | string[] queries = { 45 | $"create table if not exists {CheckpointsTable} (Guid GUID PRIMARY KEY, DeviceId TEXT NOT NULL, UserId TEXT NOT NULL, Timestamp INTEGER NOT NULL, SyncTimestamp INTEGER NULL)", 46 | $"create index if not exists idx_{CheckpointsTable} on {CheckpointsTable}(Guid)", 47 | $"create index if not exists idx_{CheckpointsTable}_device_user on {CheckpointsTable}(DeviceId, UserId)", 48 | #if EMBY 49 | $"create table if not exists {ItemsTable} (Id TEXT PRIMARY KEY, Guid GUID NOT NULL, SeriesId INTEGER NULL, Season INTEGER NULL, Status INTEGER NOT NULL, LastModified INTEGER NOT NULL, Type TEXT NOT NULL)", 50 | $"create index if not exists idx_{ItemsTable} on {ItemsTable}(Id)", 51 | $"create table if not exists {UserInfoTable} (Id TEXT NOT NULL, Guid GUID NOT NULL, UserId TEXT NOT NULL, LastModified INTEGER NOT NULL, Type TEXT NOT NULL, PRIMARY KEY (Id, UserId))", 52 | $"create index if not exists idx_{UserInfoTable} on {UserInfoTable}(Id, UserId)" 53 | #else 54 | $"create table if not exists {ItemsTable} (Guid GUID PRIMARY KEY, SeriesId GUID NULL, Season INTEGER NULL, Status INTEGER NOT NULL, LastModified INTEGER NOT NULL, Type TEXT NOT NULL)", 55 | $"create index if not exists idx_{ItemsTable} on {ItemsTable}(Guid)", 56 | $"create table if not exists {UserInfoTable} (Guid GUID NOT NULL, UserId TEXT NOT NULL, LastModified INTEGER NOT NULL, Type TEXT NOT NULL, PRIMARY KEY (Guid, UserId))", 57 | $"create index if not exists idx_{UserInfoTable} on {UserInfoTable}(Guid, UserId)" 58 | #endif 59 | }; 60 | 61 | connection.RunQueries(queries); 62 | } 63 | } 64 | 65 | public Checkpoint GetCheckpoint(Guid checkpointId) 66 | { 67 | using (WriteLock.Read()) 68 | { 69 | using (var connection = CreateConnection(true)) 70 | { 71 | using (var statement = connection.PrepareStatement($"select * from {CheckpointsTable} where Guid=@Guid;")) 72 | { 73 | statement.TryBind("@Guid", checkpointId); 74 | foreach (var row in statement.ExecuteQuery()) 75 | { 76 | return new Checkpoint 77 | { 78 | Guid = row.GetGuid(0), 79 | DeviceId = row.GetString(1), 80 | UserId = row.GetString(2), 81 | Timestamp = row.GetInt64(3), 82 | SyncTimestamp = row.IsDBNull(4) ? null : (long?)row.GetInt64(4) 83 | }; 84 | } 85 | } 86 | 87 | return null; 88 | } 89 | } 90 | } 91 | 92 | public bool HasCheckpoints() 93 | { 94 | using (WriteLock.Read()) 95 | { 96 | using (var connection = CreateConnection(true)) 97 | { 98 | using (var statement = connection.PrepareStatement($"select exists(select 1 from {CheckpointsTable});")) 99 | { 100 | return statement.SelectScalarInt() == 1; 101 | } 102 | } 103 | } 104 | } 105 | 106 | public Checkpoint CreateCheckpoint(string deviceId, string userId) 107 | { 108 | using (WriteLock.Write()) 109 | { 110 | using (var connection = CreateConnection(true)) 111 | { 112 | return connection.RunInTransaction(db => 113 | { 114 | long timestamp; 115 | using (var statement = connection.PrepareStatement($"select max(SyncTimestamp) from {CheckpointsTable} where DeviceId=@DeviceId and UserId=@UserId;")) 116 | { 117 | statement.TryBind("@DeviceId", deviceId); 118 | statement.TryBind("@UserId", userId); 119 | 120 | timestamp = statement.SelectScalarInt64() ?? DateTime.UtcNow.ToFileTime(); 121 | } 122 | 123 | using (var statement = db.PrepareStatement($"delete from {CheckpointsTable} where DeviceId=@DeviceId and UserId=@UserId;")) 124 | { 125 | statement.TryBind("@DeviceId", deviceId); 126 | statement.TryBind("@UserId", userId); 127 | statement.ExecuteNonQuery(); 128 | } 129 | 130 | var guid = Guid.NewGuid(); 131 | 132 | using (var statement = db.PrepareStatement($"insert into {CheckpointsTable}(Guid, DeviceId, UserId, Timestamp) values (@Guid, @DeviceId, @UserId, @Timestamp);")) 133 | { 134 | statement.TryBind("@Guid", guid); 135 | statement.TryBind("@DeviceId", deviceId); 136 | statement.TryBind("@UserId", userId); 137 | statement.TryBind("@Timestamp", timestamp); 138 | statement.ExecuteNonQuery(); 139 | } 140 | 141 | return new Checkpoint 142 | { 143 | Guid = guid, 144 | DeviceId = deviceId, 145 | UserId = userId, 146 | Timestamp = timestamp, 147 | SyncTimestamp = null 148 | }; 149 | }); 150 | } 151 | } 152 | } 153 | 154 | public void UpdateCheckpoint(Guid checkpointId, long syncTimestamp) 155 | { 156 | using (WriteLock.Write()) 157 | { 158 | using (var connection = CreateConnection()) 159 | { 160 | connection.RunInTransaction(db => 161 | { 162 | using (var statement = db.PrepareStatement($"update {CheckpointsTable} set SyncTimestamp=@SyncTimestamp where Guid=@Guid;")) 163 | { 164 | statement.TryBind("@SyncTimestamp", syncTimestamp); 165 | statement.TryBind("@Guid", checkpointId); 166 | statement.ExecuteNonQuery(); 167 | } 168 | }); 169 | } 170 | } 171 | } 172 | 173 | public void RemoveCheckpoint(Guid checkpointId) 174 | { 175 | using (WriteLock.Write()) 176 | { 177 | using (var connection = CreateConnection()) 178 | { 179 | connection.RunInTransaction(db => 180 | { 181 | using (var statement = db.PrepareStatement($"delete from {CheckpointsTable} where Guid=@Guid;")) 182 | { 183 | statement.TryBind("@Guid", checkpointId); 184 | statement.ExecuteNonQuery(); 185 | } 186 | }); 187 | } 188 | } 189 | } 190 | 191 | public List GetItems( 192 | long fromTimestamp, 193 | long toTimestamp, 194 | ItemStatus status, 195 | IReadOnlyCollection itemTypes, 196 | int skip, 197 | int limit) 198 | { 199 | using (WriteLock.Read()) 200 | { 201 | using (var connection = CreateConnection(true)) 202 | { 203 | var condition = ItemsCondition(itemTypes); 204 | var sql = $"select * from {ItemsTable} where {condition} limit @Limit OFFSET @Offset;"; 205 | 206 | using (var statement = connection.PrepareStatement(sql)) 207 | { 208 | statement.TryBind("@FromTimestamp", fromTimestamp); 209 | statement.TryBind("@ToTimestamp", toTimestamp); 210 | statement.TryBind("@Status", (int)status); 211 | statement.TryBind("@Limit", limit); 212 | statement.TryBind("@Offset", skip); 213 | 214 | return GetItems(statement); 215 | } 216 | } 217 | } 218 | } 219 | 220 | private List GetItems(Statement statement) 221 | { 222 | var result = new List(); 223 | 224 | foreach (var row in statement.ExecuteQuery()) 225 | { 226 | var item = new ItemRec 227 | { 228 | #if EMBY 229 | ItemId = row.GetString(0), 230 | Guid = row.GetGuid(1), 231 | SeriesId = row.IsDBNull(2) ? null : (long?)row.GetInt64(2), 232 | Season = row.IsDBNull(3) ? null : (int?)row.GetInt(3), 233 | Status = (ItemStatus)row.GetInt(4), 234 | LastModified = row.GetInt64(5), 235 | Type = row.GetString(6) 236 | #else 237 | Guid = row.GetGuid(0), 238 | SeriesId = row.IsDBNull(1) ? null : (Guid?)row.GetGuid(1), 239 | Season = row.IsDBNull(2) ? null : (int?)row.GetInt(2), 240 | Status = (ItemStatus)row.GetInt(3), 241 | LastModified = row.GetInt64(4), 242 | Type = row.GetString(5) 243 | #endif 244 | }; 245 | result.Add(item); 246 | } 247 | 248 | return result; 249 | } 250 | 251 | public int ItemsCount( 252 | long fromTimestamp, 253 | long toTimestamp, 254 | ItemStatus status, 255 | IReadOnlyCollection itemTypes) 256 | { 257 | using (WriteLock.Read()) 258 | { 259 | using (var connection = CreateConnection(true)) 260 | { 261 | var condition = ItemsCondition(itemTypes); 262 | var sql = $"select COUNT(*) from {ItemsTable} where {condition};"; 263 | 264 | using (var statement = connection.PrepareStatement(sql)) 265 | { 266 | statement.TryBind("@FromTimestamp", fromTimestamp); 267 | statement.TryBind("@ToTimestamp", toTimestamp); 268 | statement.TryBind("@Status", (int)status); 269 | return statement.SelectScalarInt() ?? 0; 270 | } 271 | } 272 | } 273 | } 274 | 275 | private string ItemsCondition(IReadOnlyCollection itemTypes) 276 | { 277 | var condition = $"Status = @Status and LastModified between @FromTimestamp and @ToTimestamp"; 278 | if (itemTypes != null && itemTypes.Count > 0) 279 | { 280 | condition += $" and Type in ('{String.Join("','", itemTypes.ToArray())}')"; 281 | } 282 | return condition; 283 | } 284 | 285 | public List GetUserInfos( 286 | long fromTimestamp, 287 | long toTimestamp, 288 | string userId, 289 | IReadOnlyCollection itemTypes, 290 | int skip, 291 | int limit) 292 | { 293 | using (WriteLock.Read()) 294 | { 295 | using (var connection = CreateConnection(true)) 296 | { 297 | var condition = UserInfoCondition(itemTypes); 298 | var sql = $"select * from {UserInfoTable} where {condition} limit @Limit OFFSET @Offset;"; 299 | 300 | using (var statement = connection.PrepareStatement(sql)) 301 | { 302 | statement.TryBind("@FromTimestamp", fromTimestamp); 303 | statement.TryBind("@ToTimestamp", toTimestamp); 304 | statement.TryBind("@UserId", userId); 305 | statement.TryBind("@Limit", limit); 306 | statement.TryBind("@Offset", skip); 307 | 308 | return GetUserInfos(statement); 309 | } 310 | } 311 | } 312 | } 313 | 314 | private List GetUserInfos(Statement statement) 315 | { 316 | var result = new List(); 317 | 318 | foreach (var row in statement.ExecuteQuery()) 319 | { 320 | var item = new UserInfoRec 321 | { 322 | #if EMBY 323 | ItemId = row.GetString(0), 324 | Guid = row.GetGuid(1), 325 | UserId = row.GetString(2), 326 | LastModified = row.GetInt64(3), 327 | Type = row.GetString(4) 328 | #else 329 | Guid = row.GetGuid(0), 330 | UserId = row.GetString(1), 331 | LastModified = row.GetInt64(2), 332 | Type = row.GetString(3) 333 | #endif 334 | }; 335 | result.Add(item); 336 | } 337 | 338 | return result; 339 | } 340 | 341 | public int UserInfoCount( 342 | long fromTimestamp, 343 | long toTimestamp, 344 | string userId, 345 | IReadOnlyCollection itemTypes) 346 | { 347 | using (WriteLock.Read()) 348 | { 349 | using (var connection = CreateConnection(true)) 350 | { 351 | var condition = UserInfoCondition(itemTypes); 352 | var sql = $"select COUNT(*) from {UserInfoTable} where {condition};"; 353 | 354 | using (var statement = connection.PrepareStatement(sql)) 355 | { 356 | statement.TryBind("@FromTimestamp", fromTimestamp); 357 | statement.TryBind("@ToTimestamp", toTimestamp); 358 | statement.TryBind("@UserId", userId); 359 | return statement.SelectScalarInt() ?? 0; 360 | } 361 | } 362 | } 363 | } 364 | 365 | private string UserInfoCondition(IReadOnlyCollection itemTypes) 366 | { 367 | var condition = $"UserId = @UserId and LastModified between @FromTimestamp and @ToTimestamp"; 368 | if (itemTypes != null && itemTypes.Count > 0) 369 | { 370 | condition += $" and Type in ('{String.Join("','", itemTypes.ToArray())}')"; 371 | } 372 | return condition; 373 | } 374 | 375 | public void DeleteOldData(long timestamp) 376 | { 377 | using (WriteLock.Write()) 378 | { 379 | using (var connection = CreateConnection()) 380 | { 381 | connection.RunInTransaction(db => 382 | { 383 | using (var statement = db.PrepareStatement($"delete from {CheckpointsTable} where Timestamp < @Timestamp;")) 384 | { 385 | statement.TryBind("@Timestamp", timestamp); 386 | statement.ExecuteNonQuery(); 387 | } 388 | 389 | bool hasSessions; 390 | using (var statement = connection.PrepareStatement($"select exists(select 1 from {CheckpointsTable});")) 391 | { 392 | hasSessions = statement.SelectScalarInt() == 1; 393 | } 394 | 395 | if (hasSessions) 396 | { 397 | long minTimestamp; 398 | using (var statement = connection.PrepareStatement($"select MIN(Timestamp) from {CheckpointsTable};")) 399 | { 400 | minTimestamp = statement.SelectScalarInt64() ?? 0; 401 | } 402 | using (var statement = db.PrepareStatement($"delete from {ItemsTable} where LastModified < @Timestamp;")) 403 | { 404 | statement.TryBind("@Timestamp", timestamp); 405 | statement.ExecuteNonQuery(); 406 | } 407 | using (var statement = db.PrepareStatement($"delete from {UserInfoTable} where LastModified < @Timestamp;")) 408 | { 409 | statement.TryBind("@Timestamp", timestamp); 410 | statement.ExecuteNonQuery(); 411 | } 412 | } 413 | else 414 | { 415 | using (var statement = db.PrepareStatement($"delete from {ItemsTable};")) 416 | { 417 | statement.ExecuteNonQuery(); 418 | } 419 | using (var statement = db.PrepareStatement($"delete from {UserInfoTable};")) 420 | { 421 | statement.ExecuteNonQuery(); 422 | } 423 | } 424 | }); 425 | } 426 | } 427 | } 428 | 429 | public void SaveItems(IEnumerable items) 430 | { 431 | using (WriteLock.Write()) 432 | { 433 | using (var connection = CreateConnection()) 434 | { 435 | connection.RunInTransaction(db => 436 | { 437 | #if EMBY 438 | var sql = $"insert or replace into {ItemsTable} values (@Id, @Guid, @SeriesId, @Season, @Status, @LastModified, @Type);"; 439 | #else 440 | var sql = $"insert or replace into {ItemsTable} values (@Guid, @SeriesId, @Season, @Status, @LastModified, @Type);"; 441 | #endif 442 | foreach (var i in items) 443 | { 444 | using (var statement = db.PrepareStatement(sql)) 445 | { 446 | #if EMBY 447 | statement.TryBind("@Id", i.ItemId); 448 | #endif 449 | statement.TryBind("@Guid", i.Guid); 450 | statement.TryBind("@SeriesId", i.SeriesId); 451 | statement.TryBind("@Season", i.Season); 452 | statement.TryBind("@Status", (int)i.Status); 453 | statement.TryBind("@LastModified", i.LastModified); 454 | statement.TryBind("@Type", i.Type); 455 | statement.ExecuteNonQuery(); 456 | } 457 | } 458 | }); 459 | } 460 | } 461 | } 462 | 463 | public void SaveUserInfo(List infoRecs) 464 | { 465 | using (WriteLock.Write()) 466 | { 467 | using (var connection = CreateConnection()) 468 | { 469 | connection.RunInTransaction(db => 470 | { 471 | #if EMBY 472 | var sql = $"insert or replace into {UserInfoTable} values (@Id, @Guid, @UserId, @LastModified, @Type);"; 473 | #else 474 | var sql = $"insert or replace into {UserInfoTable} values (@Guid, @UserId, @LastModified, @Type);"; 475 | #endif 476 | foreach (var i in infoRecs) 477 | { 478 | using (var statement = db.PrepareStatement(sql)) 479 | { 480 | #if EMBY 481 | statement.TryBind("@Id", i.ItemId); 482 | #endif 483 | statement.TryBind("@Guid", i.Guid); 484 | statement.TryBind("@UserId", i.UserId); 485 | statement.TryBind("@LastModified", i.LastModified); 486 | statement.TryBind("@Type", i.Type); 487 | statement.ExecuteNonQuery(); 488 | } 489 | } 490 | }); 491 | } 492 | } 493 | } 494 | } 495 | } 496 | -------------------------------------------------------------------------------- /InfuseSync/Storage/Emby/BaseSqliteRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Threading; 5 | using SQLitePCL.pretty; 6 | using System.Linq; 7 | using MediaBrowser.Model.Logging; 8 | using InfuseSync.Logging; 9 | 10 | namespace InfuseSync.Storage 11 | { 12 | public abstract class BaseSqliteRepository : IDisposable 13 | { 14 | protected string DbFilePath { get; set; } 15 | protected ReaderWriterLockSlim WriteLock { get; } 16 | 17 | protected ILogger _logger { get; private set; } 18 | private static bool _versionLogged; 19 | 20 | protected BaseSqliteRepository(ILogger logger) 21 | { 22 | _logger = logger; 23 | WriteLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); 24 | } 25 | 26 | protected TransactionMode TransactionMode => TransactionMode.Deferred; 27 | 28 | protected TransactionMode ReadTransactionMode => TransactionMode.Deferred; 29 | 30 | internal static int ThreadSafeMode { get; set; } 31 | 32 | private string _defaultWal; 33 | 34 | protected IDatabaseConnection _connection; 35 | 36 | protected virtual bool EnableSingleConnection => true; 37 | 38 | protected virtual bool EnableTempStoreMemory => false; 39 | 40 | protected virtual int? CacheSize => null; 41 | 42 | protected IDatabaseConnection CreateConnection(bool isReadOnly = false) 43 | { 44 | if (_connection != null) 45 | { 46 | return _connection.Clone(false); 47 | } 48 | 49 | lock (WriteLock) 50 | { 51 | if (!_versionLogged) 52 | { 53 | _versionLogged = true; 54 | } 55 | 56 | ConnectionFlags connectionFlags; 57 | 58 | if (isReadOnly) 59 | { 60 | connectionFlags = ConnectionFlags.Create; 61 | connectionFlags |= ConnectionFlags.ReadWrite; 62 | } 63 | else 64 | { 65 | connectionFlags = ConnectionFlags.Create; 66 | connectionFlags |= ConnectionFlags.ReadWrite; 67 | } 68 | 69 | if (EnableSingleConnection) 70 | { 71 | connectionFlags |= ConnectionFlags.PrivateCache; 72 | } 73 | else 74 | { 75 | connectionFlags |= ConnectionFlags.SharedCached; 76 | } 77 | 78 | connectionFlags |= ConnectionFlags.NoMutex; 79 | 80 | var db = SQLite3.Open(DbFilePath, connectionFlags, null, false); 81 | 82 | try 83 | { 84 | if (string.IsNullOrWhiteSpace(_defaultWal)) 85 | { 86 | var query = "PRAGMA journal_mode"; 87 | 88 | using (var statement = PrepareStatement(db, query)) 89 | { 90 | foreach (var row in statement.ExecuteQuery()) 91 | { 92 | _defaultWal = row.GetString(0); 93 | break; 94 | } 95 | } 96 | } 97 | 98 | var queries = new List 99 | { 100 | "PRAGMA synchronous=Normal" 101 | }; 102 | 103 | if (CacheSize.HasValue) 104 | { 105 | queries.Add("PRAGMA cache_size=" + CacheSize.Value.ToString(CultureInfo.InvariantCulture)); 106 | } 107 | 108 | if (EnableTempStoreMemory) 109 | { 110 | queries.Add("PRAGMA temp_store = memory"); 111 | } 112 | else 113 | { 114 | queries.Add("PRAGMA temp_store = file"); 115 | } 116 | 117 | db.ExecuteAll(string.Join(";", queries.ToArray())); 118 | } 119 | catch 120 | { 121 | db.Dispose(); 122 | throw; 123 | } 124 | 125 | _connection = db; 126 | return db; 127 | } 128 | } 129 | 130 | public IStatement PrepareStatement(IDatabaseConnection connection, string sql) 131 | { 132 | return connection.PrepareStatement(sql); 133 | } 134 | 135 | public IStatement[] PrepareAll(IDatabaseConnection connection, List sql) 136 | { 137 | var length = sql.Count; 138 | var result = new IStatement[length]; 139 | 140 | for (var i = 0; i < length; i++) 141 | { 142 | result[i] = connection.PrepareStatement(sql[i]); 143 | } 144 | 145 | return result; 146 | } 147 | 148 | protected void RunDefaultInitialization(IDatabaseConnection db) 149 | { 150 | var queries = new List 151 | { 152 | "PRAGMA journal_mode=WAL", 153 | "PRAGMA page_size=4096", 154 | "PRAGMA synchronous=Normal" 155 | }; 156 | 157 | if (EnableTempStoreMemory) 158 | { 159 | queries.AddRange(new List 160 | { 161 | "pragma default_temp_store = memory", 162 | "pragma temp_store = memory" 163 | }); 164 | } 165 | else 166 | { 167 | queries.AddRange(new List 168 | { 169 | "pragma temp_store = file" 170 | }); 171 | } 172 | 173 | db.ExecuteAll(string.Join(";", queries.ToArray())); 174 | } 175 | 176 | public void Dispose() 177 | { 178 | Dispose(true); 179 | GC.SuppressFinalize(this); 180 | } 181 | 182 | private readonly object _disposeLock = new object(); 183 | private bool _disposed; 184 | 185 | protected virtual void Dispose(bool disposing) 186 | { 187 | if (_disposed) 188 | { 189 | return; 190 | } 191 | 192 | if (disposing) 193 | { 194 | DisposeConnection(); 195 | } 196 | 197 | _disposed = true; 198 | } 199 | 200 | private void DisposeConnection() 201 | { 202 | try 203 | { 204 | lock (_disposeLock) 205 | { 206 | using (WriteLock.Write()) 207 | { 208 | _connection?.Dispose(); 209 | } 210 | } 211 | } 212 | catch (Exception ex) 213 | { 214 | _logger.LogError(ex, $"Error disposing database: {ex}"); 215 | } 216 | } 217 | 218 | protected List GetColumnNames(IDatabaseConnection connection, string table) 219 | { 220 | var list = new List(); 221 | 222 | using (var statement = PrepareStatement(connection, "PRAGMA table_info(" + table + ")")) 223 | { 224 | foreach (var row in statement.ExecuteQuery()) 225 | { 226 | if (!row.IsDBNull(1)) 227 | { 228 | var name = row.GetString(1); 229 | 230 | list.Add(name); 231 | } 232 | } 233 | } 234 | 235 | return list; 236 | } 237 | 238 | protected bool AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List existingColumnNames) 239 | { 240 | if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase)) 241 | { 242 | return false; 243 | } 244 | 245 | connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL"); 246 | return true; 247 | } 248 | } 249 | } 250 | -------------------------------------------------------------------------------- /InfuseSync/Storage/Emby/SqliteExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using SQLitePCL.pretty; 4 | 5 | #if EMBY 6 | using ResultSet = SQLitePCL.pretty.IResultSet; 7 | #else 8 | using ResultSet = System.Collections.Generic.IReadOnlyList; 9 | #endif 10 | 11 | namespace InfuseSync.Storage 12 | { 13 | public static class SqliteExtensions 14 | { 15 | private static readonly string[] _datetimeFormats = new string[] { 16 | "THHmmssK", 17 | "THHmmK", 18 | "HH:mm:ss.FFFFFFFK", 19 | "HH:mm:ssK", 20 | "HH:mmK", 21 | "yyyy-MM-dd HH:mm:ss.FFFFFFFK", /* NOTE: UTC default (5). */ 22 | "yyyy-MM-dd HH:mm:ssK", 23 | "yyyy-MM-dd HH:mmK", 24 | "yyyy-MM-ddTHH:mm:ss.FFFFFFFK", 25 | "yyyy-MM-ddTHH:mmK", 26 | "yyyy-MM-ddTHH:mm:ssK", 27 | "yyyyMMddHHmmssK", 28 | "yyyyMMddHHmmK", 29 | "yyyyMMddTHHmmssFFFFFFFK", 30 | "THHmmss", 31 | "THHmm", 32 | "HH:mm:ss.FFFFFFF", 33 | "HH:mm:ss", 34 | "HH:mm", 35 | "yyyy-MM-dd HH:mm:ss.FFFFFFF", /* NOTE: Non-UTC default (19). */ 36 | "yyyy-MM-dd HH:mm:ss", 37 | "yyyy-MM-dd HH:mm", 38 | "yyyy-MM-ddTHH:mm:ss.FFFFFFF", 39 | "yyyy-MM-ddTHH:mm", 40 | "yyyy-MM-ddTHH:mm:ss", 41 | "yyyyMMddHHmmss", 42 | "yyyyMMddHHmm", 43 | "yyyyMMddTHHmmssFFFFFFF", 44 | "yyyy-MM-dd", 45 | "yyyyMMdd", 46 | "yy-MM-dd" 47 | }; 48 | 49 | private static string _datetimeFormatUtc = _datetimeFormats[5]; 50 | private static string _datetimeFormatLocal = _datetimeFormats[19]; 51 | 52 | public static void RunQueries(this IDatabaseConnection connection, string[] queries) 53 | { 54 | connection.RunInTransaction(conn => 55 | { 56 | conn.ExecuteAll(string.Join(";", queries)); 57 | }, TransactionMode.Deferred); 58 | } 59 | 60 | public static T RunInTransaction(this IDatabaseConnection This, Func f) 61 | { 62 | return This.RunInTransaction(f, TransactionMode.Deferred); 63 | } 64 | 65 | public static bool TableExists(this IDatabaseConnection connection, string tableName) 66 | { 67 | using (var statement = connection.PrepareStatement($"select 1 from sqlite_master where tbl_name = '{tableName}'")) 68 | { 69 | return statement.MoveNext(); 70 | } 71 | } 72 | 73 | public static ReadOnlySpan ToGuidBlob(this Guid guid) 74 | { 75 | return guid.ToByteArray().AsSpan(); 76 | } 77 | 78 | public static Guid GetGuid(this ResultSet result, int index) 79 | { 80 | #if EMBY 81 | #if NETCOREAPP 82 | return new Guid(result.GetBlob(index)); 83 | #else 84 | return new Guid(result.GetBlob(index).ToArray()); 85 | #endif 86 | #else 87 | return new Guid(result[index].ToBlob().ToArray()); 88 | #endif 89 | } 90 | 91 | #if JELLYFIN 92 | public static bool IsDBNull(this ResultSet result, int index) 93 | { 94 | return result[index].SQLiteType == SQLiteType.Null; 95 | } 96 | 97 | public static string GetString(this ResultSet result, int index) 98 | { 99 | return result[index].ToString(); 100 | } 101 | 102 | public static bool GetBoolean(this ResultSet result, int index) 103 | { 104 | return result[index].ToBool(); 105 | } 106 | 107 | public static int GetInt(this ResultSet result, int index) 108 | { 109 | return result[index].ToInt(); 110 | } 111 | 112 | public static long GetInt64(this ResultSet result, int index) 113 | { 114 | return result[index].ToInt64(); 115 | } 116 | 117 | public static float GetFloat(this ResultSet result, int index) 118 | { 119 | return result[index].ToFloat(); 120 | } 121 | #endif 122 | 123 | private static void ThrowInvalidParamName(IStatement statement, string name) 124 | { 125 | #if DEBUG 126 | throw new Exception("Invalid param name: " + name + ". SQL: " + statement.SQL); 127 | #endif 128 | } 129 | 130 | public static void TryBind(this IStatement statement, int index, double value) 131 | { 132 | IBindParameter bindParam = statement.BindParameters[index]; 133 | bindParam.Bind(value); 134 | } 135 | 136 | public static void TryBind(this IStatement statement, string name, double value) 137 | { 138 | IBindParameter bindParam; 139 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 140 | { 141 | bindParam.Bind(value); 142 | } 143 | else 144 | { 145 | ThrowInvalidParamName(statement, name); 146 | } 147 | } 148 | 149 | public static void TryBind(this IStatement statement, string name, string value) 150 | { 151 | IBindParameter bindParam; 152 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 153 | { 154 | if (value == null) 155 | { 156 | bindParam.BindNull(); 157 | } 158 | else 159 | { 160 | #if EMBY 161 | bindParam.Bind(value.AsSpan()); 162 | #else 163 | bindParam.Bind(value); 164 | #endif 165 | } 166 | } 167 | else 168 | { 169 | ThrowInvalidParamName(statement, name); 170 | } 171 | } 172 | 173 | public static void TryBind(this IStatement statement, int index, string value) 174 | { 175 | IBindParameter bindParam = statement.BindParameters[index]; 176 | if (value == null) 177 | { 178 | bindParam.BindNull(); 179 | } 180 | else 181 | { 182 | #if EMBY 183 | bindParam.Bind(value.AsSpan()); 184 | #else 185 | bindParam.Bind(value); 186 | #endif 187 | } 188 | } 189 | 190 | public static void TryBind(this IStatement statement, int index, bool value) 191 | { 192 | IBindParameter bindParam = statement.BindParameters[index]; 193 | bindParam.Bind(value); 194 | } 195 | 196 | public static void TryBind(this IStatement statement, int index, bool? value) 197 | { 198 | IBindParameter bindParam = statement.BindParameters[index]; 199 | if (value == null) 200 | { 201 | bindParam.BindNull(); 202 | } 203 | else 204 | { 205 | bindParam.Bind(value.Value); 206 | } 207 | } 208 | 209 | public static void TryBind(this IStatement statement, string name, bool value) 210 | { 211 | IBindParameter bindParam; 212 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 213 | { 214 | bindParam.Bind(value); 215 | } 216 | else 217 | { 218 | ThrowInvalidParamName(statement, name); 219 | } 220 | } 221 | 222 | public static void TryBind(this IStatement statement, int index, int value) 223 | { 224 | IBindParameter bindParam = statement.BindParameters[index]; 225 | bindParam.Bind(value); 226 | } 227 | 228 | public static void TryBind(this IStatement statement, string name, int value) 229 | { 230 | IBindParameter bindParam; 231 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 232 | { 233 | bindParam.Bind(value); 234 | } 235 | else 236 | { 237 | ThrowInvalidParamName(statement, name); 238 | } 239 | } 240 | 241 | public static void TryBind(this IStatement statement, string name, int? value) 242 | { 243 | IBindParameter bindParam; 244 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 245 | { 246 | if (value == null) 247 | { 248 | bindParam.BindNull(); 249 | } 250 | else 251 | { 252 | bindParam.Bind(value.Value); 253 | } 254 | } 255 | else 256 | { 257 | ThrowInvalidParamName(statement, name); 258 | } 259 | } 260 | 261 | public static void TryBind(this IStatement statement, int index, Guid value) 262 | { 263 | IBindParameter bindParam = statement.BindParameters[index]; 264 | bindParam.Bind(value.ToGuidBlob()); 265 | } 266 | 267 | public static void TryBind(this IStatement statement, string name, Guid value) 268 | { 269 | IBindParameter bindParam; 270 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 271 | { 272 | bindParam.Bind(value.ToGuidBlob()); 273 | } 274 | else 275 | { 276 | ThrowInvalidParamName(statement, name); 277 | } 278 | } 279 | 280 | public static void TryBind(this IStatement statement, string name, Guid? value) 281 | { 282 | if (value.HasValue) 283 | { 284 | TryBind(statement, name, value.Value); 285 | } 286 | else 287 | { 288 | TryBindNull(statement, name); 289 | } 290 | } 291 | 292 | public static void TryBind(this IStatement statement, string name, ReadOnlySpan value) 293 | { 294 | IBindParameter bindParam; 295 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 296 | { 297 | bindParam.Bind(value); 298 | } 299 | else 300 | { 301 | ThrowInvalidParamName(statement, name); 302 | } 303 | } 304 | 305 | public static void TryBind(this IStatement statement, int index, DateTimeOffset? value) 306 | { 307 | if (value.HasValue) 308 | { 309 | TryBind(statement, index, value.Value); 310 | } 311 | else 312 | { 313 | TryBindNull(statement, index); 314 | } 315 | } 316 | 317 | public static void TryBind(this IStatement statement, int index, DateTimeOffset value, bool enableMsPrecision) 318 | { 319 | IBindParameter bindParam = statement.BindParameters[index]; 320 | 321 | if (enableMsPrecision) 322 | { 323 | bindParam.Bind(value.ToUnixTimeMilliseconds()); 324 | } 325 | else 326 | { 327 | bindParam.Bind(value.ToUnixTimeSeconds()); 328 | } 329 | } 330 | 331 | public static void TryBind(this IStatement statement, string name, DateTimeOffset value, bool enableMsPrecision) 332 | { 333 | IBindParameter bindParam; 334 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 335 | { 336 | if (enableMsPrecision) 337 | { 338 | bindParam.Bind(value.ToUnixTimeMilliseconds()); 339 | } 340 | else 341 | { 342 | bindParam.Bind(value.ToUnixTimeSeconds()); 343 | } 344 | } 345 | else 346 | { 347 | ThrowInvalidParamName(statement, name); 348 | } 349 | } 350 | 351 | public static void TryBind(this IStatement statement, int index, DateTimeOffset value) 352 | { 353 | TryBind(statement, index, value, false); 354 | } 355 | 356 | public static void TryBind(this IStatement statement, string name, DateTimeOffset value) 357 | { 358 | TryBind(statement, name, value, false); 359 | } 360 | 361 | public static void TryBind(this IStatement statement, int index, long value) 362 | { 363 | IBindParameter bindParam = statement.BindParameters[index]; 364 | 365 | bindParam.Bind(value); 366 | } 367 | 368 | public static void TryBind(this IStatement statement, string name, long value) 369 | { 370 | IBindParameter bindParam; 371 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 372 | { 373 | bindParam.Bind(value); 374 | } 375 | else 376 | { 377 | ThrowInvalidParamName(statement, name); 378 | } 379 | } 380 | 381 | public static void TryBind(this IStatement statement, string name, long? value) 382 | { 383 | IBindParameter bindParam; 384 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 385 | { 386 | if (value == null) 387 | { 388 | bindParam.BindNull(); 389 | } 390 | else 391 | { 392 | bindParam.Bind(value.Value); 393 | } 394 | } 395 | else 396 | { 397 | ThrowInvalidParamName(statement, name); 398 | } 399 | } 400 | 401 | public static void TryBind(this IStatement statement, int index, ReadOnlySpan value) 402 | { 403 | IBindParameter bindParam = statement.BindParameters[index]; 404 | bindParam.Bind(value); 405 | } 406 | 407 | public static void TryBindNull(this IStatement statement, int index) 408 | { 409 | IBindParameter bindParam = statement.BindParameters[index]; 410 | 411 | bindParam.BindNull(); 412 | } 413 | 414 | public static void TryBindNull(this IStatement statement, string name) 415 | { 416 | IBindParameter bindParam; 417 | if (statement.BindParameters.TryGetValue(name, out bindParam)) 418 | { 419 | bindParam.BindNull(); 420 | } 421 | else 422 | { 423 | ThrowInvalidParamName(statement, name); 424 | } 425 | } 426 | 427 | public static void TryBind(this IStatement statement, int index, double? value) 428 | { 429 | if (value.HasValue) 430 | { 431 | TryBind(statement, index, value.Value); 432 | } 433 | else 434 | { 435 | TryBindNull(statement, index); 436 | } 437 | } 438 | 439 | public static void TryBind(this IStatement statement, int index, int? value) 440 | { 441 | if (value.HasValue) 442 | { 443 | TryBind(statement, index, value.Value); 444 | } 445 | else 446 | { 447 | TryBindNull(statement, index); 448 | } 449 | } 450 | 451 | public static void TryBind(this IStatement statement, string name, bool? value) 452 | { 453 | if (value.HasValue) 454 | { 455 | TryBind(statement, name, value.Value); 456 | } 457 | else 458 | { 459 | TryBindNull(statement, name); 460 | } 461 | } 462 | 463 | public static IEnumerable ExecuteQuery(this IStatement statement) 464 | { 465 | while (statement.MoveNext()) 466 | { 467 | yield return statement.Current; 468 | } 469 | } 470 | 471 | public static void ExecuteNonQuery(this IStatement statement) 472 | { 473 | statement.MoveNext(); 474 | } 475 | 476 | public static int? SelectScalarInt(this IStatement statement) 477 | { 478 | if (statement.MoveNext() && !statement.Current.IsDBNull(0)) 479 | { 480 | return statement.Current.GetInt(0); 481 | } 482 | 483 | return null; 484 | } 485 | 486 | public static long? SelectScalarInt64(this IStatement statement) 487 | { 488 | if (statement.MoveNext() && !statement.Current.IsDBNull(0)) 489 | { 490 | return statement.Current.GetInt64(0); 491 | } 492 | 493 | return null; 494 | } 495 | } 496 | } 497 | -------------------------------------------------------------------------------- /InfuseSync/Storage/Jellyfin/BaseSqliteRepository.cs: -------------------------------------------------------------------------------- 1 | #nullable disable 2 | 3 | #pragma warning disable CS1591 4 | 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Threading; 8 | using Jellyfin.Extensions; 9 | using Microsoft.Data.Sqlite; 10 | using Microsoft.Extensions.Logging; 11 | 12 | namespace InfuseSync.Storage 13 | { 14 | public abstract class BaseSqliteRepository : IDisposable 15 | { 16 | private bool _disposed = false; 17 | 18 | protected ReaderWriterLockSlim WriteLock { get; } 19 | 20 | protected BaseSqliteRepository(ILogger logger) 21 | { 22 | _logger = logger; 23 | 24 | WriteLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); 25 | } 26 | 27 | protected string DbFilePath { get; set; } 28 | 29 | protected ILogger _logger { get; private set; } 30 | 31 | protected virtual int? CacheSize => null; 32 | 33 | protected virtual string LockingMode => "NORMAL"; 34 | 35 | protected virtual string JournalMode => "WAL"; 36 | 37 | protected virtual int? JournalSizeLimit => 134_217_728; // 128MiB 38 | 39 | protected virtual int? PageSize => null; 40 | 41 | protected virtual TempStoreMode TempStore => TempStoreMode.Memory; 42 | 43 | protected virtual SynchronousMode? Synchronous => SynchronousMode.Normal; 44 | 45 | public virtual void Initialize() 46 | { 47 | // Configuration and pragmas can affect VACUUM so it needs to be last. 48 | using (var connection = CreateConnection()) 49 | { 50 | connection.Execute("VACUUM"); 51 | } 52 | } 53 | 54 | protected SqliteConnection CreateConnection(bool isReadOnly = false) 55 | { 56 | var connection = new SqliteConnection($"Filename={DbFilePath}"); 57 | connection.Open(); 58 | 59 | if (CacheSize.HasValue) 60 | { 61 | connection.Execute("PRAGMA cache_size=" + CacheSize.Value); 62 | } 63 | 64 | if (!string.IsNullOrWhiteSpace(LockingMode)) 65 | { 66 | connection.Execute("PRAGMA locking_mode=" + LockingMode); 67 | } 68 | 69 | if (!string.IsNullOrWhiteSpace(JournalMode)) 70 | { 71 | connection.Execute("PRAGMA journal_mode=" + JournalMode); 72 | } 73 | 74 | if (JournalSizeLimit.HasValue) 75 | { 76 | connection.Execute("PRAGMA journal_size_limit=" + JournalSizeLimit.Value); 77 | } 78 | 79 | if (Synchronous.HasValue) 80 | { 81 | connection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value); 82 | } 83 | 84 | if (PageSize.HasValue) 85 | { 86 | connection.Execute("PRAGMA page_size=" + PageSize.Value); 87 | } 88 | 89 | connection.Execute("PRAGMA temp_store=" + (int)TempStore); 90 | 91 | return connection; 92 | } 93 | 94 | protected void RunDefaultInitialization(SqliteConnection connection) 95 | { 96 | } 97 | 98 | public SqliteCommand PrepareStatement(SqliteConnection connection, string sql) 99 | { 100 | var command = connection.CreateCommand(); 101 | command.CommandText = sql; 102 | return command; 103 | } 104 | 105 | protected bool TableExists(SqliteConnection connection, string name) 106 | { 107 | using var statement = PrepareStatement(connection, "select DISTINCT tbl_name from sqlite_master"); 108 | foreach (var row in statement.ExecuteQuery()) 109 | { 110 | if (string.Equals(name, row.GetString(0), StringComparison.OrdinalIgnoreCase)) 111 | { 112 | return true; 113 | } 114 | } 115 | 116 | return false; 117 | } 118 | 119 | protected List GetColumnNames(SqliteConnection connection, string table) 120 | { 121 | var columnNames = new List(); 122 | 123 | foreach (var row in connection.Query("PRAGMA table_info(" + table + ")")) 124 | { 125 | if (row.TryGetString(1, out var columnName)) 126 | { 127 | columnNames.Add(columnName); 128 | } 129 | } 130 | 131 | return columnNames; 132 | } 133 | 134 | protected void AddColumn(SqliteConnection connection, string table, string columnName, string type, List existingColumnNames) 135 | { 136 | if (existingColumnNames.Contains(columnName, StringComparison.OrdinalIgnoreCase)) 137 | { 138 | return; 139 | } 140 | 141 | connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL"); 142 | } 143 | 144 | protected void CheckDisposed() 145 | { 146 | ObjectDisposedException.ThrowIf(_disposed, this); 147 | } 148 | 149 | public void Dispose() 150 | { 151 | Dispose(true); 152 | GC.SuppressFinalize(this); 153 | } 154 | 155 | protected virtual void Dispose(bool dispose) 156 | { 157 | if (_disposed) 158 | { 159 | return; 160 | } 161 | 162 | _disposed = true; 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /InfuseSync/Storage/Jellyfin/SqliteExtensions.cs: -------------------------------------------------------------------------------- 1 | #pragma warning disable CS1591 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Data; 6 | using System.Globalization; 7 | using Microsoft.Data.Sqlite; 8 | 9 | namespace InfuseSync.Storage 10 | { 11 | public static class SqliteExtensions 12 | { 13 | private const string DatetimeFormatUtc = "yyyy-MM-dd HH:mm:ss.FFFFFFFK"; 14 | private const string DatetimeFormatLocal = "yyyy-MM-dd HH:mm:ss.FFFFFFF"; 15 | 16 | /// 17 | /// An array of ISO-8601 DateTime formats that we support parsing. 18 | /// 19 | private static readonly string[] _datetimeFormats = new string[] 20 | { 21 | "THHmmssK", 22 | "THHmmK", 23 | "HH:mm:ss.FFFFFFFK", 24 | "HH:mm:ssK", 25 | "HH:mmK", 26 | DatetimeFormatUtc, 27 | "yyyy-MM-dd HH:mm:ssK", 28 | "yyyy-MM-dd HH:mmK", 29 | "yyyy-MM-ddTHH:mm:ss.FFFFFFFK", 30 | "yyyy-MM-ddTHH:mmK", 31 | "yyyy-MM-ddTHH:mm:ssK", 32 | "yyyyMMddHHmmssK", 33 | "yyyyMMddHHmmK", 34 | "yyyyMMddTHHmmssFFFFFFFK", 35 | "THHmmss", 36 | "THHmm", 37 | "HH:mm:ss.FFFFFFF", 38 | "HH:mm:ss", 39 | "HH:mm", 40 | DatetimeFormatLocal, 41 | "yyyy-MM-dd HH:mm:ss", 42 | "yyyy-MM-dd HH:mm", 43 | "yyyy-MM-ddTHH:mm:ss.FFFFFFF", 44 | "yyyy-MM-ddTHH:mm", 45 | "yyyy-MM-ddTHH:mm:ss", 46 | "yyyyMMddHHmmss", 47 | "yyyyMMddHHmm", 48 | "yyyyMMddTHHmmssFFFFFFF", 49 | "yyyy-MM-dd", 50 | "yyyyMMdd", 51 | "yy-MM-dd" 52 | }; 53 | 54 | public static IEnumerable Query(this SqliteConnection sqliteConnection, string commandText) 55 | { 56 | if (sqliteConnection.State != ConnectionState.Open) 57 | { 58 | sqliteConnection.Open(); 59 | } 60 | 61 | using var command = sqliteConnection.CreateCommand(); 62 | command.CommandText = commandText; 63 | using (var reader = command.ExecuteReader()) 64 | { 65 | while (reader.Read()) 66 | { 67 | yield return reader; 68 | } 69 | } 70 | } 71 | 72 | public static void Execute(this SqliteConnection sqliteConnection, string commandText) 73 | { 74 | using var command = sqliteConnection.CreateCommand(); 75 | command.CommandText = commandText; 76 | command.ExecuteNonQuery(); 77 | } 78 | 79 | public static void RunQueries(this SqliteConnection connection, string[] queries) 80 | { 81 | connection.RunInTransaction(conn => 82 | { 83 | foreach (var querie in queries) 84 | { 85 | conn.Execute(querie); 86 | } 87 | }); 88 | } 89 | 90 | public static string ToDateTimeParamValue(this DateTime dateValue) 91 | { 92 | var kind = DateTimeKind.Utc; 93 | 94 | return (dateValue.Kind == DateTimeKind.Unspecified) 95 | ? DateTime.SpecifyKind(dateValue, kind).ToString( 96 | GetDateTimeKindFormat(kind), 97 | CultureInfo.InvariantCulture) 98 | : dateValue.ToString( 99 | GetDateTimeKindFormat(dateValue.Kind), 100 | CultureInfo.InvariantCulture); 101 | } 102 | 103 | private static string GetDateTimeKindFormat(DateTimeKind kind) 104 | => (kind == DateTimeKind.Utc) ? DatetimeFormatUtc : DatetimeFormatLocal; 105 | 106 | public static bool TryReadDateTime(this SqliteDataReader reader, int index, out DateTime result) 107 | { 108 | if (reader.IsDBNull(index)) 109 | { 110 | result = default; 111 | return false; 112 | } 113 | 114 | var dateText = reader.GetString(index); 115 | 116 | if (DateTime.TryParseExact(dateText, _datetimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out var dateTimeResult)) 117 | { 118 | // If the resulting DateTimeKind is Unspecified it is actually Utc. 119 | // This is required downstream for the Json serializer. 120 | if (dateTimeResult.Kind == DateTimeKind.Unspecified) 121 | { 122 | dateTimeResult = DateTime.SpecifyKind(dateTimeResult, DateTimeKind.Utc); 123 | } 124 | 125 | result = dateTimeResult; 126 | return true; 127 | } 128 | 129 | result = default; 130 | return false; 131 | } 132 | 133 | public static bool TryGetGuid(this SqliteDataReader reader, int index, out Guid result) 134 | { 135 | if (reader.IsDBNull(index)) 136 | { 137 | result = default; 138 | return false; 139 | } 140 | 141 | result = reader.GetGuid(index); 142 | return true; 143 | } 144 | 145 | public static bool TryGetString(this SqliteDataReader reader, int index, out string result) 146 | { 147 | result = string.Empty; 148 | 149 | if (reader.IsDBNull(index)) 150 | { 151 | return false; 152 | } 153 | 154 | result = reader.GetString(index); 155 | return true; 156 | } 157 | 158 | public static bool TryGetBoolean(this SqliteDataReader reader, int index, out bool result) 159 | { 160 | if (reader.IsDBNull(index)) 161 | { 162 | result = default; 163 | return false; 164 | } 165 | 166 | result = reader.GetBoolean(index); 167 | return true; 168 | } 169 | 170 | public static int GetInt(this SqliteDataReader reader, int index) 171 | { 172 | return reader.GetInt32(index); 173 | } 174 | 175 | public static bool TryGetInt32(this SqliteDataReader reader, int index, out int result) 176 | { 177 | if (reader.IsDBNull(index)) 178 | { 179 | result = default; 180 | return false; 181 | } 182 | 183 | result = reader.GetInt32(index); 184 | return true; 185 | } 186 | 187 | public static bool TryGetInt64(this SqliteDataReader reader, int index, out long result) 188 | { 189 | if (reader.IsDBNull(index)) 190 | { 191 | result = default; 192 | return false; 193 | } 194 | 195 | result = reader.GetInt64(index); 196 | return true; 197 | } 198 | 199 | public static bool TryGetSingle(this SqliteDataReader reader, int index, out float result) 200 | { 201 | if (reader.IsDBNull(index)) 202 | { 203 | result = default; 204 | return false; 205 | } 206 | 207 | result = reader.GetFloat(index); 208 | return true; 209 | } 210 | 211 | public static bool TryGetDouble(this SqliteDataReader reader, int index, out double result) 212 | { 213 | if (reader.IsDBNull(index)) 214 | { 215 | result = default; 216 | return false; 217 | } 218 | 219 | result = reader.GetDouble(index); 220 | return true; 221 | } 222 | 223 | public static void TryBind(this SqliteCommand statement, string name, Guid value) 224 | { 225 | statement.TryBind(name, value, true); 226 | } 227 | 228 | public static void TryBind(this SqliteCommand statement, string name, object value, bool isBlob = false) 229 | { 230 | var preparedValue = value ?? DBNull.Value; 231 | if (statement.Parameters.Contains(name)) 232 | { 233 | statement.Parameters[name].Value = preparedValue; 234 | } 235 | else 236 | { 237 | // Blobs aren't always detected automatically 238 | if (isBlob) 239 | { 240 | statement.Parameters.Add(new SqliteParameter(name, SqliteType.Blob) { Value = value }); 241 | } 242 | else 243 | { 244 | statement.Parameters.AddWithValue(name, preparedValue); 245 | } 246 | } 247 | } 248 | 249 | public static void TryBindNull(this SqliteCommand statement, string name) 250 | { 251 | statement.TryBind(name, DBNull.Value); 252 | } 253 | 254 | public static IEnumerable ExecuteQuery(this SqliteCommand command) 255 | { 256 | using (var reader = command.ExecuteReader()) 257 | { 258 | while (reader.Read()) 259 | { 260 | yield return reader; 261 | } 262 | } 263 | } 264 | 265 | public static int? SelectScalarInt(this SqliteCommand command) 266 | { 267 | var result = command.ExecuteScalar(); 268 | if (result == null || result == DBNull.Value) 269 | { 270 | return null; 271 | } 272 | return Convert.ToInt32(result, CultureInfo.InvariantCulture); 273 | 274 | } 275 | 276 | public static long? SelectScalarInt64(this SqliteCommand command) 277 | { 278 | var result = command.ExecuteScalar(); 279 | if (result == null || result == DBNull.Value) 280 | { 281 | return null; 282 | } 283 | return Convert.ToInt64(result, CultureInfo.InvariantCulture); 284 | } 285 | 286 | public static SqliteCommand PrepareStatement(this SqliteConnection sqliteConnection, string sql) 287 | { 288 | var command = sqliteConnection.CreateCommand(); 289 | command.CommandText = sql; 290 | return command; 291 | } 292 | 293 | public static void RunInTransaction(this SqliteConnection This, Action action) 294 | { 295 | This.RunInTransaction((Func)delegate (SqliteConnection connection) 296 | { 297 | action(connection); 298 | return null; 299 | }); 300 | } 301 | 302 | public static T RunInTransaction(this SqliteConnection This, Func f) 303 | { 304 | var transaction = This.BeginTransaction(); 305 | try 306 | { 307 | T result = f(This); 308 | transaction.Commit(); 309 | return result; 310 | } 311 | catch (Exception) 312 | { 313 | transaction.Rollback(); 314 | throw; 315 | } 316 | } 317 | 318 | public static bool TableExists(this SqliteConnection This, string name) 319 | { 320 | using var statement = This.PrepareStatement("select DISTINCT tbl_name from sqlite_master"); 321 | foreach (var row in statement.ExecuteQuery()) 322 | { 323 | if (string.Equals(name, row.GetString(0), StringComparison.OrdinalIgnoreCase)) 324 | { 325 | return true; 326 | } 327 | } 328 | 329 | return false; 330 | } 331 | } 332 | } 333 | -------------------------------------------------------------------------------- /InfuseSync/Storage/Jellyfin/SynchronousMode.cs: -------------------------------------------------------------------------------- 1 | namespace InfuseSync.Storage; 2 | 3 | /// 4 | /// The disk synchronization mode, controls how aggressively SQLite will write data 5 | /// all the way out to physical storage. 6 | /// 7 | public enum SynchronousMode 8 | { 9 | /// 10 | /// SQLite continues without syncing as soon as it has handed data off to the operating system. 11 | /// 12 | Off = 0, 13 | 14 | /// 15 | /// SQLite database engine will still sync at the most critical moments. 16 | /// 17 | Normal = 1, 18 | 19 | /// 20 | /// SQLite database engine will use the xSync method of the VFS 21 | /// to ensure that all content is safely written to the disk surface prior to continuing. 22 | /// 23 | Full = 2, 24 | 25 | /// 26 | /// EXTRA synchronous is like FULL with the addition that the directory containing a rollback journal 27 | /// is synced after that journal is unlinked to commit a transaction in DELETE mode. 28 | /// 29 | Extra = 3 30 | } 31 | -------------------------------------------------------------------------------- /InfuseSync/Storage/Jellyfin/TempStoreMode.cs: -------------------------------------------------------------------------------- 1 | namespace InfuseSync.Storage; 2 | 3 | /// 4 | /// Storage mode used by temporary database files. 5 | /// 6 | public enum TempStoreMode 7 | { 8 | /// 9 | /// The compile-time C preprocessor macro SQLITE_TEMP_STORE 10 | /// is used to determine where temporary tables and indices are stored. 11 | /// 12 | Default = 0, 13 | 14 | /// 15 | /// Temporary tables and indices are stored in a file. 16 | /// 17 | File = 1, 18 | 19 | /// 20 | /// Temporary tables and indices are kept in as if they were pure in-memory databases memory. 21 | /// 22 | Memory = 2 23 | } 24 | -------------------------------------------------------------------------------- /InfuseSync/Storage/Migrations/DbVersionManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | #if EMBY 6 | using MediaBrowser.Model.Logging; 7 | using InfuseSync.Logging; 8 | using SQLitePCL.pretty; 9 | using DatabaseConnection = SQLitePCL.pretty.IDatabaseConnection; 10 | #else 11 | using Microsoft.Extensions.Logging; 12 | using Microsoft.Data.Sqlite; 13 | using DatabaseConnection = Microsoft.Data.Sqlite.SqliteConnection; 14 | #endif 15 | 16 | namespace InfuseSync.Storage.Migrations 17 | { 18 | public class DbVersionManager: IDisposable 19 | { 20 | private const int DbVersion = 2; 21 | 22 | public readonly Dictionary migrations; 23 | 24 | private readonly ILogger _logger; 25 | 26 | public DbVersionManager(ILogger logger) 27 | { 28 | _logger = logger; 29 | 30 | migrations = new IDbMigration[] { 31 | new MigrationDropBetaDatabase(), 32 | new MigrationChangeUserDataPrimaryKey() 33 | } 34 | .ToDictionary(m => m.DbVersion, m => m); 35 | } 36 | 37 | public void UpdateVersion(DatabaseConnection connection, bool dbJustCreated) 38 | { 39 | if (dbJustCreated) 40 | { 41 | connection.Execute($"PRAGMA user_version = {DbVersion};"); 42 | return; 43 | } 44 | 45 | int version; 46 | using (var versionStatement = connection.PrepareStatement("PRAGMA user_version;")) 47 | { 48 | var userVersion = versionStatement.SelectScalarInt(); 49 | if (userVersion == null) 50 | { 51 | connection.Execute($"PRAGMA user_version = {DbVersion};"); 52 | } 53 | version = userVersion ?? DbVersion; 54 | } 55 | 56 | if (version >= DbVersion) 57 | { 58 | return; 59 | } 60 | 61 | _logger.LogInformation($"InfuseSync: DB version {version} is outdated. Will migrate to version {DbVersion}."); 62 | 63 | for (var migrateVersion = version; migrateVersion < DbVersion; ++migrateVersion) 64 | { 65 | var migration = migrations[migrateVersion]; 66 | if (migration != null) 67 | { 68 | _logger.LogInformation($"InfuseSync: Performing migration for DB version {migrateVersion}."); 69 | migration.Migrate(connection); 70 | } 71 | else 72 | { 73 | _logger.LogInformation($"InfuseSync: Migration not found for DB version {migrateVersion}."); 74 | } 75 | } 76 | 77 | connection.Execute($"PRAGMA user_version = {DbVersion};"); 78 | 79 | _logger.LogInformation($"InfuseSync: DB migration finished."); 80 | } 81 | 82 | public void Dispose() 83 | { 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /InfuseSync/Storage/Migrations/IDbMigration.cs: -------------------------------------------------------------------------------- 1 | #if EMBY 2 | using DatabaseConnection = SQLitePCL.pretty.IDatabaseConnection; 3 | #else 4 | using DatabaseConnection = Microsoft.Data.Sqlite.SqliteConnection; 5 | #endif 6 | 7 | namespace InfuseSync.Storage.Migrations 8 | { 9 | public interface IDbMigration 10 | { 11 | int DbVersion { get; } 12 | void Migrate(DatabaseConnection connection); 13 | } 14 | } -------------------------------------------------------------------------------- /InfuseSync/Storage/Migrations/MigrationChangeUserDataPrimaryKey.cs: -------------------------------------------------------------------------------- 1 | #if EMBY 2 | using SQLitePCL.pretty; 3 | using DatabaseConnection = SQLitePCL.pretty.IDatabaseConnection; 4 | #else 5 | using Microsoft.Data.Sqlite; 6 | using DatabaseConnection = Microsoft.Data.Sqlite.SqliteConnection; 7 | #endif 8 | 9 | namespace InfuseSync.Storage.Migrations 10 | { 11 | public class MigrationChangeUserDataPrimaryKey : IDbMigration 12 | { 13 | public int DbVersion => 1; 14 | 15 | public void Migrate(DatabaseConnection connection) 16 | { 17 | connection.RunInTransaction(db => 18 | { 19 | if (!db.TableExists("user_info")) 20 | { 21 | return; 22 | } 23 | 24 | string createQuery = 25 | #if EMBY 26 | "create table if not exists user_info_tmp(Id TEXT NOT NULL, Guid GUID NOT NULL, UserId TEXT NOT NULL, LastModified INTEGER NOT NULL, Type TEXT NOT NULL, PRIMARY KEY (Id, UserId))"; 27 | #else 28 | "create table if not exists user_info_tmp(Guid GUID NOT NULL, UserId TEXT NOT NULL, LastModified INTEGER NOT NULL, Type TEXT NOT NULL, PRIMARY KEY (Guid, UserId))"; 29 | #endif 30 | db.Execute(createQuery); 31 | db.Execute("insert into user_info_tmp select * from user_info"); 32 | db.Execute("drop table user_info"); 33 | db.Execute("alter table user_info_tmp rename to user_info"); 34 | 35 | string createIndex = 36 | #if EMBY 37 | "create index if not exists idx_user_info on user_info(Id, UserId)"; 38 | #else 39 | "create index if not exists idx_user_info on user_info(Guid, UserId)"; 40 | #endif 41 | db.Execute(createIndex); 42 | }); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /InfuseSync/Storage/Migrations/MigrationDropBetaDatabase.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | #if EMBY 5 | using SQLitePCL.pretty; 6 | using DatabaseConnection = SQLitePCL.pretty.IDatabaseConnection; 7 | #else 8 | using Microsoft.Data.Sqlite; 9 | using DatabaseConnection = Microsoft.Data.Sqlite.SqliteConnection; 10 | #endif 11 | 12 | namespace InfuseSync.Storage.Migrations 13 | { 14 | public class MigrationDropBetaDatabase : IDbMigration 15 | { 16 | public int DbVersion => 0; 17 | 18 | public void Migrate(DatabaseConnection connection) 19 | { 20 | connection.RunInTransaction(db => { 21 | var selectTable = "select name from sqlite_master where type='table' and name not like 'sqlite_%';"; 22 | List tables; 23 | using (var entitiesStatetment = db.PrepareStatement(selectTable)) 24 | { 25 | tables = entitiesStatetment.ExecuteQuery().Select(row => row.GetString(0)).ToList(); 26 | } 27 | 28 | foreach (var table in tables) 29 | { 30 | db.Execute($"drop table '{table}';"); 31 | } 32 | 33 | var selectIndex = "select name from sqlite_master where type='index' and name not like 'sqlite_%';"; 34 | List indexes; 35 | using (var indexesStatetment = db.PrepareStatement(selectIndex)) 36 | { 37 | indexes = indexesStatetment.ExecuteQuery().Select(row => row.GetString(0)).ToList(); 38 | } 39 | 40 | foreach (var index in indexes) 41 | { 42 | db.Execute($"drop index '{index}';"); 43 | } 44 | }); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /InfuseSync/Storage/ReaderWriterLockSlimExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | 4 | namespace InfuseSync.Storage 5 | { 6 | public static class ReaderWriterLockSlimExtensions 7 | { 8 | public static IDisposable Read(this ReaderWriterLockSlim obj) 9 | { 10 | return new ReadLockToken(obj); 11 | } 12 | 13 | public static IDisposable Write(this ReaderWriterLockSlim obj) 14 | { 15 | return new WriteLockToken(obj); 16 | } 17 | 18 | private sealed class ReadLockToken : IDisposable 19 | { 20 | private ReaderWriterLockSlim _sync; 21 | 22 | public ReadLockToken(ReaderWriterLockSlim sync) 23 | { 24 | _sync = sync; 25 | sync.EnterReadLock(); 26 | } 27 | 28 | public void Dispose() 29 | { 30 | if (_sync != null) 31 | { 32 | _sync.ExitReadLock(); 33 | _sync = null; 34 | } 35 | } 36 | } 37 | 38 | private sealed class WriteLockToken : IDisposable 39 | { 40 | private ReaderWriterLockSlim _sync; 41 | 42 | public WriteLockToken(ReaderWriterLockSlim sync) 43 | { 44 | _sync = sync; 45 | sync.EnterWriteLock(); 46 | } 47 | 48 | public void Dispose() 49 | { 50 | if (_sync != null) 51 | { 52 | _sync.ExitWriteLock(); 53 | _sync = null; 54 | } 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /InfuseSync/thumb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/firecore/InfuseSync/551e23fd6040d858b6bbe6b8647552cda7328f83/InfuseSync/thumb.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # InfuseSync 2 | 3 | InfuseSync is a plugin for Emby and Jellyfin media servers that tracks all media changes to decrease sync times with [Infuse](https://firecore.com/infuse) clients. 4 | 5 | ## Standard Installation (recommended) 6 | View the InfuseSync [install guide](https://support.firecore.com/hc/articles/23885208585367) for Emby and Jellyfin. 7 | 8 | ## Build and Install Manually 9 | 10 | 1. Install [.NET Core SDK](https://dotnet.microsoft.com/download) 11 | 12 | 2. Build the plugin with following command: 13 | 14 | ``` 15 | dotnet publish --configuration Release 16 | ``` 17 | 18 | 3. Place the resulting .dll file that can be found in ```InfuseSync/bin/emby``` or ```InfuseSync/bin/jellyfin``` directory into a plugin folder for the corresponding media server. 19 | --------------------------------------------------------------------------------