Esempio n. 1
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            if (string.IsNullOrEmpty(Settings.URL))
            {
                throw new Exception("Plik Host is empty.");
            }
            NameValueCollection requestHeaders = new NameValueCollection();

            requestHeaders["X-PlikToken"] = Settings.APIKey;
            UploadMetadataRequest metaDataReq = new UploadMetadataRequest();

            metaDataReq.Files                = new UploadMetadataRequestFile0();
            metaDataReq.Files.File0          = new UploadMetadataRequestFile();
            metaDataReq.Files.File0.FileName = fileName;
            metaDataReq.Files.File0.FileType = RequestHelpers.GetMimeType(fileName);
            metaDataReq.Files.File0.FileSize = Convert.ToInt32(stream.Length);
            metaDataReq.Removable            = Settings.Removable;
            metaDataReq.OneShot              = Settings.OneShot;
            if (Settings.TTLUnit != 3) // everything except the expire time -1
            {
                metaDataReq.Ttl = Convert.ToInt32(GetMultiplyIndex(2, Settings.TTLUnit) * Settings.TTL * 60);
            }
            else
            {
                metaDataReq.Ttl = -1;
            }
            if (Settings.HasComment)
            {
                metaDataReq.Comment = Settings.Comment;
            }
            if (Settings.IsSecured)
            {
                metaDataReq.Login    = Settings.Login;
                metaDataReq.Password = Settings.Password;
            }
            string metaDataResp             = SendRequest(HttpMethod.POST, Settings.URL + "/upload", JsonConvert.SerializeObject(metaDataReq), headers: requestHeaders);
            UploadMetadataResponse metaData = JsonConvert.DeserializeObject <UploadMetadataResponse>(metaDataResp);

            requestHeaders["x-uploadtoken"] = metaData.uploadToken;
            string       url        = $"{Settings.URL}/file/{metaData.id}/{metaData.files.First().Value.id}/{fileName}";
            UploadResult FileDatReq = SendRequestFile(url, stream, fileName, "file", headers: requestHeaders);

            return(ConvertResult(metaData, FileDatReq));
        }
Esempio n. 2
0
        public ActionResult SendPlaystateCommand(
            [FromRoute, Required] string sessionId,
            [FromRoute, Required] PlaystateCommand command,
            [FromQuery] long?seekPositionTicks,
            [FromQuery] string?controllingUserId)
        {
            _sessionManager.SendPlaystateCommand(
                RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id,
                sessionId,
                new PlaystateRequest()
            {
                Command           = command,
                ControllingUserId = controllingUserId,
                SeekPositionTicks = seekPositionTicks,
            },
                CancellationToken.None);

            return(NoContent());
        }
Esempio n. 3
0
        /// <summary>
        /// Tries to parse a <see cref="B2Error"/> from the given response.
        /// </summary>
        /// <param name="res">The response that contains an error.</param>
        /// <returns>
        /// The parse result, or null if the response is successful or cannot be parsed.
        /// </returns>
        /// <exception cref="IOException">If the response body cannot be read.</exception>
        private static B2Error ParseB2Error(HttpWebResponse res)
        {
            if (RequestHelpers.IsSuccessStatusCode(res.StatusCode))
            {
                return(null);
            }

            try
            {
                string body = RequestHelpers.ResponseToString(res);
                DebugHelper.WriteLine($"B2 uploader: ParseB2Error() got: {body}");
                B2Error err = JsonConvert.DeserializeObject <B2Error>(body);
                return(err);
            }
            catch (JsonException)
            {
                return(null);
            }
        }
