Пример #1
0
        private async Task <Models.User> RetrieveAuthor(Models.Post post)
        {
            var userCollection = MongoWrapper.Database.GetCollection <Models.User>(nameof(User));

            var userFilterBuilder = new FilterDefinitionBuilder <Models.User>();
            var userFilter        = userFilterBuilder.And
                                    (
                userFilterBuilder.Eq(u => u._id, post.Poster._id),
                GeneralUtils.NotDeactivated(userFilterBuilder)
                                    );

            var userProjectionBuilder = new ProjectionDefinitionBuilder <Models.User>();
            var userProjection        = userProjectionBuilder
                                        .Include(m => m._id)
                                        .Include(m => m.FullName)
                                        .Include(m => m.Avatar)
                                        .Include(m => m.Phone)
                                        .Include(m => m.StartDate)
                                        .Include(m => m.Email)
                                        .Include(m => m.Address)
                                        .Include("_t");

            return((await userCollection.FindAsync(userFilter, new FindOptions <Models.User>
            {
                Limit = 1,
                AllowPartialResults = true,
                Projection = userProjection
            })).SingleOrDefault());
        }
Пример #2
0
        public async Task <List <Movie> > GetMovies(int yearLowerBand, int yearUpperBand)
        {
            var movies = new List <Movie>();

            var projectionBuilder = new ProjectionDefinitionBuilder <Movie>();
            var projection        = projectionBuilder
                                    .Include(x => x.Awards)
                                    .Include(x => x.Genres)
                                    .Include(x => x.Plot)
                                    .Include(x => x.Rated)
                                    .Include(x => x.Title)
                                    .Include(x => x.Year)
                                    .Exclude("_id");

            var filterBuilder = new FilterDefinitionBuilder <Movie>();
            var filter        = filterBuilder.Gte(x => x.Year, yearLowerBand) & filterBuilder.Lte(x => x.Year, yearUpperBand);

            using (IAsyncCursor <Movie> documents = await _database.GetCollection <Movie>("movies")
                                                    .FindAsync(filter, new FindOptions <Movie, Movie>
            {
                Projection = projection
            }))
            {
                while (documents.MoveNext())
                {
                    movies.AddRange(documents.Current);
                }
            }

            return(movies);
        }
        public async Task <T> GetDocumentWithSpecificFieldsAsync(string objectIdString, string[] projectionFields)
        {
            // TODO:Mohit Use FilterDefinitionBuilder - as the class is created for specific purpose

            var filter = new BsonDocument();

            filter.Add("_id", objectIdString);

            var projBuilder = new ProjectionDefinitionBuilder <T>();

            ProjectionDefinition <T>[] projections = new ProjectionDefinition <T> [projectionFields.Length];
            for (int i = 0; i < projectionFields.Length; i++)
            {
                var prof = projBuilder.Include(projectionFields[i]);
                projections[i] = prof;
            }

            var projectionDefinition = projBuilder.Combine(projections);
            var resultList           = await this.Collection.Find(filter).Project <T>(projectionDefinition).ToListAsync();

            //var resultList = await collection.Find(filter).ToListAsync();

            if (resultList.Count > 0)
            {
                return(resultList[0]);
            }
            else
            {
                return(null);
            }
        }
Пример #4
0
        public async Task <string> FilterMovies(int yearLowerBand, int yearUpperBand)
        {
            var movies = new List <BsonDocument>();

            var projectionBuilder = new ProjectionDefinitionBuilder <BsonDocument>();
            var projection        = projectionBuilder
                                    .Include("awards")
                                    .Include("genres")
                                    .Include("plot")
                                    .Include("rated")
                                    .Include("title")
                                    .Include("year")
                                    .Exclude("_id");

            var filterBuilder = new FilterDefinitionBuilder <BsonDocument>();
            var filter        = filterBuilder.Gte("year", yearLowerBand) & filterBuilder.Lte("year", yearUpperBand);

            using (IAsyncCursor <BsonDocument> documents = await _database.GetCollection <BsonDocument>("movies").FindAsync(filter))
            {
                while (documents.MoveNext())
                {
                    movies.AddRange(documents.Current);
                }
            }

            return(movies.ToJson());
        }
Пример #5
0
        public List <BsonDocument> getSatinfo()  //for combox 下拉显示

        {
            List <BsonDocument> satinfoList = new List <BsonDocument>();

            col = MongoDBHelper <SatInfomation> .Init();


            //创建约束生成器
            FilterDefinitionBuilder <BsonDocument> builder = Builders <BsonDocument> .Filter;

            ProjectionDefinitionBuilder <BsonDocument> builderProjection = Builders <BsonDocument> .Projection;
            //Exclude  不包含某元素
            ProjectionDefinition <BsonDocument> projection = builderProjection.Include("SatName").Exclude("_id");

            try
            {
                satinfoList = col.Find <BsonDocument>(builder.Empty).Project(projection).ToList();

                //foreach (var item in result)
                //{
                //    //取出整条值
                //    Console.WriteLine(item[0]);
                //}
            }

            catch (Exception e)
            {
                Console.WriteLine("mongodb连接失败" + e.Message); //只是输出终端显示 异常信息
                //throw;  //这是主动抛出异常 使程序停止
            }
            return(satinfoList);
        }
        public async Task <dynamic> Post([FromBody] PasswordRecoveryRequest requestBody)
        {
            this.EnsureModelValidation();

            var collection = MongoWrapper.Database.GetCollection <Models.User>(nameof(User));

            var projectionBuilder = new ProjectionDefinitionBuilder <Models.User>();
            var projection        = projectionBuilder
                                    .Include(u => u._id)
                                    .Include(u => u.Email)
                                    .Include(u => u.FullName)
                                    .Include("_t");

            var filterBuilder = new FilterDefinitionBuilder <Models.User>();
            var filter        = filterBuilder.And(
                filterBuilder.Eq(u => u.Email, requestBody.Email),
                GeneralUtils.NotDeactivated(filterBuilder)
                );

            var user = (await collection.FindAsync(filter, new FindOptions <Models.User>
            {
                Limit = 1,
                Projection = projection,
            })).SingleOrDefault();

            await EmailUtils.SendPasswordRecoveryEmail(MongoWrapper, SmtpConfiguration, user);

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Data = null,
                Message = "Um código foi enviado para o e-mail! Este código permite a redefinição para uma senha gerada automaticamente.",
                Success = true,
            });
        }
