private ManualImportItem MapItem(ImportDecision <LocalTrack> decision, string downloadId, bool replaceExistingFiles, bool disableReleaseSwitching)
        {
            var item = new ManualImportItem();

            item.Id         = HashConverter.GetHashInt31(decision.Item.Path);
            item.Path       = decision.Item.Path;
            item.Name       = Path.GetFileNameWithoutExtension(decision.Item.Path);
            item.DownloadId = downloadId;

            if (decision.Item.Artist != null)
            {
                item.Artist = decision.Item.Artist;
            }

            if (decision.Item.Album != null)
            {
                item.Album   = decision.Item.Album;
                item.Release = decision.Item.Release;
            }

            if (decision.Item.Tracks.Any())
            {
                item.Tracks = decision.Item.Tracks;
            }

            item.Quality                 = decision.Item.Quality;
            item.Size                    = _diskProvider.GetFileSize(decision.Item.Path);
            item.Rejections              = decision.Rejections;
            item.Tags                    = decision.Item.FileTrackInfo;
            item.AdditionalFile          = decision.Item.AdditionalFile;
            item.ReplaceExistingFiles    = replaceExistingFiles;
            item.DisableReleaseSwitching = disableReleaseSwitching;

            return(item);
        }
Exemple #2
0
        public IActionResult Authenticate(UserInfo userInfo)
        {
            try
            {
                var userId = userService.Authenticate(userInfo.Email, userInfo.Password);

                var    tokenHandler = new JwtSecurityTokenHandler();
                string key          = Secrets.JwtKey;
                byte[] keyByte      = HashConverter.PlainTextToBytes(key);

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, userId.ToString())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(keyByte), SecurityAlgorithms.HmacSha256Signature)
                };
                var token       = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                return(Ok(new { token = tokenString }));
            }
            catch (Exception ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Exemple #3
0
        private Queue MapQueueItem(TrackedDownload trackedDownload, Episode episode)
        {
            var queue = new Queue
            {
                Series   = trackedDownload.RemoteEpisode?.Series,
                Episode  = episode,
                Language = trackedDownload.RemoteEpisode?.ParsedEpisodeInfo.Language ?? Language.Unknown,
                Quality  = trackedDownload.RemoteEpisode?.ParsedEpisodeInfo.Quality ?? new QualityModel(Quality.Unknown),
                Title    = Parser.Parser.RemoveFileExtension(trackedDownload.DownloadItem.Title),
                Size     = trackedDownload.DownloadItem.TotalSize,
                Sizeleft = trackedDownload.DownloadItem.RemainingSize,
                Timeleft = trackedDownload.DownloadItem.RemainingTime,
                Status   = trackedDownload.DownloadItem.Status.ToString(),
                TrackedDownloadStatus = trackedDownload.Status,
                TrackedDownloadState  = trackedDownload.State,
                StatusMessages        = trackedDownload.StatusMessages.ToList(),
                ErrorMessage          = trackedDownload.DownloadItem.Message,
                RemoteEpisode         = trackedDownload.RemoteEpisode,
                DownloadId            = trackedDownload.DownloadItem.DownloadId,
                Protocol       = trackedDownload.Protocol,
                DownloadClient = trackedDownload.DownloadItem.DownloadClientInfo.Name,
                Indexer        = trackedDownload.Indexer,
                OutputPath     = trackedDownload.DownloadItem.OutputPath.ToString()
            };

            queue.Id = HashConverter.GetHashInt31($"trackedDownload-{trackedDownload.DownloadClient}-{trackedDownload.DownloadItem.DownloadId}-ep{episode?.Id ?? 0}");

            if (queue.Timeleft.HasValue)
            {
                queue.EstimatedCompletionTime = DateTime.UtcNow.Add(queue.Timeleft.Value);
            }

            return(queue);
        }
Exemple #4
0
        private List <User> Update(List <UserExt> toUpdateList)
        {
            List <User> updateObj = new List <User>();

            foreach (var u in toUpdateList)
            {
                if (!u.Password.Contains("*"))
                {
                    var tempPass = HashConverter.CalculateHash(u.Password, u.Username);

                    var user = UserServices.GetUser(u.ID);
                    if (user != null && (user.Username != u.Username ||
                                         user.Name != u.Name ||
                                         user.RoleID != u.RoleID ||
                                         user.Email != u.Email ||
                                         user.Address != u.Address ||
                                         user.Password != tempPass))
                    {
                        user.Username   = u.Username;
                        user.Password   = tempPass;
                        user.Name       = u.Name;
                        user.Role       = RoleServices.GetRole(u.RoleID.GetValueOrDefault());
                        user.RoleID     = u.RoleID;
                        user.Email      = u.Email;
                        user.Address    = u.Address;
                        user.ModifiedOn = DateTime.Now;
                        user.ModifiedBy = AuthenticatedUser;
                        updateObj.Add(user);
                    }
                }
            }
            return(updateObj);
        }
        public void Authentication(string username, string clearTextPassword)
        {
            var userData = userRepository.Login(username, HashConverter.CalculateHash(clearTextPassword, username));

            if (userData == null)
            {
                throw new UnauthorizedAccessException("Access denied. Please provide some valid credentials.");
            }

            //#region Handheld != Access Denied
            //if (userData.RoleID.HasValue && userData.Role.RoleCode != "ADMINISTRATOR")
            //{
            //    if (DisableAccessForHandheldUser(userData.RoleID.Value))
            //        throw new UnauthorizedAccessException("Access denied. This role was not authorized to access the system.");
            //}
            //#endregion Handheld User != Access Denied

            CustomPrincipal customPrincipal = Thread.CurrentPrincipal as CustomPrincipal;

            if (customPrincipal == null)
            {
                throw new ArgumentException("The application's default thread principal must be set to a CustomPrincipal object on startup.");
            }

            customPrincipal.Identity = new CustomIdentity(userData.Username, userData.Role.RoleCode, userData.Email);
        }
Exemple #6
0
        public List <Queue.Queue> GetPendingQueue()
        {
            var queued = new List <Queue.Queue>();

            foreach (var pendingRelease in GetPendingReleases())
            {
                foreach (var episode in pendingRelease.RemoteEpisode.Episodes)
                {
                    var ect = pendingRelease.Release.PublishDate.AddMinutes(GetDelay(pendingRelease.RemoteEpisode));

                    var queue = new Queue.Queue
                    {
                        Id                      = HashConverter.GetHashInt31(string.Format("pending-{0}-ep{1}", pendingRelease.Id, episode.Id)),
                        Series                  = pendingRelease.RemoteEpisode.Series,
                        Episode                 = episode,
                        Quality                 = pendingRelease.RemoteEpisode.ParsedEpisodeInfo.Quality,
                        Title                   = pendingRelease.Title,
                        Size                    = pendingRelease.RemoteEpisode.Release.Size,
                        Sizeleft                = pendingRelease.RemoteEpisode.Release.Size,
                        RemoteEpisode           = pendingRelease.RemoteEpisode,
                        Timeleft                = ect.Subtract(DateTime.UtcNow),
                        EstimatedCompletionTime = ect,
                        Status                  = "Pending"
                    };
                    queued.Add(queue);
                }
            }

            return(queued);
        }
        public void ShouldInsertEntriesInThreadSafeManner()
        {
            var storage       = new RAMStorage(50);
            var hashConverter = new HashConverter();

            var hashes = Enumerable.Range(0, 100).Select(b => (byte)b).ToArray();
            var longs  = hashConverter.ToInts(hashes, 25);

            int   tracksCount             = 520;
            int   subFingerprintsPerTrack = 33;
            float one = 8192f / 5512;

            Parallel.For(0, tracksCount, i =>
            {
                var trackReference = new ModelReference <int>(i);
                for (int j = 0; j < subFingerprintsPerTrack; ++j)
                {
                    var hashed = new HashedFingerprint(longs, (uint)j, j * one, Array.Empty <byte>());
                    storage.AddHashedFingerprint(hashed, trackReference);
                }
            });

            for (int i = 0; i < 25; ++i)
            {
                var subFingerprints = storage.GetSubFingerprintsByHashTableAndHash(i, longs[i]);
                Assert.AreEqual(tracksCount * subFingerprintsPerTrack, subFingerprints.Count);
            }
        }
Exemple #8
0
        public static ManualImportResource ToResource(this Core.MediaFiles.EpisodeImport.Manual.ManualImportItem model)
        {
            if (model == null)
            {
                return(null);
            }

            return(new ManualImportResource
            {
                Id = HashConverter.GetHashInt31(model.Path),

                Path = model.Path,
                RelativePath = model.RelativePath,
                FolderName = model.FolderName,
                Name = model.Name,
                Size = model.Size,
                Series = model.Series.ToResource(),
                SeasonNumber = model.SeasonNumber,
                Episodes = model.Episodes.ToResource(),
                Quality = model.Quality,
                //QualityWeight
                DownloadId = model.DownloadId,
                Rejections = model.Rejections
            });
        }
Exemple #9
0
        private Queue MapMovie(TrackedDownload trackedDownload, Movie movie)
        {
            var queue = new Queue
            {
                Languages = trackedDownload.RemoteMovie?.ParsedMovieInfo.Languages ?? new List <Language> {
                    Language.Unknown
                },
                Quality  = trackedDownload.RemoteMovie?.ParsedMovieInfo.Quality ?? new QualityModel(Quality.Unknown),
                Title    = trackedDownload.DownloadItem.Title,
                Size     = trackedDownload.DownloadItem.TotalSize,
                Sizeleft = trackedDownload.DownloadItem.RemainingSize,
                Timeleft = trackedDownload.DownloadItem.RemainingTime,
                Status   = trackedDownload.DownloadItem.Status.ToString(),
                TrackedDownloadStatus = trackedDownload.Status,
                TrackedDownloadState  = trackedDownload.State,
                StatusMessages        = trackedDownload.StatusMessages.ToList(),
                ErrorMessage          = trackedDownload.DownloadItem.Message,
                RemoteMovie           = trackedDownload.RemoteMovie,
                DownloadId            = trackedDownload.DownloadItem.DownloadId,
                Protocol       = trackedDownload.Protocol,
                Movie          = movie,
                DownloadClient = trackedDownload.DownloadItem.DownloadClientInfo.Name,
                Indexer        = trackedDownload.Indexer,
                OutputPath     = trackedDownload.DownloadItem.OutputPath.ToString()
            };

            queue.Id = HashConverter.GetHashInt31($"trackedDownload-{trackedDownload.DownloadClient}-{trackedDownload.DownloadItem.DownloadId}");

            if (queue.Timeleft.HasValue)
            {
                queue.EstimatedCompletionTime = DateTime.UtcNow.Add(queue.Timeleft.Value);
            }

            return(queue);
        }
Exemple #10
0
        public static ManualImportResource ToResource(this ManualImportItem model)
        {
            if (model == null)
            {
                return(null);
            }

            return(new ManualImportResource
            {
                Id = HashConverter.GetHashInt31(model.Path),
                Path = model.Path,
                RelativePath = model.RelativePath,
                FolderName = model.FolderName,
                Name = model.Name,
                Size = model.Size,
                Movie = model.Movie.ToResource(0),
                Quality = model.Quality,
                Languages = model.Languages,
                ReleaseGroup = model.ReleaseGroup,

                //QualityWeight
                DownloadId = model.DownloadId,
                Rejections = model.Rejections
            });
        }
Exemple #11
0
        private Queue MapEpisode(TrackedDownload trackedDownload, Episode episode)
        {
            var queue = new Queue
            {
                Id       = HashConverter.GetHashInt31(string.Format("trackedDownload-{0}-ep{1}", trackedDownload.DownloadItem.DownloadId, episode.Id)),
                Series   = trackedDownload.RemoteEpisode.Series,
                Episode  = episode,
                Quality  = trackedDownload.RemoteEpisode.ParsedEpisodeInfo.Quality,
                Title    = trackedDownload.DownloadItem.Title,
                Size     = trackedDownload.DownloadItem.TotalSize,
                Sizeleft = trackedDownload.DownloadItem.RemainingSize,
                Timeleft = trackedDownload.DownloadItem.RemainingTime,
                Status   = trackedDownload.DownloadItem.Status.ToString(),
                TrackedDownloadStatus = trackedDownload.Status.ToString(),
                StatusMessages        = trackedDownload.StatusMessages.ToList(),
                RemoteEpisode         = trackedDownload.RemoteEpisode,
                DownloadId            = trackedDownload.DownloadItem.DownloadId,
                Protocol = trackedDownload.Protocol
            };

            if (queue.Timeleft.HasValue)
            {
                queue.EstimatedCompletionTime = DateTime.UtcNow.Add(queue.Timeleft.Value);
            }

            return(queue);
        }
        public void should_remove_same_release()
        {
            AddPending(id: 1, album: "Album");

            var queueId = HashConverter.GetHashInt31(string.Format("pending-{0}-book{1}", 1, _album.Id));

            Subject.RemovePendingQueueItems(queueId);

            AssertRemoved(1);
        }
        public void should_remove_same_release()
        {
            AddPending(id: 1, title: "Movie", year: 2001);

            var queueId = HashConverter.GetHashInt31(string.Format("pending-{0}-movie{1}", 1, _movie.Id));

            Subject.RemovePendingQueueItems(queueId);

            AssertRemoved(1);
        }
        public void should_remove_same_release()
        {
            AddPending(id: 1, seasonNumber: 2, episodes: new[] { 3 });

            var queueId = HashConverter.GetHashInt31(string.Format("pending-{0}-ep{1}", 1, _episode.Id));

            Subject.RemovePendingQueueItems(queueId);

            AssertRemoved(1);
        }
        public void should_not_remove_singleepisodes()
        {
            AddPending(id: 1, seasonNumber: 2, episodes: new[] { 1 });
            AddPending(id: 2, seasonNumber: 2, episodes: new[] { 1, 2 });

            var queueId = HashConverter.GetHashInt31(string.Format("pending-{0}-ep{1}", 2, _episode.Id));

            Subject.RemovePendingQueueItems(queueId);

            AssertRemoved(2);
        }
        public void should_remove_multiple_releases_release()
        {
            AddPending(id: 1, album: "Album 1");
            AddPending(id: 2, album: "Album 2");
            AddPending(id: 3, album: "Album 3");
            AddPending(id: 4, album: "Album 3");

            var queueId = HashConverter.GetHashInt31(string.Format("pending-{0}-book{1}", 3, _album.Id));

            Subject.RemovePendingQueueItems(queueId);

            AssertRemoved(3, 4);
        }
        public void should_not_remove_diffrent_albums()
        {
            AddPending(id: 1, album: "Album 1");
            AddPending(id: 2, album: "Album 1");
            AddPending(id: 3, album: "Album 2");
            AddPending(id: 4, album: "Album 3");

            var queueId = HashConverter.GetHashInt31(string.Format("pending-{0}-book{1}", 1, _album.Id));

            Subject.RemovePendingQueueItems(queueId);

            AssertRemoved(1, 2);
        }
        public void should_not_remove_diffrent_books()
        {
            AddPending(id: 1, book: "Book 1");
            AddPending(id: 2, book: "Book 1");
            AddPending(id: 3, book: "Book 2");
            AddPending(id: 4, book: "Book 3");

            var queueId = HashConverter.GetHashInt31(string.Format("pending-{0}-book{1}", 1, _book.Id));

            Subject.RemovePendingQueueItems(queueId);

            AssertRemoved(1, 2);
        }
        public void should_not_remove_diffrent_season()
        {
            AddPending(id: 1, seasonNumber: 2, episodes: new[] { 1 });
            AddPending(id: 2, seasonNumber: 2, episodes: new[] { 1 });
            AddPending(id: 3, seasonNumber: 3, episodes: new[] { 1 });
            AddPending(id: 4, seasonNumber: 3, episodes: new[] { 1 });

            var queueId = HashConverter.GetHashInt31(String.Format("pending-{0}-ep{1}", 1, _episode.Id));

            Subject.RemovePendingQueueItems(queueId);

            AssertRemoved(1, 2);
        }
        public void should_remove_multiple_releases_release()
        {
            AddPending(id: 1, seasonNumber: 2, episodes: new[] { 1 });
            AddPending(id: 2, seasonNumber: 2, episodes: new[] { 2 });
            AddPending(id: 3, seasonNumber: 2, episodes: new[] { 3 });
            AddPending(id: 4, seasonNumber: 2, episodes: new[] { 3 });

            var queueId = HashConverter.GetHashInt31(String.Format("pending-{0}-ep{1}", 3, _episode.Id));

            Subject.RemovePendingQueueItems(queueId);

            AssertRemoved(3, 4);
        }
Exemple #21
0
        public async Task <UserDto> CreateUser(UserDto input)
        {
            var user = new User
            {
                Username = input.Username,
                Password = HashConverter.CreateMD5(input.Password)
            };

            await _context.Users.AddAsync(user);

            await _context.SaveChangesAsync();

            return(_mapper.Map <User, UserDto>(user));
        }
Exemple #22
0
        private bool VerifyHash(string password, string storedHash)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty, null or whitespace only string.", "password");
            }

            byte[] key = HashConverter.PlainTextToBytes(Secrets.MD5Key);
            using (var hmac = new System.Security.Cryptography.HMACMD5(key))
            {
                var computedHash = HashConverter.ToString(hmac.ComputeHash(HashConverter.PlainTextToBytes(password)));
                return(storedHash == computedHash);
            }
        }