Esempio n. 4
0
        public async Task <ActionResult> UpdateUserPassword(
            [FromRoute, Required] Guid userId,
            [FromBody, Required] UpdateUserPassword request)
        {
            if (!await RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true).ConfigureAwait(false))
            {
                return(StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the password."));
            }

            var user = _userManager.GetUserById(userId);

            if (user == null)
            {
                return(NotFound("User not found"));
            }

            if (request.ResetPassword)
            {
                await _userManager.ResetPassword(user).ConfigureAwait(false);
            }
            else
            {
                var success = await _userManager.AuthenticateUser(
                    user.Username,
                    request.CurrentPw,
                    request.CurrentPw,
                    HttpContext.GetNormalizedRemoteIp().ToString(),
                    false).ConfigureAwait(false);

                if (success == null)
                {
                    return(StatusCode(StatusCodes.Status403Forbidden, "Invalid user or password entered."));
                }

                await _userManager.ChangePassword(user, request.NewPw).ConfigureAwait(false);

                var currentToken = (await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false)).Token;

                await _sessionManager.RevokeUserTokens(user.Id, currentToken).ConfigureAwait(false);
            }

            return(NoContent());
        }
Esempio n. 5
0
        /// <inheritdoc/>
        public async Task <List <Rule> > GetRulesAsync()
        {
            if (_currentChallenge == 0)
            {
                await RenewChallengeAsync();
            }

            byte[] response = await SendRequestAsync(
                RequestHelpers.PrepareAS2_GENERIC_Request(RequestHeaders.A2S_RULES, _currentChallenge));

            if (response.Length > 0)
            {
                return(DataResolutionUtils.ExtractListData <Rule>(response));
            }
            else
            {
                throw new InvalidOperationException("Server did not response the query");
            }
        }
Esempio n. 6
0
        public void Get_Residency_ById_And_Courses_WithoutGenericHelper()
        {
            //arrange
            var filterLambdaOperatorDescriptor = GetFilterExpressionDescriptor <ResidencyModel>
                                                 (
                GetResidencyByIdFilterBody(2),
                "q"
                                                 );

            IMapper mapper = serviceProvider.GetRequiredService <IMapper>();
            IEnrollmentRepository repository = serviceProvider.GetRequiredService <IEnrollmentRepository>();

            //act
            var expression      = mapper.MapToOperator(filterLambdaOperatorDescriptor).Build();
            var selectAndExpand = new Common.Configuration.ExpansionDescriptors.SelectExpandDefinitionDescriptor
            {
                ExpandedItems = new List <Common.Configuration.ExpansionDescriptors.SelectExpandItemDescriptor>
                {
                    new Common.Configuration.ExpansionDescriptors.SelectExpandItemDescriptor
                    {
                        MemberName = "StatesLivedIn"
                    }
                }
            };

            var entity = (ResidencyModel)RequestHelpers.GetEntity
                         (
                new Business.Requests.GetEntityRequest
            {
                Filter = filterLambdaOperatorDescriptor,
                SelectExpandDefinition = selectAndExpand,
                ModelType = typeof(ResidencyModel).AssemblyQualifiedName,
                DataType  = typeof(Residency).AssemblyQualifiedName
            },
                repository,
                mapper
                         ).Result.Entity;

            //assert
            AssertFilterStringIsCorrect(expression, "q => (q.UserId == 2)");
            Assert.Equal(2, entity.StatesLivedIn.Count);
        }
Esempio n. 7
0
        public void GraphqlBatchUpdateEntities(EntityFactory entityFactory, int numEntities)
        {
            var entity           = entityFactory.Construct();
            var entityProperties = entity.GetType().GetProperties();

            if (entityProperties.Any(x => x.PropertyType.IsEnum) || entity.HasFile)
            {
                throw new SkipException("Batch update is currently not supported on entities with enum or file");
            }

            var entityList = entityFactory.ConstructAndSave(_output, numEntities);

            //setup the rest client
            var client = new RestClient
            {
                BaseUrl = new Uri($"{_configure.BaseUrl}/api/graphql")
            };

            //setup the request
            var request = new RestRequest
            {
                Method        = Method.POST,
                RequestFormat = DataFormat.Json
            };

            //get the authorization token and adds the token to the request
            var loginToken         = new LoginToken(_configure.BaseUrl, _configure.SuperUsername, _configure.SuperPassword);
            var authorizationToken = $"{loginToken.TokenType} {loginToken.AccessToken}";

            request.AddHeader("Authorization", authorizationToken);

            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "*\\*");

            // form the query to update the entity
            var updateQuery = QueryBuilder.BatchUpdateEntityQueryBuilder(entityList);

            request.AddParameter("text/json", updateQuery, ParameterType.RequestBody);

            // mass update all entities in the list in a single request and check status code is ok
            RequestHelpers.ValidateResponse(client, Method.POST, request, HttpStatusCode.OK);
        }
