public ReportController(MongoWrapper mongoWrapper, SmtpConfiguration smtpConfiguration, ILogger <ReportController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(ReportController)} Constructor Invoked");
     MongoWrapper      = mongoWrapper;
     SmtpConfiguration = smtpConfiguration;
 }
 public RenewTokenController(MongoWrapper mongoWrapper, TokenConfigurations tokenConfigurations, SigningConfigurations signingConfigurations, ILogger <RenewTokenController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(RenewTokenController)} Constructor Invoked");
     TokenConfigurations   = tokenConfigurations;
     SigningConfigurations = signingConfigurations;
     MongoWrapper          = mongoWrapper;
 }
 public RegisterUserControllerBase(MongoWrapper mongoWrapper, SmtpConfiguration smtpConfiguration, TokenConfigurations tokenConfigurations, SigningConfigurations signingConfigurations, ILogger <RegisterUserControllerBase <TBody> > logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(RegisterUserControllerBase<TBody>)} Constructor Invoked");
     MongoWrapper          = mongoWrapper;
     SmtpConfiguration     = smtpConfiguration;
     TokenConfigurations   = tokenConfigurations;
     SigningConfigurations = signingConfigurations;
 }
        public MongoWrapperTests()
        {
            _mockRepository = new MockRepository(MockBehavior.Strict);
            _mongoSettings  = _mockRepository.Create <MongoSettings>("some:connection", "database");
            _mongoClient    = _mockRepository.Create <IMongoClient>();
            _mongoWrapper   = new MongoWrapper(_mongoSettings.Object, _mongoClient.Object);

            _mongoClient.Setup(x => x.GetDatabase(_mongoSettings.Object.Database, null)).Returns(It.IsAny <IMongoDatabase>());
        }
        //
        // GET: /Entregas/
        public ActionResult Index(string id)
        {
            // Get remarks by id
            var caixaAzul = MongoWrapper.GetDatabase().
                            GetCollection("caixaAzul").
                            FindOneByIdAs <CaixaAzul>(ObjectId.Parse(id));

            return(View(caixaAzul));
        }
 public LoginController(MongoWrapper mongoWrapper, ServerInfo serverInfo, TokenConfigurations tokenConfigurations, SigningConfigurations signingConfigurations, ILogger <LoginController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(LoginController)} Constructor Invoked");
     MongoWrapper          = mongoWrapper;
     ServerInfo            = serverInfo;
     TokenConfigurations   = tokenConfigurations;
     SigningConfigurations = signingConfigurations;
 }
        //
        // GET: /CaixaAzul/

        public ActionResult Index()
        {
            // Get all users by sorting by createdate
            var caixaAzul = MongoWrapper.GetDatabase().
                            GetCollection("caixaAzul").
                            FindAll().
                            SetSortOrder(SortBy.Descending("createdate"));

            return(View(caixaAzul));
        }
        public ActionResult Edit(string id)
        {
            // Obtain id compatible with MongoDB to query
            var objectId = ObjectId.Parse(id);

            // Get user by id
            var caixaAzul = MongoWrapper.GetDatabase().
                            GetCollection("caixaAzul").
                            FindOneByIdAs <CaixaAzul>(ObjectId.Parse(id));

            return(View(caixaAzul));
        }
示例#9
0
        /// <summary>
        /// Creates the <see cref="MongoWrapper"/> using the provided configuration.
        /// </summary>
        /// <param name="config">The configuration parameters for MongoDB.</param>
        /// <returns>The wrapper class for MongoDB</returns>
        private static MongoWrapper CreateMongoWrapper(MongodbConfiguration config)
        {
            LOGGER.Info("Connecting to MongoDB...");
            MongoWrapper mongoWrapper;

            try
            {
                mongoWrapper = new MongoWrapper(config.MongoConnectionString, config.MongoDatabase);
            }
            catch (Exception e)
            {
                throw new ApplicationException("Error while connecting to MongoDB", e);
            }
            return(mongoWrapper);
        }
        public ActionResult Edit(string id, CaixaAzul caixaAzulToEdit)
        {
            // Get user collection reference
            var caixaAzulDB = MongoWrapper.GetDatabase().GetCollection("caixaAzul");

            // Update user by id
            var caixaAzul = caixaAzulDB.FindOneById(ObjectId.Parse(id));

            caixaAzul["numeroCaixa"] = caixaAzulToEdit.numeroCaixa;
            caixaAzul["cnpjCD"]      = caixaAzulToEdit.cnpjCD;

            // Update user object
            caixaAzulDB.Save(caixaAzul);

            return(RedirectToAction("Index"));
        }
        public void InsertMockCaixaAzul_2()
        {
            System.Diagnostics.Debug.WriteLine("Testing Inser Mock");
            int    numCaixa     = 17;
            string cnpjProvider = "22222222222222";
            // Get user collection reference
            var caixaAzulDb = MongoWrapper.GetDatabase().GetCollection("caixaAzul");

            // Create BsonDocument object for new user
            var caixaAzul = new BsonDocument();

            caixaAzul["numeroCaixa"] = numCaixa;
            caixaAzul["cnpjCD"]      = cnpjProvider;
            // Insert new user object to collection
            caixaAzulDb.Insert(caixaAzul);
        }
        public ActionResult New(string id, CaixaAzul caixaAzulToEdit)
        {
            // Get user collection reference
            var caixaAzulDb = MongoWrapper.GetDatabase().GetCollection("caixaAzul");

            // Create BsonDocument object for new user
            var caixaAzul = new BsonDocument();

            caixaAzul["numeroCaixa"] = caixaAzulToEdit.numeroCaixa;
            caixaAzul["cnpjCD"]      = caixaAzulToEdit.cnpjCD;
            //caixaAzul["entrega"] = caixaAzulToEdit.entrega;
            //CaixaAzul["createdate"] = DateTime.Now;

            // Insert new user object to collection
            caixaAzulDb.Insert(caixaAzul);

            return(RedirectToAction("Index"));
        }