Пример #7
0
        public bool ApplyToCourse(string route)
        {
            // Validate the course's existence in the first place
            var courseFields = CourseFieldBuilder.Include(c => c.Id);
            var courses      = _courseCollection
                               .Find(c => c.PublicRoute == route)
                               .Project <Course>(courseFields)
                               .ToList();

            if (courses.Count == 0)
            {
                return(false);
            }
            var course = courses.Single();

            // Validate the user's existence in the first place
            var userFields = UserFieldBuilder
                             .Include(u => u.CoursesApplied);
            var email = User.Identity?.Name;
            var users = _userCollection
                        .Find(u => u.Email == email)
                        .Project <User>(userFields)
                        .ToList();

            if (users.Count == 0)
            {
                return(false);
            }

            var user = users.Single();

            if (user.CoursesApplied.Contains(course.Id))
            {
                return(false);
            }

            var update = Builders <User> .Update.PushEach("courses_applied", new List <ObjectId>
            {
                course.Id
            }, position : 0);

            _userCollection.UpdateOne(u => u.Email == email, update);

            return(true);
        }
Пример #8
0
        protected virtual ProjectionDefinition <T> CreateProjectionDefinition(
            ProjectionParams projection, ProjectionDefinitionBuilder <T> projectionBuilder)
        {
            projection = projection ?? new ProjectionParams();

            return(projectionBuilder.Combine(
                       projection.Select(field => projectionBuilder.Include(field))
                       ).Exclude(InternalIdFieldName));
        }
Пример #9
0
 /// <summary>
 /// 内嵌文档分页
 /// </summary>
 public void SunPageList()
 {
     //投影定义创建器:ProjectionDefinitionBuilder
     //用ProjectionDefinition过滤子文档
     ProjectionDefinitionBuilder <Model2> projBuilder = Builders <Model2> .Projection;
     //Include :确定要包含哪些字段值(即给哪些字段赋值)
     //Slice:获得子文档集合分片,第一个参数field指取出的子文档集合,第二各参数skip指跳过多少个子文档,第三个参数limit取出多少个
     ProjectionDefinition <Model2> proj = projBuilder.Include(m => m.Field2C).Slice(m => m.Field2C, 1, 3);
     //过滤条件是Field2A=2
     Model2 doc = mongoDBService.SubdocumentPageList <Model2>(collectionName, m => m.Field2A == "2", proj);
 }
Пример #10
0
        public IActionResult LogIn([FromBody] LoginData request)
        {
            var userFields = UserFieldBuilder
                             .Include(u => u.Email)
                             .Include(u => u.Password)
                             .Include(u => u.Salt)
                             .Include(u => u.FirstName)
                             .Include(u => u.LastName);

            var list = _userCollection
                       .Find(u => u.Email == request.Email)
                       .Project <User>(userFields)
                       .ToList();

            var data = new Dictionary <string, object>();

            if (list.Count != 0)
            {
                var user = list[0];

                var salt   = user.Salt;
                var hashed = GenerateHashedString(salt, request.Password);

                if (user.Password == hashed)
                {
                    data["user"] = new Dictionary <string, object>
                    {
                        ["email"]     = user.Email,
                        ["firstName"] = user.FirstName,
                        ["lastName"]  = user.LastName,
                    };

                    var claims = new[]
                    {
                        new Claim(ClaimTypes.Name, request.Email)
                    };

                    var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Secret"]));
                    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(
                        issuer: "http://localhost:5000",
                        audience: "http://localhost:5000",
                        claims: claims,
                        expires: DateTime.Now.AddHours(2),
                        signingCredentials: credentials);

                    data["token"] = new JwtSecurityTokenHandler().WriteToken(token);
                    return(Ok(data));
                }
            }

            return(BadRequest());
        }
Пример #11
0
        private BsonDocument simpleKeyQuery()
        {
            // Key Query
            rotateCollection();
            BsonDocument query = new BsonDocument();
            int          range = sequence * testOpts.workingset / 100;
            int          rest  = sequence - range;

            int recordno = rest + getNextVal(range);

            query.Add("_id",
                      new BsonDocument("w", workerID).Add("i", recordno));
            DateTime      starttime = DateTime.Now;
            BsonDocument  myDoc;
            List <String> projFields = new List <String>(testOpts.numFields);

            if (testOpts.projectFields == 0)
            {
                myDoc = coll.Find(query).FirstOrDefault();
            }
            else
            {
                int numProjFields = (testOpts.projectFields <= testOpts.numFields) ? testOpts.projectFields : testOpts.numFields;
                int i             = 0;
                while (i < numProjFields)
                {
                    projFields.Add("fld" + i);
                    i++;
                }
                var projection = new ProjectionDefinitionBuilder <BsonDocument>();
                foreach (var field in projFields)
                {
                    projection.Include(field);
                }
                myDoc = coll.Find(query)
                        .Project <BsonDocument>(projection.Combine())
                        .FirstOrDefault();
            }

            if (myDoc != null)
            {
                var taken = (DateTime.Now - starttime).TotalMilliseconds;
                if (taken > testOpts.slowThreshold)
                {
                    testResults.RecordSlowOp("keyqueries", 1);
                }
                testResults.RecordOpsDone("keyqueries", 1);
            }
            return(myDoc);
        }
Пример #12
0
        private void rangeQuery()
        {
            // Key Query
            rotateCollection();
            BsonDocument query      = new BsonDocument();
            var          projection = new ProjectionDefinitionBuilder <BsonDocument>();
            int          recordno   = getNextVal(sequence);

            query.Add("_id", new BsonDocument("$gt", new BsonDocument("w",
                                                                      workerID).Add("i", recordno)));
            DateTime starttime = new DateTime();
            IAsyncCursor <BsonDocument> cursor;

            if (testOpts.projectFields == 0)
            {
                cursor = coll.Find(query)
                         .Limit(testOpts.rangeDocs)
                         .ToCursor();
            }
            else
            {
                int numProjFields = (testOpts.projectFields <= testOpts.numFields) ? testOpts.projectFields : testOpts.numFields;
                for (int i = 0; i < numProjFields; i++)
                {
                    projection.Include("fld" + i);
                }
                cursor = coll.Find(query)
                         .Project <BsonDocument>(projection.Combine())
                         .Limit(testOpts.rangeDocs)
                         .ToCursor();
            }
            while (cursor.MoveNext())
            {
                var batch = cursor.Current;
                foreach (var doc in batch)
                {
                    // Consume the cursor
                }
            }
            cursor.Dispose();

            var taken = (DateTime.Now - starttime).TotalMilliseconds;

            if (taken > testOpts.slowThreshold)
            {
                testResults.RecordSlowOp("rangequeries", 1);
            }
            testResults.RecordOpsDone("rangequeries", 1);
        }