Exemple #23
0
        public void Create(string email, string password)
        {
            ValidateEmail(email);
            ValidatePassword(password);

            var user = new User {
                Name = email
            };

            user.Hash = HashConverter.ToString(CreateHash(password));

            database.Users.Create(user);
            database.Save();
        }
Exemple #24
0
        private Queue MapQueueItem(TrackedDownload trackedDownload, Album album)
        {
            bool downloadForced = false;
            var  history        = _historyService.Find(trackedDownload.DownloadItem.DownloadId, HistoryEventType.Grabbed).FirstOrDefault();

            if (history != null && history.Data.ContainsKey("downloadForced"))
            {
                downloadForced = bool.Parse(history.Data["downloadForced"]);
            }

            var queue = new Queue
            {
                Artist   = trackedDownload.RemoteAlbum?.Artist,
                Album    = album,
                Quality  = trackedDownload.RemoteAlbum?.ParsedAlbumInfo.Quality ?? new QualityModel(Quality.Unknown),
                Title    = Parser.Parser.RemoveFileExtension(trackedDownload.DownloadItem.Title),
                Size     = trackedDownload.DownloadItem.TotalSize,
                Sizeleft = trackedDownload.DownloadItem.RemainingSize,
                Timeleft = trackedDownload.DownloadItem.RemainingTime,
                Status   = trackedDownload.DownloadItem.Status.ToString(),
                TrackedDownloadStatus = trackedDownload.Status,
                TrackedDownloadState  = trackedDownload.State,
                StatusMessages        = trackedDownload.StatusMessages.ToList(),
                ErrorMessage          = trackedDownload.DownloadItem.Message,
                RemoteAlbum           = trackedDownload.RemoteAlbum,
                DownloadId            = trackedDownload.DownloadItem.DownloadId,
                Protocol       = trackedDownload.Protocol,
                DownloadClient = trackedDownload.DownloadItem.DownloadClientInfo.Name,
                Indexer        = trackedDownload.Indexer,
                OutputPath     = trackedDownload.DownloadItem.OutputPath.ToString(),
                DownloadForced = downloadForced
            };

            if (album != null)
            {
                queue.Id = HashConverter.GetHashInt31(string.Format("trackedDownload-{0}-album{1}", trackedDownload.DownloadItem.DownloadId, album.Id));
            }
            else
            {
                queue.Id = HashConverter.GetHashInt31(string.Format("trackedDownload-{0}", trackedDownload.DownloadItem.DownloadId));
            }

            if (queue.Timeleft.HasValue)
            {
                queue.EstimatedCompletionTime = DateTime.UtcNow.Add(queue.Timeleft.Value);
            }

            return(queue);
        }