示例#13
0
        /// <summary>
        /// The actual main logic of the application, which loads the configuration, creates the
        /// connection with MongoDB, and calls <see cref="StartServerAsync(SharedData)"/> to start the server.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static async Task <int> WrappedMain(string[] args)
        {
            LOGGER.Info("Starting the Application");

            string configPath          = args.ElementAtOrDefault(0);
            ServerConfiguration config = GeneralUtils.ReadConfiguration(configPath);
            string hostUri             = $"http://{config.Listening.Address}:{config.Listening.Port}{config.Listening.BasePath}";
            var    serverInfo          = new ServerInfo(configPath, hostUri);

            MongoWrapper mongoWrapper = CreateMongoWrapper(config.Mongodb);

            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            LOGGER.Info("Entering main program logic");

            await StartServer(config, serverInfo, mongoWrapper);

            LOGGER.Info("Exiting program");

            return(0);
        }
        public ActionResult Index(string id, string codEntrega, string faturado)
        {
            var caixaAzul    = MongoWrapper.GetDatabase().GetCollection("caixaAzul");
            var caixaAzulOne = caixaAzul.FindOneById(ObjectId.Parse(id));

            var entrega = new BsonDocument().
                          Add("codigoEntrega", codEntrega).
                          Add("faturado", faturado);

            if (caixaAzulOne.Contains("entregas"))
            {
                caixaAzulOne["entregas"].AsBsonArray.Add(BsonValue.Create(entrega));
            }
            else
            {
                caixaAzulOne["entregas"] = new BsonArray().Add(BsonValue.Create(entrega));
            }

            caixaAzul.Save(caixaAzulOne);

            return(RedirectToAction("Index", new { id = id }));
        }
示例#15
0
 public RetrieveSongController(MongoWrapper mongoWrapper, ILogger <RetrieveSongController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(RetrieveSongController)} Constructor Invoked");
     MongoWrapper = mongoWrapper;
 }
 public CreateAdvertisementController(MongoWrapper mongoWrapper, ILogger <CreateAdvertisementController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(CreateAdvertisementController)} Constructor Invoked");
     MongoWrapper = mongoWrapper;
 }
示例#17
0
 public ConfirmEmailController(MongoWrapper mongoWrapper, ILogger <ConfirmEmailController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(ConfirmEmailController)} Constructor Invoked");
     MongoWrapper = mongoWrapper;
 }
示例#18
0
 public LikePostController(MongoWrapper mongoWrapper, ILogger <LikePostController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(LikePostController)} Constructor Invoked");
     MongoWrapper = mongoWrapper;
 }
示例#19
0
 public ModifySongController(MongoWrapper mongoWrapper, ILogger <ModifySongController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(ModifySongController)} Constructor Invoked");
     MongoWrapper = mongoWrapper;
 }
示例#20
0
 public RegisterMusicianController(MongoWrapper mongoWrapper, SmtpConfiguration smtpConfiguration, TokenConfigurations tokenConfigurations, SigningConfigurations signingConfigurations, ILogger <RegisterMusicianController> logger) : base(mongoWrapper, smtpConfiguration, tokenConfigurations, signingConfigurations, logger)
 {
 }