Пример #13
0
        public static async Task <ProjectDetails> GetProjectDetailsAsync(string projectId, KitsuneRequestUrlType kitsuneRequestUrlType = KitsuneRequestUrlType.PRODUCTION)
        {
            try
            {
                if (_server == null)
                {
                    InitiateConnection();
                }

                var projectionBuilder = new ProjectionDefinitionBuilder <ProductionKitsuneProject>();
                var projection        = projectionBuilder.Include(x => x.BucketNames)
                                        .Include(x => x.SchemaId)
                                        .Include(x => x.Version)
                                        .Include(x => x.Components)
                                        .Include(x => x.RuntimeOptimization)
                                        .Include(x => x._id)
                                        .Include(x => x.ProjectId)
                                        .Include(x => x.UserEmail)
                                        .Include(x => x.CompilerVersion);

                var filter = Builders <ProductionKitsuneProject> .Filter.Eq(document => document.ProjectId, projectId);

                var collectionName = KLM_Constants.KitsuneProjectProductionCollection;
                if (kitsuneRequestUrlType == KitsuneRequestUrlType.DEMO || kitsuneRequestUrlType == KitsuneRequestUrlType.PREVIEW)
                {
                    collectionName = KLM_Constants.KitsuneProjectCollection;
                }

                var productionKitsuneProjectsCOllection = _kitsuneDB.GetCollection <ProductionKitsuneProject>(collectionName);
                var result = await productionKitsuneProjectsCOllection.Find(filter,
                                                                            new FindOptions { MaxTime = TimeSpan.FromMilliseconds(KLM_Constants.MongoQueryMaxtimeOut) }).Project <ProductionKitsuneProject>(projection).FirstOrDefaultAsync();

                return(new ProjectDetails()
                {
                    BucketNames = result.BucketNames,
                    SchemaId = result.SchemaId,
                    Version = result.Version,
                    Components = result.Components,
                    DeveloperEmail = result.UserEmail,
                    RuntimeOptimization = result.RuntimeOptimization,
                    ProjectId = result.ProjectId,
                    CompilerVersion = result.CompilerVersion
                });
            }
            catch (Exception ex)
            {
            }
            return(null);
        }
        public async Task <List <T> > GetAllDocumentsWithSpecificFieldsAsync(string[] projectionFields)
        {
            var filter      = new BsonDocument();
            var projBuilder = new ProjectionDefinitionBuilder <T>();

            ProjectionDefinition <T>[] projections = new ProjectionDefinition <T> [projectionFields.Length];
            for (int i = 0; i < projectionFields.Length; i++)
            {
                var prof = projBuilder.Include(projectionFields[i]);
                projections[i] = prof;
            }

            var projectionDefinition = projBuilder.Combine(projections);
            var result = await this.Collection.Find(filter).Project <T>(projectionDefinition).ToListAsync();

            return(result);
        }
Пример #15
0
        /// <summary>TODO The main.</summary>
        public static void Main()
        {
            var client   = new MongoClient("mongodb://localhost:27017");
            var database = client.GetDatabase("test");

            var collection = database.GetCollection <Datapull>("Inquisitive_one");
            // InsertData(collection);

            // nice problem exploring mongo query weakness

            var projectionDef = new ProjectionDefinitionBuilder <Datapull>();
            var p             = projectionDef.Include(x => x.Sedol)
                                .Include(x => x.FSTicker)
                                .Include(x => x.Company);



            var data = collection.Aggregate();
            var a1   =
                data.Project(
                    x =>
                    new
            {
                FSTicker    = x.FSTicker,
                Sedol       = x.Sedol,
                Company     = x.Company,
                Exchange    = x.Exchange,
                LocalTicker = x.LocalTicker,
                IsTrue      = (x.Sedol == x.FSTicker)
            });
            var a2 = a1.Match(x => x.IsTrue);

            var result = a2.ToList();


            //var data = collection.AsQueryable().Where(x => x.Sedol == x.FSTicker).ToList();

            // PushDocumentsToArray(size, f, collection);
            Console.WriteLine("ready");
            Console.ReadLine();
        }
Пример #16
0
        /// <summary>
        /// 获取字段
        /// </summary>
        /// <param name="fieldsExp"></param>
        /// <returns></returns>
        public ProjectionDefinition <T> IncludeFields <T>(Expression <Func <T, object> > fieldsExp) where T : class, new()
        {
            ProjectionDefinitionBuilder <T> projection = Builders <T> .Projection;

            if (fieldsExp == null)
            {
                return(null);
            }
            List <ProjectionDefinition <T> > list = new List <ProjectionDefinition <T> >();
            NewExpression newExpression           = fieldsExp.Body as NewExpression;

            if (newExpression == null || newExpression.Members == null)
            {
                throw new Exception("fieldsExp is invalid expression format, eg: x => new { x.Field1, x.Field2 }");
            }
            foreach (MemberInfo current in newExpression.Members)
            {
                list.Add(projection.Include(current.Name));
            }
            return(projection.Combine(list));
        }
Пример #17
0
        internal static string GetBizFloatUrlPattern(string themeId)
        {
            try
            {
                if (_kitsuneServer == null)
                {
                    InitializeConnection();
                }

                var temp_themeCollection          = _kitsuneDatabase.GetCollection <ProductionKitsuneResource>(MongoConnector.ProductionResorcesCollectionName);
                var temp_productDefinitionBuilder = new ProjectionDefinitionBuilder <ProductionKitsuneResource>();
                var temp_pd = temp_productDefinitionBuilder.Include(x => x._id).Include(x => x.UrlPattern).Include(x => x.IsDefault).Include(x => x.UrlPatternRegex).Include(x => x.IsStatic).Include(s => s.PageType);

                var temp_result = temp_themeCollection.Find(x => x.ProjectId == themeId && x.PageType == Kitsune.Models.Project.KitsunePageType.DETAILS && x.KObject.Contains("business.updates")).Project <ProductionKitsuneResource>(temp_pd)?.ToList();

                if (temp_result != null && temp_result.Count() > 0)
                {
                    return(temp_result.FirstOrDefault().UrlPattern);
                }
                else
                {
                    temp_result = temp_themeCollection.Find(x => x.ProjectId == themeId &&
                                                            (x.UrlPatternRegex.ToLower().Contains("([a-zA-Z0-9\\-\\.,\\%]+)/b-([a-zA-Z0-9\\-\\.,\\%]+)") ||
                                                             x.UrlPatternRegex.ToLower().Contains("([a-zA-Z0-9\\-\\.,\\%]+)/u-([a-zA-Z0-9\\-\\.,\\%]+)") ||
                                                             x.UrlPatternRegex.ToLower().Contains("([a-zA-Z0-9\\-\\.,\\%]+)/u([a-zA-Z0-9\\-\\.,\\%]+)") ||
                                                             (x.UrlPatternRegex.ToLower().Contains("([a-zA-Z0-9\\-\\.,\\%]+)/b([a-zA-Z0-9\\-\\.,\\%]+)")))).Project <ProductionKitsuneResource>(temp_pd)?.ToList();

                    if (temp_result != null && temp_result.Count() > 0)
                    {
                        return(temp_result.FirstOrDefault().UrlPattern);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write($"Exception: GetBizFloatUrlPattern({themeId}) - {ex.ToString()}");
            }

            return(null);
        }
Пример #18
0
        public async Task <dynamic> GetByAuthorId(string userId)
        {
            var userCollection = MongoWrapper.Database.GetCollection <Models.Musician>(nameof(Models.User));

            var userFilterBuilder = new FilterDefinitionBuilder <Models.Musician>();
            var userFilter        = userFilterBuilder.And
                                    (
                userFilterBuilder.Eq(u => u._id, new ObjectId(userId)),
                GeneralUtils.NotDeactivated(userFilterBuilder),
                GeneralUtils.NotDeactivated(userFilterBuilder, m => m.Songs)
                                    );

            var userProjectionBuilder = new ProjectionDefinitionBuilder <Models.Musician>();
            var userProjection        = userProjectionBuilder
                                        .Include(m => m.Songs);

            var user = (await userCollection.FindAsync(userFilter, new FindOptions <Models.Musician>
            {
                Limit = 1,
            })).SingleOrDefault();

            if (user == null)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(new ResponseBody
                {
                    Code = ResponseCode.NotFound,
                    Success = false,
                    Message = "Usuário não encontrado!",
                });
            }

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Success = true,
                Message = "Músicas encontradas com sucesso!",
                Data = user.Songs.Select(ResponseMappingExtensions.BuildSongResponse),
            });
        }