Exemple #25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddMvcCore()
            .AddApiExplorer();

            services.AddCors();

            // configure jwt authentication
            string key = Secrets.JwtKey;

            byte[] keyByte = HashConverter.PlainTextToBytes(key);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>();
                        var userId      = int.Parse(context.Principal.Identity.Name);
                        var user        = userService.GetById(userId);
                        if (user == null)
                        {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        return(Task.CompletedTask);
                    }
                };
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(keyByte),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            services.AddScoped <IUserService, UserService>();
        }
Exemple #26
0
 private User Add(User data)
 {
     return(new User
     {
         Username = UsernameAlias,
         Password = HashConverter.CalculateHash(Password, UsernameAlias),
         RoleID = SelectedRole.ID,
         Name = data.Name,
         Email = data.Email,
         Address = data.Address,
         CreatedOn = DateTime.Now,
         CreatedBy = AuthenticatedUser,
         ModifiedOn = DateTime.Now,
         ModifiedBy = AuthenticatedUser
     });
 }
Exemple #27
0
        private string GetHash(string file)
        {
            var data = new StringBuilder();

            data.Append(file);
            try
            {
                data.Append(_diskProvider.FileGetLastWrite(file).ToBinary());
                data.Append(_diskProvider.GetFileSize(file));
            }
            catch (Exception ex)
            {
                _logger.Trace(ex, "Ignored hashing error during scan for {0}", file);
            }

            return(HashConverter.GetHash(data.ToString()).ToHexString());
        }