示例#21
0
 public UploadResourceController(MongoWrapper mongoWrapper, ILogger <UploadResourceController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(UploadResourceController)} Constructor Invoked");
     MongoWrapper = mongoWrapper;
 }
 public IncSongCounterController(MongoWrapper mongoWrapper, ILogger <IncSongCounterController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(IncSongCounterController)} Constructor Invoked");
     MongoWrapper = mongoWrapper;
 }
示例#23
0
        private static (Task task, IWebHost host) StartHost(ServerConfiguration serverConfig, ServerInfo serverInfo, MongoWrapper mongoWrapper)
        {
            IWebHost host = BuildHost(serverConfig, serverInfo, mongoWrapper);

            LOGGER.Info("Starting HTTP Host...");
            var hostTask = host.RunAsync();

            LOGGER.Info("HTTP host is running on {}", serverInfo.HostUri);
            return(hostTask, host);
        }
示例#24
0
 private static IWebHost BuildHost(ServerConfiguration serverConfig, ServerInfo serverInfo, MongoWrapper mongoWrapper)
 {
     return(new WebHostBuilder()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseWebRoot(Path.Combine(Directory.GetCurrentDirectory(), "webroot"))
            .SuppressStatusMessages(true)
            .UseEnvironment(EnvironmentName.Development)
            .CaptureStartupErrors(false)
            .ConfigureLogging(logging =>
     {
         logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
     })
            .UseNLog(NLogAspNetCoreOptions.Default)
            .UseKestrel((builderContext, options) =>
     {
         // Configure Kestrel Options and Builder Context here
         options.AddServerHeader = false;
         // Set because Kestrel sometimes does sync writes, unfortunately
         options.AllowSynchronousIO = true;
         options.ApplicationSchedulingMode = SchedulingMode.ThreadPool;
         options.Listen(IPAddress.Parse(serverConfig.Listening.Address), serverConfig.Listening.Port, listenOptions =>
         {
             // Configure Listen Options here
             listenOptions.NoDelay = true;
         });
     })
            .UseLibuv(options =>
     {
         options.ThreadCount = Environment.ProcessorCount * 2;
     })
            .ConfigureServices(services =>
     {
         // Configure dependency injection (services) for the Startup class here
         services.AddSingleton(mongoWrapper);
         services.AddSingleton(serverInfo);
         // We act as a cache for the ServerConfiguration object, invoking this func on every request for it.
         services.AddScoped(provider => serverConfig);
         services.AddScoped(provider => provider.GetRequiredService <ServerConfiguration>().Smtp);
         // services.AddScoped(provider => provider.GetRequiredService<ServerConfiguration>().XX);
     })
            .UseStartup <RestServerStartup>()
            .Build());
 }
示例#25
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);
                }
            }));
        }
示例#26
0
        /// <summary>
        /// Method that contains initialization for all the pieces of the server application.
        /// </summary>
        /// <param name="sharedData"></param>
        private static async Task StartServer(ServerConfiguration serverConfig, ServerInfo serverInfo, MongoWrapper mongoWrapper)
        {
            var serverController = new ServerController(
                configurationReloader: () =>
            {
                serverConfig = GeneralUtils.ReadConfiguration(serverInfo.ConfigurationPath);
            }
                );

            (Task hostTask, IWebHost host) = StartHost(serverConfig, serverInfo, mongoWrapper);

            (Task radioTask, RadioCastServer radioCastServer) = StartRadio(serverConfig.Radio);

            (Task shellTask, FmShell.Shell shell) = StartShell(serverConfig, serverInfo, serverController, radioCastServer);

            Task radioFeeder = StartRadioFeeder(radioCastServer, mongoWrapper);

            await AwaitTermination(shellTask, shell, hostTask, host, radioFeeder);

            radioCastServer.Dispose();
        }
示例#27
0
 public XomlTaskService(MongoWrapper mongo)
 {
     this._mongo = mongo;
 }
示例#28
0
 public AllPlaces(MongoWrapper mongoWrapper)
 {
     _mongoWrapper = mongoWrapper;
 }
示例#29
0
 public BasicNetworkLoggerMiddleware(RequestDelegate next, MongoWrapper mongoWrapper, ILoggerFactory loggerFactory)
 {
     Logger       = loggerFactory.CreateLogger <BasicNetworkLoggerMiddleware>();
     Next         = next;
     MongoWrapper = mongoWrapper;
 }
示例#30
0
 public GeolocationController(MongoWrapper mongoWrapper, ILogger <GeolocationController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(GeolocationController)} Constructor Invoked");
     MongoWrapper = mongoWrapper;
 }
示例#31
0
 public RadioInfoController(MongoWrapper mongoWrapper, ILogger <RadioInfoController> logger)
 {
     Logger = logger;
     Logger.LogTrace($"{nameof(RadioInfoController)} Constructor Invoked");
     MongoWrapper = mongoWrapper;
 }