Пример #19
0
        public async Task <dynamic> GetById(string id)
        {
            var postCollection = MongoWrapper.Database.GetCollection <Models.Post>(nameof(Post));

            var postFilterBuilder = new FilterDefinitionBuilder <Models.Post>();
            var postFilter        = postFilterBuilder.And
                                    (
                postFilterBuilder.Eq(u => u._id, new ObjectId(id)),
                GeneralUtils.NotDeactivated(postFilterBuilder)
                                    );

            var postCommentProjectionBuilder = new ProjectionDefinitionBuilder <Models.Post>();
            var postCommentProjection        = postCommentProjectionBuilder.Include(p => p.Comments);

            var post = (await postCollection.FindAsync(postFilter, new FindOptions <Models.Post>
            {
                Limit = 1,
                Projection = postCommentProjection
            })).SingleOrDefault();

            if (post == null)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(new ResponseBody
                {
                    Code = ResponseCode.NotFound,
                    Success = false,
                    Message = "Comment não encontrado!",
                });
            }

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Success = true,
                Message = "Comentários do post retornados com sucesso!",
                Data = post.Comments.Select(c => c.BuildCommentResponse()),
            });
        }
Пример #20
0
        /// <summary>
        /// Get all the Resouces(Styles, Scripts and Assets) details from KitsuneProjects DB
        /// </summary>
        /// <param name="crawlId"></param>
        /// <returns></returns>
        public static ResoucesDetails GetAllTheResourcesOfWebite(string crawlId)
        {
            try
            {
                if (crawlId == null)
                {
                    throw new Exception("CrawlId cannot be Null");
                }
                if (_server == null)
                {
                    InitiateConnection();
                }
                var urlCollection = _kitsuneDB.GetCollection <KitsuneKrawlerStats>(EnvironmentConstants.ApplicationConfiguration.MongoDBCollections.KitsuneKrawlStatsCollection);

                //Filter Defination
                var filterDefinationBuilder = new FilterDefinitionBuilder <KitsuneKrawlerStats>();
                var filterDefination        = filterDefinationBuilder.Where(x => x.ProjectId == crawlId);

                //Projection Defination
                var projectDefinationBuilder = new ProjectionDefinitionBuilder <KitsuneKrawlerStats>();
                ProjectionDefinition <KitsuneKrawlerStats> projectDefination = projectDefinationBuilder.Include(x => x.Assets)
                                                                               .Include(x => x.Scripts)
                                                                               .Include(x => x.Styles)
                                                                               .Include(x => x.Links)
                                                                               .Exclude(x => x._id);

                //Process
                var result = urlCollection.Find(filterDefination)
                             .Project <ResoucesDetails>(projectDefination)
                             .FirstOrDefaultAsync()
                             .Result;
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <dynamic> Post([FromBody] CreateAdvertisementRequest requestBody)
        {
            var userId = new ObjectId(this.GetCurrentUserId());

            var userCollection = MongoWrapper.Database.GetCollection <Models.Contractor>(nameof(Models.User));

            var userFilterBuilder = new FilterDefinitionBuilder <Models.Contractor>();
            var userFilter        = userFilterBuilder.And
                                    (
                GeneralUtils.NotDeactivated(userFilterBuilder),
                userFilterBuilder.Eq(u => u._id, userId)
                                    );

            var userProjectionBuilder = new ProjectionDefinitionBuilder <Models.Contractor>();
            var userProjection        = userProjectionBuilder
                                        .Include(m => m._id)
                                        .Include(m => m.FullName)
                                        .Include(m => m.Avatar)
                                        .Include(m => m.FileBytesLimit)
                                        .Include(m => m.FileBytesOccupied)
                                        .Include("_t");

            var userTask = userCollection.FindAsync(userFilter, new FindOptions <Models.Contractor>
            {
                Limit = 1,
                AllowPartialResults = false,
                Projection          = userProjection
            });

            Models.Contractor user = null;

            List <(FileReference, Func <Task>)> files             = new List <(FileReference, Func <Task>)>();
            Task <(FileReference, Func <Task>)> fileReferenceTask = Task.FromResult <(FileReference, Func <Task>)>((null, () => Task.CompletedTask));

            if (requestBody.Midias != null)
            {
                long totalSize = 0;
                foreach (MidiaRequest midiaRequest in requestBody.Midias)
                {
                    if (midiaRequest.Id != null)
                    {
                        fileReferenceTask = GeneralUtils.GetFileForReferenceToken
                                            (
                            MongoWrapper,
                            midiaRequest.Id,
                            userId
                                            );
                        var(fileReference, expirer) = await fileReferenceTask;
                        totalSize += fileReference.FileInfo.Size;
                        files.Add((fileReference, expirer));
                    }
                }
                user = (await userTask).Single();
                GeneralUtils.CheckSizeForUser(totalSize, user.FileBytesOccupied, user.FileBytesLimit);
            }

            var postCollection = MongoWrapper.Database.GetCollection <Models.Advertisement>(nameof(Models.Advertisement));

            var creationDate = DateTime.UtcNow;

            var ad = new Models.Advertisement
            {
                _id            = ObjectId.GenerateNewId(creationDate),
                Title          = requestBody.Titulo,
                Text           = requestBody.Descricao,
                FileReferences = files.Select(f => f.Item1).ToList(),
                Position       = requestBody.Coordenada == null ? null : new GeoJsonPoint <GeoJson3DGeographicCoordinates>(requestBody.Coordenada.ToGeoJsonCoordinate()),
                Poster         = user ?? (await userTask).Single(),
            };

            await postCollection.InsertOneAsync(ad);

            files.AsParallel().ForAll(async f => await f.Item2());

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Data = ad._id,
                Message = "Postagem criada com sucesso!",
                Success = true
            });
        }