Esempio n. 8
0
        public async Task <ActionResult> SendPlaystateCommand(
            [FromRoute, Required] string sessionId,
            [FromRoute, Required] PlaystateCommand command,
            [FromQuery] long?seekPositionTicks,
            [FromQuery] string?controllingUserId)
        {
            await _sessionManager.SendPlaystateCommand(
                await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false),
                sessionId,
                new PlaystateRequest()
            {
                Command           = command,
                ControllingUserId = controllingUserId,
                SeekPositionTicks = seekPositionTicks,
            },
                CancellationToken.None)
            .ConfigureAwait(false);

            return(NoContent());
        }
Esempio n. 9
0
        public async Task <ActionResult> UpdateUser(
            [FromRoute, Required] Guid userId,
            [FromBody, Required] UserDto updateUser)
        {
            if (!await RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, false).ConfigureAwait(false))
            {
                return(StatusCode(StatusCodes.Status403Forbidden, "User update not allowed."));
            }

            var user = _userManager.GetUserById(userId);

            if (!string.Equals(user.Username, updateUser.Name, StringComparison.Ordinal))
            {
                await _userManager.RenameUser(user, updateUser.Name).ConfigureAwait(false);
            }

            await _userManager.UpdateConfigurationAsync(user.Id, updateUser.Configuration).ConfigureAwait(false);

            return(NoContent());
        }
Esempio n. 10
0
        public ActionResult SysAdmin(bool?isPwdReset)
        {
            if (isPwdReset.HasValue && isPwdReset.Value)
            {
                ViewData[ViewConstants.REDIRECT_URL_KEY] = UrlsConstants.RESET_PASSWORD_URL;
            }

            var sysUser = MasterLocator.UserService.GetById(Context.UserId);

            ViewData[ViewConstants.AZURE_PICTURE_URL]      = PictureService.GetPicturesRelativeAddress();
            ViewData[ViewConstants.DEMO_AZURE_PICTURE_URL] = PictureService.GeDemoPicturesRelativeAddress();
            PrepareJsonData(SysAdminViewData.Create(sysUser), ViewConstants.CURRENT_PERSON);
            ViewData[ViewConstants.SERVER_TIME] = Context.NowSchoolTime.ToString(DATE_TIME_FORMAT);
            var ip = RequestHelpers.GetClientIpAddress(Request);

            MasterLocator.UserTrackingService.IdentifySysAdmin(sysUser.Login, "", "", null, ip);
            ViewData[ViewConstants.ROLE_NAME] = CoreRoles.SUPER_ADMIN_ROLE.LoweredName;
            ViewData[ViewConstants.ASSESSMENT_APLICATION_ID] = MasterLocator.ApplicationService.GetAssessmentId();
            return(View());
        }