Exemple #28
0
        private User Update(User data)
        {
            var userUpdate = UserServices.GetUser(data.ID);

            if (userUpdate != null)
            {
                userUpdate.Username   = UsernameAlias;
                userUpdate.Password   = !string.IsNullOrEmpty(Password) ? HashConverter.CalculateHash(Password, UsernameAlias) : data.Password;
                userUpdate.Role       = SelectedRole;
                userUpdate.RoleID     = SelectedRole.ID;
                userUpdate.Name       = data.Name;
                userUpdate.Email      = data.Email;
                userUpdate.Address    = data.Address;
                userUpdate.ModifiedOn = DateTime.Now;
                userUpdate.ModifiedBy = AuthenticatedUser;
            }
            return(userUpdate);
        }
Exemple #29
0
        private byte[] CreateHash(string password)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty, null or whitespace only string.", "password");
            }

            string key = Secrets.MD5Key;

            byte[] keyByte = HashConverter.PlainTextToBytes(key);

            byte[] hash;
            using (var hmac = new System.Security.Cryptography.HMACMD5(keyByte))
            {
                hash = hmac.ComputeHash(HashConverter.PlainTextToBytes(password));
            }
            return(hash);
        }
Exemple #30
0
        private string GetHash(string folder, string[] files)
        {
            var data = new StringBuilder();

            data.Append(folder);
            try
            {
                data.Append(_diskProvider.FolderGetLastWrite(folder).ToBinary());
            }
            catch (Exception ex)
            {
                _logger.Trace(ex, "Ignored hashing error during scan for {0}", folder);
            }

            foreach (var file in files.OrderBy(v => v))
            {
                data.Append(GetHash(file));
            }

            return(HashConverter.GetHash(data.ToString()).ToHexString());
        }