Пример #22
0
        [AllowAnonymous] // No authorization required for Login Request, obviously
        public async Task <dynamic> Post([FromBody] LoginRequest requestBody)
        {
            this.EnsureModelValidation();

            var collection = MongoWrapper.Database.GetCollection <Models.User>(nameof(User));

            var projectionBuilder = new ProjectionDefinitionBuilder <Models.User>();
            var projection        = projectionBuilder
                                    .Include(u => u.Password)
                                    .Include(u => u.Avatar)
                                    .Include(u => u.FullName)
                                    .Include("_t");

            var filterBuilder = new FilterDefinitionBuilder <Models.User>();
            var filter        = filterBuilder.And(
                filterBuilder.Eq(u => u.Email, requestBody.Email),
                GeneralUtils.NotDeactivated(filterBuilder)
                );

            var user = (await collection.FindAsync(filter, new FindOptions <Models.User>
            {
                Limit = 1,
                Projection = projection,
            })).SingleOrDefault();

            var responseBody = new ResponseBody();

            if (user == null)
            {
                responseBody.Code    = ResponseCode.NotFound;
                responseBody.Success = false;
                responseBody.Message = "Usuário não encontrado!";
                Response.StatusCode  = (int)HttpStatusCode.Unauthorized;
                return(responseBody);
            }

            var passwordMatchesTask = Task.Run(() => Encryption.Compare(requestBody.Password, user.Password));

            var(creationDate, expiryDate, token) = await AuthenticationUtils.GenerateJwtTokenForUser(user._id.ToString(), TokenConfigurations, SigningConfigurations);

            bool passwordMatches = await passwordMatchesTask;

            if (!passwordMatches)
            {
                responseBody.Message = "Senha incorreta!";
                responseBody.Code    = ResponseCode.IncorrectPassword;
                responseBody.Success = false;
                Response.StatusCode  = (int)HttpStatusCode.Unauthorized;
                return(responseBody);
            }

            responseBody.Message = "Login efetuado com sucesso!";
            responseBody.Code    = ResponseCode.GenericSuccess;
            responseBody.Success = true;
            responseBody.Data    = new
            {
                user = new
                {
                    user.Kind,
                    user.Avatar,
                    user.FullName,
                },
                tokenData = new
                {
                    created     = creationDate,
                    expiration  = expiryDate,
                    accessToken = token,
                }
            };
            Response.StatusCode = (int)HttpStatusCode.OK;
            return(responseBody);
        }
        /// <summary>
        /// Webhook update
        /// </summary>
        /// <param name="instaMojoHookResponse"></param>
        public void UpdateWebHook(InstamojoWebhookRequestModel instaMojoHookResponse)
        {
            try
            {
                if (_server == null)
                {
                    InitiateConnection();
                }

                //update the InstamojoTransactionLog database
                var collection = _kitsuneDB.GetCollection <InstamojoTransactionLog>("InstamojoTransactionLogs");
                var udb        = new UpdateDefinitionBuilder <InstamojoTransactionLog>();
                var update     = udb.Set(x => x.status, instaMojoHookResponse.status)
                                 .Set(x => x.fees, instaMojoHookResponse.fees)
                                 .Set(x => x.mac, instaMojoHookResponse.mac)
                                 .Set(x => x.currency, instaMojoHookResponse.currency)
                                 .Set(x => x.shorturl, instaMojoHookResponse.shorturl)
                                 .Set(x => x.payment_id, instaMojoHookResponse.payment_id);
                var result = collection.UpdateOne(x => x.payment_request_id == instaMojoHookResponse.payment_request_id, update, new UpdateOptions()
                {
                    IsUpsert = true
                });

                string walletBalance = null;


                var userCollection = _kitsuneDB.GetCollection <UserModel>("users");
                var pdb            = new ProjectionDefinitionBuilder <UserModel>();
                var pd             = pdb.Include(x => x.Wallet).Include(x => x.Email).Include(x => x.UserName);
                //get user details
                var user = userCollection.Find(x => x.UserName == instaMojoHookResponse.buyer).Project <UserModel>(pd).FirstOrDefaultAsync().Result;

                //if successfully credited then update the wallet
                if (instaMojoHookResponse.status.ToLower() == "credit")
                {
                    //update the wallet
                    if (user != null)
                    {
                        var    builder     = new UpdateDefinitionBuilder <UserModel>();
                        var    currentTime = DateTime.Now;
                        double amount      = Double.Parse(instaMojoHookResponse.amount);

                        //if wallet is not present then create one
                        if (user.Wallet != null)
                        {
                            user.Wallet.Balance  += amount;
                            user.Wallet.UpdatedOn = currentTime;
                        }
                        else if (user.Wallet == null)
                        {
                            user.Wallet = new Kitsune.Models.Wallet {
                                Balance = amount, UpdatedOn = DateTime.Now
                            }
                        }
                        ;

                        userCollection.UpdateOne((x => x.UserName == instaMojoHookResponse.buyer), builder.Set(x => x.Wallet, user.Wallet));
                        walletBalance = user.Wallet.Balance.ToString();

                        //wallet stats
                        var         walletCollection = _kitsuneDB.GetCollection <WalletStats>(EnvConstants.Constants.WalletStats);
                        WalletStats walletStats      = new WalletStats();
                        walletStats.Amount    = amount;
                        walletStats.IsAdded   = true;
                        walletStats.Reason    = "Money Added";
                        walletStats.UserEmail = user.Email;
                        walletStats.CreatedOn = DateTime.Now;
                        walletCollection.InsertOneAsync(walletStats);

                        //KitsuneConversionAPI kitsuneApi = new KitsuneConversionAPI();
                        EmailHelper emailHelper = new EmailHelper();
                        Dictionary <string, string> optionalParameters = new Dictionary <string, string>();
                        optionalParameters.Add(EnvConstants.Constants.EmailParam_AmountAdded, walletStats.Amount.ToString());
                        optionalParameters.Add(EnvConstants.Constants.EmailParam_WalletAmount, (user.Wallet.Balance - user.Wallet.UnbilledUsage).ToString());
                        optionalParameters.Add(EnvConstants.Constants.EmailParam_PaymentId, instaMojoHookResponse.payment_id);
                        optionalParameters.Add(EnvConstants.Constants.EmailParam_PaymentPartyName, instaMojoHookResponse.buyer_name);
                        //SendKitsuneConvertEmailRequestModel emailcommand = new SendKitsuneConvertEmailRequestModel() { EmailID = user.Email, UserName = user.UserName, MailType = MailType.Payment_Success, Attachments = null, OptionalParams = optionalParameters };
                        //kitsuneApi.SendKitsuneConvertEmail(emailCommand);
                        emailHelper.SendGetKitsuneEmail(user.Email,
                                                        user.UserName,
                                                        MailType.PAYMENT_SUCCESS,
                                                        null,
                                                        optionalParameters);
                    }
                    else
                    {
                        throw new Exception("Couldn't fetch user details");
                    }
                }
                else
                {
                    //KitsuneConversionAPI kitsuneApi = new KitsuneConversionAPI();
                    EmailHelper emailHelper = new EmailHelper();
                    Dictionary <string, string> optionalParameters = new Dictionary <string, string>();
                    optionalParameters.Add(EnvConstants.Constants.EmailParam_PaymentId, instaMojoHookResponse.payment_id);
                    //SDK.Models.SendKitsuneConvertEmailCommand emailCommand = new SDK.Models.SendKitsuneConvertEmailCommand() { EmailID = user.Email, UserName = user.UserName, MailType = SDK.Models.MailType.Payment_Error, Attachments = null, OptionalParams = optionalParameters };
                    //kitsuneApi.SendKitsuneConvertEmail(emailCommand);
                    emailHelper.SendGetKitsuneEmail(user.Email,
                                                    user.UserName,
                                                    MailType.PAYMENT_ERROR,
                                                    null,
                                                    optionalParameters);
                }
                //update the PaymentTransactionLog database
                var mojoLogCollection = _kitsuneDB.GetCollection <PaymentTransactionLog>("PaymentTransactionLogs");
                var mojoUdb           = new UpdateDefinitionBuilder <PaymentTransactionLog>();
                var mojoUpdate        = mojoUdb.Set(x => x.Status, instaMojoHookResponse.status)
                                        .Set(x => x.UpdatedOn, DateTime.Now);
                mojoLogCollection.UpdateOne(x => x.PaymentRequestId == instaMojoHookResponse.payment_request_id, mojoUpdate, new UpdateOptions()
                {
                    IsUpsert = true
                });
            }
            catch (Exception ex)
            {
                //save the log
            }
        }