Esempio n. 11
0
        public void Write(string accion, string mensaje)
        {
            var _lei = new LogEventInfo(LogLevel.Info, _logger.Name, _logger.Name);

            _lei.Properties.Add("accion", accion);

            if (_application.IsAuthenticated())
            {
                var personaId = _application.GetCurrentUser().PersonaId;
                if (personaId.HasValue)
                {
                    var persona = _iPersonaService.Get((int)personaId);
                    _lei.Properties.Add("indentificacion", persona.Identificacion);
                }
                else
                {
                    _lei.Properties.Add("indentificacion", "AN");
                }
            }
            else
            {
                _lei.Properties.Add("indentificacion", "AN");
            }


            //Almacenar IP
            if (HttpContext.Current != null && HttpContext.Current.Request != null)
            {
                string ipAddress = RequestHelpers.GetClientIpAddress(new HttpRequestWrapper(HttpContext.Current.Request));

                _lei.Properties.Add("ip", ipAddress);
            }
            else
            {
                _lei.Properties.Add("ip", string.Empty);
            }

            _lei.Message = mensaje;

            _logger.Log(_lei);
        }
Esempio n. 12
0
        public static void Main(string[] args)
        {
            bool tracingDisabled = args.Any(arg => arg.Equals("TracingDisabled", StringComparison.OrdinalIgnoreCase));

            Console.WriteLine($"TracingDisabled {tracingDisabled}");

            string port = args.FirstOrDefault(arg => arg.StartsWith("Port="))?.Split('=')[1] ?? "9000";

            Console.WriteLine($"Port {port}");

            using (var listener = StartHttpListenerWithPortResilience(port))
            {
                Console.WriteLine();
                Console.WriteLine($"Starting HTTP listener at {Url}");

                // send http requests using WebClient
                Console.WriteLine();
                Console.WriteLine("Sending request with WebClient.");

                using (Tracer.Instance.StartActive("RequestHelpers.SendWebClientRequests"))
                {
                    RequestHelpers.SendWebClientRequests(tracingDisabled, Url, RequestContent);
                }

                Console.WriteLine("Sending request with WebRequest.");

                using (Tracer.Instance.StartActive("RequestHelpers.SendWebRequestRequests"))
                {
                    RequestHelpers.SendWebRequestRequests(tracingDisabled, Url, RequestContent);
                }

                Console.WriteLine();
                Console.WriteLine("Stopping HTTP listener.");
                listener.Stop();
            }

            // Force process to end, otherwise the background listener thread lives forever in .NET Core.
            // Apparently listener.GetContext() doesn't throw an exception if listener.Stop() is called,
            // like it does in .NET Framework.
            Environment.Exit(0);
        }
Esempio n. 13
0
        public ActionResult DisplayContent(
            [FromRoute, Required] string?sessionId,
            [FromQuery, Required] string?itemType,
            [FromQuery, Required] string?itemId,
            [FromQuery, Required] string?itemName)
        {
            var command = new BrowseRequest
            {
                ItemId   = itemId,
                ItemName = itemName,
                ItemType = itemType
            };

            _sessionManager.SendBrowseCommand(
                RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id,
                sessionId,
                command,
                CancellationToken.None);

            return(NoContent());
        }
Esempio n. 14
0
        public void MissingXSRFTokenValidCookiesUnauthTest()
        {
            // get a paired client and xsrf token
            var clientxsrf = ClientXsrf.GetValidClientAndxsrfTokenPair(_configure);

            // extract the client
            var client = clientxsrf.client;

            // extract the xsrf token
            var xsrfToken = clientxsrf.xsrfToken;

            // set the uri for the authorised api request
            client.BaseUrl = new Uri($"{_configure.BaseUrl}/api/account/me");

            //setup the request
            var request = RequestHelpers.BasicPostRequest();

            // we don't expect out result to be valid since we have not attatched a valid
            // xsrf token as a header, although we do have valid cookies
            ResponseHelpers.CheckResponse(client, request, expectValid: false);
        }
Esempio n. 15
0
        public ActionResult Play(
            [FromRoute, Required] string sessionId,
            [FromRoute, Required] PlayCommand command,
            [FromQuery] Guid[] itemIds,
            [FromQuery] long?startPositionTicks)
        {
            var playRequest = new PlayRequest
            {
                ItemIds            = itemIds,
                StartPositionTicks = startPositionTicks,
                PlayCommand        = command
            };

            _sessionManager.SendPlayCommand(
                RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id,
                sessionId,
                playRequest,
                CancellationToken.None);

            return(NoContent());
        }
Esempio n. 16
0
        private void PrepareStudentJsonData()
        {
            Trace.Assert(Context.PersonId.HasValue);
            var startupData = SchoolLocator.SchoolService.GetStartupData();

            var district   = PrepareCommonViewDataForSchoolPerson(startupData);
            var person     = startupData.Person;
            var personView = PersonInfoViewData.Create(person);

            ProcessFirstLogin(person);
            ProcessActive(person, personView);
            PrepareJsonData(personView, ViewConstants.CURRENT_PERSON);
            var dayTypes  = SchoolLocator.DayTypeService.GetDayTypes(startupData.Classes.SelectMany(x => x.ClassPeriods, (a, b) => b.DayTypeRef).ToList());
            var classesVD = ClassComplexViewData.Create(startupData.Classes, startupData.Rooms, dayTypes).ToList();

            PrepareJsonData(classesVD, ViewConstants.CLASSES);
            var ip = RequestHelpers.GetClientIpAddress(Request);

            MasterLocator.UserTrackingService.IdentifyStudent(Context.Login, person.FirstName, person.LastName,
                                                              district.Name, "", person.FirstLoginDate, Context.DistrictTimeZone, ip, Context.SCEnabled);
        }
Esempio n. 17
0
        public ActionResult SendFullGeneralCommand(
            [FromRoute, Required] string?sessionId,
            [FromBody, Required] GeneralCommand command)
        {
            var currentSession = RequestHelpers.GetSession(_sessionManager, _authContext, Request);

            if (command == null)
            {
                throw new ArgumentException("Request body may not be null");
            }

            command.ControllingUserId = currentSession.UserId;

            _sessionManager.SendGeneralCommand(
                currentSession.Id,
                sessionId,
                command,
                CancellationToken.None);

            return(NoContent());
        }
Esempio n. 18
0
        public ActionResult UpdateInfo(Guid developerId, string name, string websiteLink, string email)
        {
            var user = MasterLocator.UserService.GetByLogin(email);

            if (user != null && user.Id != Context.UserId)
            {
                return(Json(new ChalkableException("User email already exists")));
            }

            var res = MasterLocator.DeveloperService.Edit(developerId, name, email, websiteLink, null);

            MasterLocator.UserTrackingService.ChangedEmail(Context.Login, email);
            if (Context.Role.LoweredName == CoreRoles.DEVELOPER_ROLE.LoweredName)
            {
                var timeZoneId = Context.DistrictTimeZone;
                var ip         = RequestHelpers.GetClientIpAddress(Request);
                MasterLocator.UserTrackingService.IdentifyDeveloper(res.Email, res.DisplayName,
                                                                    String.IsNullOrEmpty(timeZoneId) ? DateTime.UtcNow : DateTime.UtcNow.ConvertFromUtc(timeZoneId), timeZoneId, ip);
            }
            return(Json(DeveloperViewData.Create(res)));
        }
Esempio n. 19
0
        public ActionResult SendSystemCommand(
            [FromRoute, Required] string?sessionId,
            [FromRoute, Required] string?command)
        {
            var name = command;

            if (Enum.TryParse(name, true, out GeneralCommandType commandType))
            {
                name = commandType.ToString();
            }

            var currentSession = RequestHelpers.GetSession(_sessionManager, _authContext, Request);
            var generalCommand = new GeneralCommand
            {
                Name = name,
                ControllingUserId = currentSession.UserId
            };

            _sessionManager.SendGeneralCommand(currentSession.Id, sessionId, generalCommand, CancellationToken.None);

            return(NoContent());
        }