Пример #24
0
 public IDocumentProjectionBuilder Include(string property)
 {
     _projections.Add(InternalBuilder.Include(property));
     return(this);
 }
Пример #25
0
        public static async Task <KitsuneDomainDetails> GetCustomerDetailsFromDomainAsync(string domainUrl, KitsuneRequestUrlType kitsuneRequestUrlType = KitsuneRequestUrlType.PRODUCTION)
        {
            try
            {
                if (_server == null)
                {
                    InitiateConnection();
                }
                if (String.IsNullOrEmpty(domainUrl))
                {
                    return(null);
                }

                var websiteCollection    = _kitsuneDB.GetCollection <KitsuneWebsiteCollection>(KLM_Constants.KitsuneWebsiteCollection);
                var websiteDNSCollection = _kitsuneDB.GetCollection <WebsiteDNSInfo>(KLM_Constants.KitsuneDNSCollection);

                var result        = new KitsuneDomainDetails();
                var tempDomainUrl = domainUrl.ToUpper();

                var filter = (Builders <KitsuneWebsiteCollection> .Filter.Eq(document => document.WebsiteUrl, tempDomainUrl)) &
                             Builders <KitsuneWebsiteCollection> .Filter.Eq(document => document.IsActive, true);

                if (kitsuneRequestUrlType == KitsuneRequestUrlType.DEMO || kitsuneRequestUrlType == KitsuneRequestUrlType.PREVIEW)
                {
                    filter = Builders <KitsuneWebsiteCollection> .Filter.Eq(document => document._id, domainUrl);
                }


                var customer = websiteCollection.Find(filter, new FindOptions {
                    MaxTime = TimeSpan.FromMilliseconds(KLM_Constants.MongoQueryMaxtimeOut)
                }).FirstOrDefault();
                if (customer != null)
                {
                    result.Domain      = customer.WebsiteUrl;
                    result.ProjectId   = customer.ProjectId;
                    result.Version     = customer.KitsuneProjectVersion;
                    result.CustomerId  = customer._id;
                    result.WebsiteTag  = customer.WebsiteTag;
                    result.DeveloperId = customer.DeveloperId;
                    result.ClientId    = customer.ClientId;

                    try
                    {
                        var filterDNS = Builders <WebsiteDNSInfo> .Filter.Eq(document => document.DomainName, customer.WebsiteUrl)
                                        & Builders <WebsiteDNSInfo> .Filter.Eq(document => document.DNSStatus, DNSStatus.Active);

                        var dnsProjectionBuilder = new ProjectionDefinitionBuilder <WebsiteDNSInfo>();
                        var dnsProjection        = dnsProjectionBuilder.Include(x => x.WebsiteId).Include(x => x.IsSSLEnabled)
                                                   .Include(x => x._id);

                        var dnsInfo = websiteDNSCollection.Find(filterDNS,
                                                                new FindOptions {
                            MaxTime = TimeSpan.FromMilliseconds(KLM_Constants.MongoQueryMaxtimeOut)
                        }).Project <WebsiteDNSInfo>(dnsProjection)
                                      .Sort(Builders <WebsiteDNSInfo> .Sort.Descending(x => x.CreatedOn))
                                      ?.FirstOrDefault();

                        if (dnsInfo == null)
                        {
                            Console.WriteLine($"No active DNS record found for {tempDomainUrl}");
                            throw new Exception($"No active DNS record found for {tempDomainUrl}");
                        }

                        if (dnsInfo.IsSSLEnabled)
                        {
                            result.isSSLEnabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    #region Handle .getkitsune.com subdomain redirection

                    var filterDNS = Builders <WebsiteDNSInfo> .Filter.Eq(document => document.DomainName, tempDomainUrl)
                                    & Builders <WebsiteDNSInfo> .Filter.Eq(document => document.DNSStatus, DNSStatus.Active);

                    var dnsProjectionBuilder = new ProjectionDefinitionBuilder <WebsiteDNSInfo>();

                    var dnsInfo = websiteDNSCollection.Find(filterDNS, new FindOptions {
                        MaxTime = TimeSpan.FromMilliseconds(KLM_Constants.MongoQueryMaxtimeOut)
                    }).FirstOrDefault();
                    if (dnsInfo != null)
                    {
                        filter = (Builders <KitsuneWebsiteCollection> .Filter.Eq(document => document._id, dnsInfo.WebsiteId));

                        //customerDetails = CommonKitsuneDBGetQueryDetailsForAnyCollection<KitsuneWebsiteCollection>(Identifier_Constants.KitsuneWebsiteCollection, filter, projec, null, 1).FirstOrDefault();
                        customer = await websiteCollection.Find(filter, new FindOptions { MaxTime = TimeSpan.FromMilliseconds(KLM_Constants.MongoQueryMaxtimeOut) }).FirstOrDefaultAsync();

                        try
                        {
                            filterDNS = Builders <WebsiteDNSInfo> .Filter.Eq(document => document.DomainName, customer.WebsiteUrl)
                                        & Builders <WebsiteDNSInfo> .Filter.Eq(document => document.DNSStatus, DNSStatus.Active);

                            var newDNSInfo = websiteDNSCollection.Find(filterDNS, new FindOptions {
                                MaxTime = TimeSpan.FromMilliseconds(KLM_Constants.MongoQueryMaxtimeOut)
                            })
                                             .Sort(Builders <WebsiteDNSInfo> .Sort.Descending(x => x.CreatedOn))
                                             ?.FirstOrDefault();

                            if (customer != null)
                            {
                                result.Domain       = tempDomainUrl;
                                result.ProjectId    = customer.ProjectId;
                                result.Version      = customer.KitsuneProjectVersion;
                                result.CustomerId   = customer._id;
                                result.RedirectUrl  = customer.WebsiteUrl;
                                result.IsRedirect   = true;
                                result.WebsiteTag   = customer.WebsiteTag;
                                result.DeveloperId  = customer.DeveloperId;
                                result.ClientId     = customer.ClientId;
                                result.isSSLEnabled = newDNSInfo.IsSSLEnabled;
                            }
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        return(null);
                    }
                    #endregion
                }

                //TO-Do update to BasePlugin
                if ((kitsuneRequestUrlType == KitsuneRequestUrlType.DEMO || kitsuneRequestUrlType == KitsuneRequestUrlType.PREVIEW) || (customer != null && !customer.IsActive && customer.WebsiteUrl.ToLower().EndsWith("getkitsune.com")))
                {
                    result.IsRedirect = false;
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #26
0
        public async Task <dynamic> CommentById(string id, [FromBody] CreateCommentRequest requestBody)
        {
            var postCollection = MongoWrapper.Database.GetCollection <Models.Post>(nameof(Models.Post));

            var postFilterBuilder = new FilterDefinitionBuilder <Models.Post>();
            var postFilter        = postFilterBuilder.And
                                    (
                postFilterBuilder.Eq(u => u._id, new ObjectId(id)),
                GeneralUtils.NotDeactivated(postFilterBuilder)
                                    );

            var userId = new ObjectId(this.GetCurrentUserId());

            var userCollection = MongoWrapper.Database.GetCollection <Models.User>(nameof(Models.User));

            var userFilterBuilder = new FilterDefinitionBuilder <Models.User>();
            var userFilter        = userFilterBuilder.And(
                GeneralUtils.NotDeactivated(userFilterBuilder),
                userFilterBuilder.Eq(user => user._id, userId)
                );

            var userProjectionBuilder = new ProjectionDefinitionBuilder <Models.User>();
            var userProjection        = userProjectionBuilder
                                        .Include(m => m._id)
                                        .Include(m => m.FullName)
                                        .Include(m => m.Avatar)
                                        .Include("_t");

            var userTask = userCollection.FindAsync(userFilter, new FindOptions <Models.User>
            {
                Limit = 1,
                AllowPartialResults = false,
                Projection          = userProjection
            });

            Models.Comment newComment = new Models.Comment
            {
                _id       = ObjectId.GenerateNewId(),
                Commenter = (await userTask).Single(),
                Likes     = new HashSet <ObjectId>(),
                Text      = requestBody.Comentario,
            };

            var postUpdateBuilder = new UpdateDefinitionBuilder <Models.Post>();
            var postUpdate        = postUpdateBuilder.Push(p => p.Comments, newComment);

            var updateResult = await postCollection.UpdateOneAsync(
                postFilter,
                postUpdate
                );

            if (updateResult.MatchedCount == 0)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(new ResponseBody
                {
                    Code = ResponseCode.NotFound,
                    Success = false,
                    Message = "Post não encontrado!",
                });
            }

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Success = true,
                Message = "Comentário criado e vinculado com sucesso!",
                Data = newComment._id,
            });
        }
Пример #27
0
        private static Task StartRadioFeeder(RadioCastServer radioCastServer, MongoWrapper mongoWrapper)
        {
            var userCollection = mongoWrapper.Database.GetCollection <Models.Musician>(nameof(Models.User));

            var songSortBuilder = new SortDefinitionBuilder <ProjectedMusicianSong>();
            var songSort        = songSortBuilder
                                  .Descending(nameof(ProjectedMusicianSong.Score));

            var userFilterBuilder = new FilterDefinitionBuilder <Models.Musician>();
            var userFilter        = userFilterBuilder.And
                                    (
                GeneralUtils.NotDeactivated(userFilterBuilder),
                userFilterBuilder.AnyEq("_t", nameof(Models.Musician))
                                    );

            var songFilterBuilder = new FilterDefinitionBuilder <ProjectedMusicianSong>();
            var songFilter        = songFilterBuilder.And
                                    (
                GeneralUtils.NotDeactivated(songFilterBuilder, s => s.Song),
                songFilterBuilder.Eq(s => s.Song.RadioAuthorized, true),
                songFilterBuilder.Eq(s => s.Song.Original, true)
                                    );

            var projectionBuilder = new ProjectionDefinitionBuilder <Models.Musician>();
            var projection        = projectionBuilder.Include(m => m.FullName).Include(m => m.Songs);

            var fsBucket = new GridFSBucket <ObjectId>(mongoWrapper.Database);

            var trackHistory = new List <(IAudioSource, ProjectedMusicianSong)>();

            var onTrackChangedTE = new ManualResetEvent(true);

            radioCastServer.OnTrackChanged += async(s, e) =>
            {
                List <(IAudioSource, ProjectedMusicianSong)> myTrackHistory;
                lock (trackHistory)
                {
                    myTrackHistory = trackHistory.ToList();
                }

                RadioInfoController.CurrentSong = myTrackHistory.Where(th => th.Item1.Equals(e.NewTrack)).Select(th => th.Item2).LastOrDefault();
                LOGGER.Info("Now playing: {}", JsonConvert.SerializeObject(RadioInfoController.CurrentSong));

                onTrackChangedTE.Set();

                if (e.OldTrack == null)
                {
                    return;
                }

                var oldTrack      = myTrackHistory.Where(th => th.Item1.Equals(e.OldTrack)).Select(th => th.Item2).LastOrDefault();
                var oldMusicianId = oldTrack._id;
                var oldTrackId    = oldTrack.Song._id;

                var musSongFilterBuilder = new FilterDefinitionBuilder <Models.Musician>();

                var musSongFilter = musSongFilterBuilder.And
                                    (
                    musSongFilterBuilder.Eq(m => m._id, oldMusicianId),
                    musSongFilterBuilder.ElemMatch(m => m.Songs, sg => sg._id == oldTrackId)
                                    );
                var musSongUpdate = new UpdateDefinitionBuilder <Models.Musician>()
                                    .Inc($"{nameof(Models.Musician.Songs)}.$.{nameof(Song.TimesPlayedRadio)}", 1);

                await userCollection.UpdateOneAsync(musSongFilter, musSongUpdate);

                // Remove oldest, only keep 5 in history
                if (myTrackHistory.Count > 5)
                {
                    lock (trackHistory)
                    {
                        trackHistory.RemoveAt(0);
                    }
                }
            };

            return(Task.Run(async() =>
            {
                while (true)
                {
                    List <(IAudioSource, ProjectedMusicianSong)> myTrackHistory;
                    lock (trackHistory)
                    {
                        myTrackHistory = trackHistory.ToList();
                    }

                    var lookupStageRandomArr = $@"
                    {{
                        $lookup:
                        {{
                            from: ""randomNumbers"",
                            pipeline:
                            [
                                {{ $sample: {{ size: 2 }} }}
                            ],
                            as: ""RandomArr""
                        }}
                    }}
                    ";

                    // OK Vezes totais que a música foi tocada * 0.5
                    // OK Vezes totais que a música foi tocada na rádio * -1
                    // OK Se música está presente na lista das últimas 5 tocadas, -100
                    // OK Se o autor da música está presente na lista das últimas 5 tocadas, -50
                    // OK Pontuação aleatória para cada música, entre - 10 e + 10
                    // OK Número de dias desde o cadastramento da música * -1
                    // OK   Há uma chance de 5% de multiplicar a pontuação resultante por -1 (efeito nostalgia)

                    var scoreStage = $@"
                    {{
                        $addFields:
                        {{
                            ""Score"":
                            {{
                                $add:
                                [
                                    {{
                                        $multiply: [ ""$Song.timesPlayed"", 0.5 ]
                                    }},
                                    {{
                                        $multiply: [ ""$Song.timesPlayedRadio"", -1 ]
                                    }},
                                    {{
                                        $cond:
                                        {{
                                            if:
                                            {{
                                                $in: [ ""$_id"", [ {myTrackHistory.Select(th => $"ObjectId(\"{th.Item2._id.ToString()}\")").DefaultIfEmpty("").Aggregate((s1, s2) => $"{s1.TrimEnd(',')},{s2.TrimEnd(',')},").TrimEnd(',')} ] ]
                                            }},
                                            then: -50,
                                            else: 0
                                        }}
                                    }},
                                    {{
                                        $cond:
                                        {{
                                            if:
                                            {{
                                                $in: [ ""$Song._id"", [ {myTrackHistory.Select(th => $"ObjectId(\"{th.Item2.Song._id.ToString()}\")").DefaultIfEmpty("").Aggregate((s1, s2) => $"{s1.TrimEnd(',')},{s2.TrimEnd(',')},").TrimEnd(',')} ] ]
                                            }},
                                            then: -100,
                                            else: 0
                                        }}
                                    }},
                                    {{
                                        $add:
                                        [ 
                                            {{
                                                $multiply:
                                                [
                                                    {{ $toDecimal: {{ $arrayElemAt: [""$RandomArr.decimal"", 0] }} }},
                                                    21
                                                ]
                                            }}, 
                                            -10
                                        ]
                                    }},
                                    {{
                                        $multiply:
                                        [
                                            {{
                                                $divide:
                                                [
                                                    {{
                                                        $subtract:
                                                        [
                                                            {{ $toDate: ""{DateTime.UtcNow.ToString("o")}"" }},
                                                            {{ $toDate: ""$Song._id"" }}
                                                        ]
                                                    }},
                                                    NumberLong(""86400000"")
                                                ]
                                            }},
                                            {{
                                                $cond:
                                                {{
                                                    if:
                                                    {{
                                                        $gt:
                                                        [
                                                            {{ $toDecimal: {{ $arrayElemAt: [""$RandomArr.decimal"", 1] }} }},
                                                            NumberDecimal(""0.1"")
                                                        ]
                                                    }},
                                                    then: -1,
                                                    else: 1
                                                }}
                                            }}
                                        ]
                                    }}
                                ]
                            }}
                        }}
                    }}";

                    LOGGER.Info("Score stage generated MongoDB query: {}", scoreStage);

                    var pipeline = PipelineDefinitionBuilder
                                   .For <Models.Musician>()
                                   .Match(userFilter)
                                   .Unwind(m => m.Songs, new AggregateUnwindOptions <Models.Musician>
                    {
                        PreserveNullAndEmptyArrays = false,
                        IncludeArrayIndex = null,
                    })
                                   .Project(m => new ProjectedMusicianSong
                    {
                        _id = m._id,
                        Song = (Song)m.Songs,
                        Score = 1,
                    })
                                   .Match(songFilter)
                                   .AppendStage <Musician, ProjectedMusicianSong, ProjectedMusicianSong>(lookupStageRandomArr)
                                   .AppendStage <Musician, ProjectedMusicianSong, ProjectedMusicianSong>(scoreStage)
                                   .Sort(songSort)
                                   .Limit(1);

                    if (LOGGER.IsDebugEnabled)
                    {
                        LOGGER.Debug("Pipeline generated MongoDB query for song: {}", pipeline.ToString());
                    }

                    var findTask = userCollection.AggregateAsync(pipeline, new AggregateOptions
                    {
                        AllowDiskUse = true,
                        BatchSize = 1,
                        UseCursor = true,
                        Comment = "Radio Aggregate Query",
                        TranslationOptions = new ExpressionTranslationOptions
                        {
                            StringTranslationMode = AggregateStringTranslationMode.CodePoints
                        }
                    });

                    var findResult = await findTask;
                    var firstSong = findResult.SingleOrDefault();
                    // If no songs, wait a minute before checking again
                    // Mostly not to strain the CPU on development environments
                    if (firstSong?.Song == null)
                    {
                        Thread.Sleep(TimeSpan.FromMinutes(1));
                        continue;
                    }
                    LOGGER.Info("Next selected song: {}", JsonConvert.SerializeObject(firstSong));
                    var audioRef = firstSong.Song.AudioReference;
                    var gridId = audioRef._id;
                    var fileStreamTask = fsBucket.OpenDownloadStreamAsync(gridId, new GridFSDownloadOptions
                    {
                        Seekable = true,
                        CheckMD5 = false,
                    });
                    var audioSource = new Mp3FileAudioSource(await fileStreamTask, firstSong.Song.Name);
                    // Wait for the radio to need more songs before we add the track we have on our hands
                    while (radioCastServer.TrackCount > 1)
                    {
                        onTrackChangedTE.WaitOne();
                        onTrackChangedTE.Reset();
                    }
                    lock (trackHistory)
                    {
                        trackHistory.Add((audioSource, firstSong));
                    }
                    radioCastServer.AddTrack(audioSource);
                }
            }));
        }