Esempio n. 20
0
        public async Task <ActionResult> DisplayContent(
            [FromRoute, Required] string sessionId,
            [FromQuery, Required] string itemType,
            [FromQuery, Required] string itemId,
            [FromQuery, Required] string itemName)
        {
            var command = new BrowseRequest
            {
                ItemId   = itemId,
                ItemName = itemName,
                ItemType = itemType
            };

            await _sessionManager.SendBrowseCommand(
                await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false),
                sessionId,
                command,
                CancellationToken.None)
            .ConfigureAwait(false);

            return(NoContent());
        }
Esempio n. 21
0
        public void Select_Residencies_In_Ascending_Order_As_ResidencyModel_Type_With_Courses()
        {
            //arrange
            var selectorLambdaOperatorDescriptor = GetExpressionDescriptor <IQueryable <ResidencyModel>, IQueryable <ResidencyModel> >
                                                   (
                GetResidenciesBodyOrderByDriversLicenseNumber(),
                "q"
                                                   );
            IMapper mapper = serviceProvider.GetRequiredService <IMapper>();
            IEnrollmentRepository repository = serviceProvider.GetRequiredService <IEnrollmentRepository>();

            //act
            var expression      = mapper.MapToOperator(selectorLambdaOperatorDescriptor).Build();
            var selectAndExpand = new Common.Configuration.ExpansionDescriptors.SelectExpandDefinitionDescriptor
            {
                ExpandedItems = new List <Common.Configuration.ExpansionDescriptors.SelectExpandItemDescriptor>
                {
                    new Common.Configuration.ExpansionDescriptors.SelectExpandItemDescriptor
                    {
                        MemberName = "StatesLivedIn"
                    }
                }
            };
            var list = RequestHelpers.GetList <ResidencyModel, Residency, IQueryable <ResidencyModel>, IQueryable <Residency> >
                       (
                new Business.Requests.GetTypedListRequest
            {
                Selector = selectorLambdaOperatorDescriptor,
                SelectExpandDefinition = selectAndExpand
            },
                repository,
                mapper
                       ).Result.List.Cast <ResidencyModel>().ToList();

            //assert
            AssertFilterStringIsCorrect(expression, "q => Convert(q.OrderBy(d => d.DriversLicenseNumber))");
            Assert.Equal(2, list.Count);
            Assert.True(list.All(d => d.StatesLivedIn.Any()));
        }
Esempio n. 22
0
        private string Push(string pushType, string valueType, string value, string title)
        {
            NameValueCollection headers = RequestHelpers.CreateAuthenticationHeader(Config.UserAPIKey, "");

            Dictionary <string, string> args = new Dictionary <string, string>();

            args.Add("device_iden", Config.CurrentDevice.Key);
            args.Add("type", pushType);
            args.Add("title", title);
            args.Add(valueType, value);

            if (valueType != "body")
            {
                if (pushType == "link")
                {
                    args.Add("body", value);
                }
                else
                {
                    args.Add("body", "Sent via ShareX");
                }
            }

            string response = SendRequestMultiPart(apiSendPushURL, args, headers);

            if (response == null)
            {
                return(null);
            }

            PushbulletResponsePush push = JsonConvert.DeserializeObject <PushbulletResponsePush>(response);

            if (push != null)
            {
                return(wwwPushesURL + "?push_iden=" + push.iden);
            }

            return(null);
        }
        public HttpResponseMessage Carregar()
        {
            HttpResponseMessage result = null;


            NameValueCollection data = HttpUtility.ParseQueryString(Request.RequestUri.Query);

            // Parametros da pesquisa
            DateTime?dataEntrega = RequestHelpers.ObterDataOuNulo(data["Data"]);

            if (!dataEntrega.HasValue)
            {
                dataEntrega = DateTime.Now;
            }

            //List<Entrega> entregas = _repoEntrega.PesquisarEntregas(null, null, null, dataEntrega);

            //dynamic lst = entregas.Select(x => new
            //{
            //    id = x.idEntrega,
            //    title = x.Projeto.sigla,
            //    description = x.descricaoAtividade,
            //    url = "#",
            //    Class = "event-warning",
            //    start = (x.dataEntregaPrevista.Value - new DateTime(1969, 12, 31)).TotalMilliseconds,
            //    end = (x.dataEntregaPrevista.Value - new DateTime(1969, 12, 31)).TotalMilliseconds
            //}).ToList();

            JObject obj = new JObject();

            //obj.Add("entregas", JsonConvert.SerializeObject(entregas));
            //obj.Add("calendar", JsonConvert.SerializeObject(lst));

            result = Request.CreateResponse(HttpStatusCode.OK, obj);


            return(result);
        }
Esempio n. 24
0
        public async Task <ActionResult> OnPlaybackProgress(
            [FromRoute, Required] Guid userId,
            [FromRoute, Required] Guid itemId,
            [FromQuery] string?mediaSourceId,
            [FromQuery] long?positionTicks,
            [FromQuery] int?audioStreamIndex,
            [FromQuery] int?subtitleStreamIndex,
            [FromQuery] int?volumeLevel,
            [FromQuery] PlayMethod?playMethod,
            [FromQuery] string?liveStreamId,
            [FromQuery] string?playSessionId,
            [FromQuery] RepeatMode?repeatMode,
            [FromQuery] bool isPaused = false,
            [FromQuery] bool isMuted  = false)
        {
            var playbackProgressInfo = new PlaybackProgressInfo
            {
                ItemId              = itemId,
                PositionTicks       = positionTicks,
                IsMuted             = isMuted,
                IsPaused            = isPaused,
                MediaSourceId       = mediaSourceId,
                AudioStreamIndex    = audioStreamIndex,
                SubtitleStreamIndex = subtitleStreamIndex,
                VolumeLevel         = volumeLevel,
                PlayMethod          = playMethod ?? PlayMethod.Transcode,
                PlaySessionId       = playSessionId,
                LiveStreamId        = liveStreamId,
                RepeatMode          = repeatMode ?? RepeatMode.RepeatNone
            };

            playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId);
            playbackProgressInfo.SessionId  = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);

            await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false);

            return(NoContent());
        }
Esempio n. 25
0
        public void GetPlayers_ShouldPopulateCorrectPlayers()
        {
            (byte[] playersPacket, object responseObject) = ResponseHelper.GetValidResponse(ResponseHelper.GetPlayers);
            var expectedObject = (List <Player>)responseObject;

            byte[] challengePacket = RequestHelpers.PrepareAS2_RENEW_CHALLENGE_Request();

            // Both requests will be executed on AS2_PLAYER since thats how you refresh challenges.
            byte[][] requestPackets = new byte[][] { challengePacket, challengePacket };

            // First response is the Challenge renewal response and the second
            byte[][] responsePackets = new byte[][] { challengePacket, playersPacket };

            Mock <IUdpClient> udpClientMock = SetupReceiveResponse(responsePackets);

            SetupRequestCompare(requestPackets, udpClientMock);

            // Ayylmao it looks ugly as hell but we will improve it later on.
            using (var sq = new ServerQuery(udpClientMock.Object, _localIpEndpoint))
            {
                Assert.Equal(JsonConvert.SerializeObject(expectedObject), JsonConvert.SerializeObject(sq.GetPlayers()));
            }
        }
Esempio n. 26
0
        public ActionResult PostCapabilities(
            [FromQuery] string?id,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] playableMediaTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] GeneralCommandType[] supportedCommands,
            [FromQuery] bool supportsMediaControl         = false,
            [FromQuery] bool supportsSync                 = false,
            [FromQuery] bool supportsPersistentIdentifier = true)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                id = RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id;
            }

            _sessionManager.ReportCapabilities(id, new ClientCapabilities
            {
                PlayableMediaTypes           = playableMediaTypes,
                SupportedCommands            = supportedCommands,
                SupportsMediaControl         = supportsMediaControl,
                SupportsSync                 = supportsSync,
                SupportsPersistentIdentifier = supportsPersistentIdentifier
            });
            return(NoContent());
        }
Esempio n. 27
0
        public ActionResult PostCapabilities(
            [FromQuery, Required] string?id,
            [FromQuery] string?playableMediaTypes,
            [FromQuery] string?supportedCommands,
            [FromQuery] bool supportsMediaControl         = false,
            [FromQuery] bool supportsSync                 = false,
            [FromQuery] bool supportsPersistentIdentifier = true)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                id = RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id;
            }

            _sessionManager.ReportCapabilities(id, new ClientCapabilities
            {
                PlayableMediaTypes           = RequestHelpers.Split(playableMediaTypes, ',', true),
                SupportedCommands            = RequestHelpers.Split(supportedCommands, ',', true),
                SupportsMediaControl         = supportsMediaControl,
                SupportsSync                 = supportsSync,
                SupportsPersistentIdentifier = supportsPersistentIdentifier
            });
            return(NoContent());
        }
Esempio n. 28
0
        public static void Main(string[] args)
        {
            bool tracingDisabled = args.Any(arg => arg.Equals("TracingDisabled", StringComparison.OrdinalIgnoreCase));

            Console.WriteLine($"TracingDisabled {tracingDisabled}");

            string port = args.FirstOrDefault(arg => arg.StartsWith("Port="))?.Split('=')[1] ?? "9000";

            Console.WriteLine($"Port {port}");

            using (var server = WebServer.Start(port, out var url))
            {
                server.RequestHandler = HandleHttpRequests;

                Console.WriteLine();
                Console.WriteLine($"Starting HTTP listener at {url}");

                // send http requests using WebClient
                Console.WriteLine();
                Console.WriteLine("Sending request with WebClient.");

                using (Tracer.Instance.StartActive("RequestHelpers.SendWebClientRequests"))
                {
                    RequestHelpers.SendWebClientRequests(tracingDisabled, url, RequestContent);
                }

                Console.WriteLine("Sending request with WebRequest.");

                using (Tracer.Instance.StartActive("RequestHelpers.SendWebRequestRequests"))
                {
                    RequestHelpers.SendWebRequestRequests(tracingDisabled, url, RequestContent);
                }

                Console.WriteLine();
                Console.WriteLine("Stopping HTTP listener.");
            }
        }
Esempio n. 29
0
        public EventList get(string sport, DateTime date)
        {
            string              jsonStr, url = "";
            EventList           eventResult     = null;
            NameValueCollection queryParameters = new NameValueCollection();

            using (var client = new GZipWebClient(_apiKey, _userAgentName, true))
            {
                if (_alternateDomain == null)
                {
                    url = "https://erikberg.com/events.json";
                }
                else
                {
                    url = "https://" + _alternateDomain + "/events.json";
                }

                if (sport != null)
                {
                    queryParameters.Add("sport", sport);
                }
                if (date != null)
                {
                    queryParameters.Add("date", date.ToString("yyyyMMdd"));
                }

                if (queryParameters.Count > 0)
                {
                    url += RequestHelpers.ToQueryString(queryParameters);
                }

                jsonStr     = client.DownloadString(url);
                eventResult = JsonConvert.DeserializeObject <EventList>(jsonStr);

                return(eventResult);
            }
        }
Esempio n. 30
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var result = _accountRepo.Login(model, RequestHelpers.RequestIPAddress());
            var valid  = _accountRepo.CheckValidForTransaction(result.UserId, RequestHelpers.RequestIPAddress());

            if (!valid)
            {
                return(RedirectToAction("IpBlocked", "Account"));
            }
            if (result != null)
            {
                SetUserSession(result);
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                ModelState.AddModelError("", "Incorrect Username or Password");
                return(View(model));
            }
        }