public HttpResponseMessage Login([FromBody] LoginModel loginModel) { string email = loginModel.email; string password = loginModel.password; CustomResponse response; User loginUser = _repository.Login(loginModel); if (loginUser != null) { //LoginUser var userToken = new UserTokenDTO() { email = email, password = password, expireDate = DateTime.Now.AddDays(TOKEN_EXPIRE_DAY) }; //Serializing userToken var jsonString = JsonConvert.SerializeObject(userToken); // Token generation var token = FTH.Extension.Encrypter.Encrypt(jsonString, LoginUtility.PRIVATE_KEY); LoginResponseDTO userDTO = GenericMapper.MapToLoginResponseDTO(loginUser, token); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, userDTO, ConstantResponse.LOGIN_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); } else { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.Unauthorized, true, null, ConstantResponse.LOGIN_FAILED); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.Unauthorized, response)); } }
public async Task <IActionResult> SignIn(User user) { if (!ModelState.IsValid) { return(ResponseMessageHelper.ModelStateInvalid(ModelState)); } var cognito = new AmazonCognitoIdentityProviderClient(_region); var request = new AdminInitiateAuthRequest { UserPoolId = _config.Value.AwsCognitoUserPoolId, ClientId = _config.Value.AwsCognitoAppClientId, AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH }; request.AuthParameters.Add("USERNAME", user.Username); request.AuthParameters.Add("PASSWORD", user.Password); try { var response = await cognito.AdminInitiateAuthAsync(request); return(ResponseMessageHelper.Ok(response.AuthenticationResult.IdToken)); } catch (NotAuthorizedException ex) { return(ResponseMessageHelper.Unauthorized(ex.Message)); } catch (Exception ex) { return(ResponseMessageHelper.InternalServerError(ex.Message)); } }
public IActionResult AddBattleShip(BattleshipModel battleshipModel) { try { string username = GetCurrentUserName(); var result = _battleshipGameService .AddBattleship(username, battleshipModel.Ship , battleshipModel.StartPosition, battleshipModel.ShipPlacement); if (result) { return(ResponseMessageHelper.Ok("Ship Added")); } else { return(ResponseMessageHelper.InternalServerError()); } } catch (BattleshipGameException ex) { return(ResponseMessageHelper.BadRequest(ex.Message)); } catch (Exception ex) { //write exception to a error log return(ResponseMessageHelper.InternalServerError()); } }
public HttpResponseMessage AddBoat([FromBody] Boat boat) { //Gets the user from token var token = Request.Headers.Authorization.Parameter; User sender = UserUtility.GetUserByToken(token); CustomResponse response; //Controls whether the user is leader or not if (sender.team == null || sender.team.leaderId != sender.id) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.Unauthorized, true, HttpStatusCode.Unauthorized, ConstantResponse.TEAM_BOAT_FAILED); return(Request.CreateResponse(HttpStatusCode.Unauthorized, response)); } //Controls whether the users'team has already had a boat or not else if (sender.team.boat != null) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, HttpStatusCode.BadRequest, ConstantResponse.TEAM_BOAT_ALREADY_HAVE_BOAT); return(Request.CreateResponse(HttpStatusCode.BadRequest, response)); } //Adds the boat to the team Boat addedBoat = _repository.AddBoat(sender.id, boat); //Maps the added boat to the its DTO BoatDTO boatDTO = GenericMapper.MapToBoatDTO(addedBoat); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, boatDTO, ConstantResponse.TEAM_BOAT_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); }
public HttpResponseMessage Invite([FromBody] UserEmailDTO emailDTO) { //Gets the Sender from token var token = Request.Headers.Authorization.Parameter; User sender = UserUtility.GetUserByToken(token); CustomResponse response; bool userHasTeam = _repository.UserHasTeam(sender.email); bool isUserLeader = _repository.IsUserLeader(sender.email); //Checks whether sender has a team or not if (!userHasTeam || !isUserLeader) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, ConstantResponse.TEAM_INVITE_SENDER_ERR); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } //Checks whether sender is trying to invite himself/herself else if (sender.email == emailDTO.email) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, ConstantResponse.TEAM_INVITE_YOURSELF); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } //used to get sender name etc.. User senderLocal = _userRepository.GetByEmail(sender.email); User receiver = _userRepository.GetByEmail(emailDTO.email); //Checks whether the sender has already sent an invitation which is not answered by the receiver yet bool inProgressInvite = _notificationRepository.InProgressInvite(senderLocal.id, receiver.id); if (inProgressInvite) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, ConstantResponse.TEAN_INVITE_INPROGRESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } //Checks whether the receiver is exist or not if (receiver == null) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, ConstantResponse.TEAM_INVITE_RECEIVER_ERR); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } //Checks whether the receiver has already had a team or not else if (receiver.team != null) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, ConstantResponse.TEAM_INVITE_RECEIVER_HAS_TEAM); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } //Helper class to create notification Notification notification = NotificationUtility.CreateForTeam(senderLocal, receiver.id); //Inserts created notification _notificationRepository.Insert(notification); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, ConstantResponse.OK, ConstantResponse.TEAM_INVITE_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); }
public HttpResponseMessage GetTeamsByCompetitionId([FromUri] int competitionId) { CustomResponse response; ICollection <TeamCompetition> teams = _competitionRepository.GetTeamsByCompetitionId(competitionId); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, teams, ConstantResponse.OK); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); }
public HttpResponseMessage Quit() { //Gets the user from token var token = Request.Headers.Authorization.Parameter; string userEmail = UserUtility.GetEmailByToken(token); CustomResponse response; try { using (M32COMDBSERVER DB = new M32COMDBSERVER()) { User loginUser = DB.Users.Include(x => x.receivedNotification).Include(x => x.team).Include(x => x.team.boat).First(x => x.email == userEmail); if (loginUser.team == null) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, ConstantResponse.TEAM_QUIT_FAILED); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } Team team = DB.Teams.Include(x => x.teamMembers).Where(x => x.id == loginUser.teamId).First(); //Team leader disposes the team if (team.leaderId == loginUser.id) { DB.Teams.Remove(team); DB.SaveChanges(); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, null, ConstantResponse.TEAM_DISPOSED); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); } //Person quits from the team team.teamMembers.Remove(loginUser); DB.Entry(team).State = EntityState.Modified; DB.Entry(loginUser).State = EntityState.Modified; DB.SaveChanges(); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, ConstantResponse.OK, ConstantResponse.TEAM_QUIT_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } }
public HttpResponseMessage getNotifications() { var token = Request.Headers.Authorization.Parameter; User user = UserUtility.GetUserByToken(token); using (M32COMDBSERVER DB = new M32COMDBSERVER()) { List <NotificationDTO> data = _repository.getNotifications(user.id); CustomResponse response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, data, ConstantResponse.NOTIFICATION_ALL_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); } }
public HttpResponseMessage RespondInvitation([FromUri] bool accept) { //Gets the headers var headers = Request.Headers; CustomResponse response; //if http packet does not include notification Token if (!headers.Contains("Actiontoken")) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, ConstantResponse.TEAM_RESPOND_MISSING_ACTIONTOKEN); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } //Notification token var actionToken = headers.GetValues("Actiontoken").First(); //Gets the Receiver from Auth token var token = Request.Headers.Authorization.Parameter; //Gets the user who sent the request string loginUserEmail = UserUtility.GetEmailByToken(token); User loginUser = _userRepository.GetByEmail(loginUserEmail); //Gets the related notification from db by using unique actionToken Notification notification = _notificationRepository.getByToken(actionToken); //invalid notification check if (notification == null || !notification.isActive || notification.receivedBy.id != loginUser.id) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.Forbidden, true, null, ConstantResponse.TEAM_RESPOND_INVALID_NOTIFICATION); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.Forbidden, response)); } //Rejection check if (!accept) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, ConstantResponse.REJECTED, ConstantResponse.TEAM_RESPOND_REJECTED); } else { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, ConstantResponse.ACCEPTED, ConstantResponse.TEAM_RESPOND_ACCEPTED); //receiver is added to the team where sender is the leader _repository.AcceptTeamInvitation(loginUserEmail, notification.sentBy.teamId); //Makes notification passive } _notificationRepository.Update(notification, false); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); }
public override void OnException(HttpActionExecutedContext actionExecutedContext) { CustomResponse response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, actionExecutedContext.Exception.ToString()); //Loging Logger.Log(actionExecutedContext.Exception.Message, actionExecutedContext.Exception.StackTrace); //Creating Response Object //ErrorResponse response = new ErrorResponse(); //response.errorAction = actionExecutedContext.ActionContext.ActionDescriptor.ActionName; //response.errorController = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName; //response.errorMessage = actionExecutedContext.Exception.ToString(); //Adding response object to response actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(System.Net.HttpStatusCode.BadRequest, response); }
public HttpResponseMessage Register([FromBody] User user) { CustomResponse response; //Inserting the user into DB var result = _repository.Register(user); //If result is not null, it means that the given email is unique! if (result != null) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.Created, false, GenericMapper.MapToUserDTO(result), ConstantResponse.USER_CREATED); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.Created, response)); } //Email in use response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, ConstantResponse.EMAIL_IN_USE); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); }
public IActionResult Reset() { try { _battleshipGameService.ResetGame(); return(ResponseMessageHelper.Ok("")); } catch (BattleshipGameException ex) { return(ResponseMessageHelper.BadRequest(ex.Message)); } catch (Exception ex) { //write exception to a error log return(ResponseMessageHelper.InternalServerError()); } }
public HttpResponseMessage Apply(int competitionId) { var token = Request.Headers.Authorization.Parameter; string userEmail = UserUtility.GetEmailByToken(token); User user = _userRepository.GetByEmail(userEmail); CustomResponse response; //checks whether user is the team leader if (user.team != null && user.team.leaderId == user.id) { Competition comp = _repository.GetById(competitionId); //Null check for competition if (comp == null) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.NotFound, true, HttpStatusCode.NotFound, ConstantResponse.COMPETITITON_APPLIED_NO_COMP_FOUND); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.NotFound, response)); } //Checks whether competition is active or not else if (comp.endDate < DateTime.Now) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, HttpStatusCode.BadRequest, ConstantResponse.COMPETITION_APPLIED_NOT_ACTIVE); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } //Checks whether the team has already applied or not bool teamAlreadyApplied = _repository.HasAlreadyApplied(competitionId, user.teamId); if (teamAlreadyApplied) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, HttpStatusCode.BadRequest, ConstantResponse.COMPETITION_APPLIED_ALREADY); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } //Adds the application to the DB _repository.Apply(comp.id, user.team.id); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, HttpStatusCode.OK, ConstantResponse.COMPETITION_APPLIED_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); } response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, HttpStatusCode.BadRequest, ConstantResponse.COMPETITION_APPLIED_NOT_TEAMLEADER); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); }
public override void OnActionExecuting(HttpActionContext actionContext) { //if it is valid, it will continue if (actionContext.ModelState.IsValid) { base.OnActionExecuting(actionContext); } //if it is not, errors are selected and written into response message else { var errorList = actionContext.ModelState.Values.SelectMany(v => v.Errors) .Select(x => x.ErrorMessage).ToList(); var errorMessage = string.Join(Environment.NewLine, errorList); CustomResponse response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, errorMessage); actionContext.Response = actionContext.Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response); } }
public IActionResult CreateBoard() { try { string username = GetCurrentUserName(); _battleshipGameService.CreateBoard(username, _config.Value.BoardSize); return(ResponseMessageHelper.OkCreated("Board created")); } catch (BattleshipGameException ex) { return(ResponseMessageHelper.BadRequest(ex.Message)); } catch (Exception ex) { //write exception to a error log return(ResponseMessageHelper.InternalServerError()); } }
public HttpResponseMessage Get(int competitionId) { //Gets the competition related with the given id var competition = _repository.GetById(competitionId); CustomResponse response; //Null check if (competition == null) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.NotFound, true, HttpStatusCode.NotFound, ConstantResponse.COMPETITION_RETRIEVE_BY_ID_NOT_FOUND); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.NotFound, response)); } //Mapping to DTO var competitionDTO = GenericMapper.MapToCompetitionDTO(competition); //Returns data response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, competitionDTO, ConstantResponse.COMPETITION_RETRIEVE_BY_ID_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); }
public HttpResponseMessage GetLastPassiveCompetitionsByRowCount(int rowCount) { //Retrieves Last {rowCount} competitions which are currently not active. var competitions = _repository.GetLastPassiveCompetitionsByRowCount(rowCount); CustomResponse response; if (competitions == null) { competitions = new List <Competition>(); } //Maps to DTO ICollection <CompetitionDTO> competitionDTOs = new List <CompetitionDTO>(); competitions.ForEach(c => competitionDTOs.Add(GenericMapper.MapToCompetitionDTO(c))); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, competitionDTOs, ConstantResponse.COMPETITION_PASSIVES_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); }
public IActionResult CreatePlayer() { try { var playerName = GetCurrentUserName(); _battleshipGameService.CreatePlayer(playerName); return(ResponseMessageHelper.OkCreated($"Good Luck! {playerName}")); } catch (BattleshipGameException ex) { return(ResponseMessageHelper.BadRequest(ex.Message)); } catch (Exception ex) { //write exception to a error log return(ResponseMessageHelper.InternalServerError()); } }
public HttpResponseMessage GetActiveCompetitions() { //Retrieves active comps from db var activeCompetitions = _repository.GetActiveCompetitions(); //Null check for Sanity ! if (activeCompetitions == null) { activeCompetitions = new List <Competition>(); } //Maps active comps to the dto ICollection <CompetitionDTO> competitionDTOs = new List <CompetitionDTO>(); activeCompetitions.ForEach(c => competitionDTOs.Add(GenericMapper.MapToCompetitionDTO(c))); //Returns data CustomResponse response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, competitionDTOs, ConstantResponse.COMPETITION_RETRIEVE_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); }
public IActionResult Attack(AttackModel attackModel) { try { string username = GetCurrentUserName(); var result = _battleshipGameService .Attack(username, attackModel.Position); return(ResponseMessageHelper.Ok(result.ToString())); } catch (BattleshipGameException ex) { return(ResponseMessageHelper.BadRequest(ex.Message)); } catch (Exception ex) { //write exception to a error log return(ResponseMessageHelper.InternalServerError()); } }
public HttpResponseMessage GetTeamMembers() { var token = Request.Headers.Authorization.Parameter; User user = UserUtility.GetUserByToken(token); Nullable <int> teamId = user.teamId; CustomResponse response; using (M32COMDBSERVER DB = new M32COMDBSERVER()) { if (teamId != null) { IEnumerable <UserDTO> result = _repository.GetTeamMembers(teamId); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, result, ConstantResponse.OK); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); } //returns null if the user does not have a team response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, null, ConstantResponse.TEAM_GET_MEMBERS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); } }
public HttpResponseMessage GetResultByCompetitionId(int competitionId) { //Retrieves the result of the competition related with the given id var teamCompetitions = _repository.GetResultByCompetitionId(competitionId); CustomResponse response; //Retrieves competition Competition competition = _repository.GetById(competitionId); if (teamCompetitions == null || competition == null) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.NotFound, true, HttpStatusCode.NotFound, ConstantResponse.COMPETITION_RESULT_NOT_FOUND); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.NotFound, response)); } //Mapping to related DTO CompetitionResultDTO result = GenericMapper.MapToCompetitionResultDTO(teamCompetitions, competition); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, result, ConstantResponse.COMPETITION_RESULT_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); }
public HttpResponseMessage GetBoat() { var token = Request.Headers.Authorization.Parameter; User sender = UserUtility.GetUserByToken(token); CustomResponse response; if (sender.team == null) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, null, ConstantResponse.TEAM_BOAT_GET_NO_TEAM); } else if (sender.team.boat == null) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, null, ConstantResponse.TEAM_BOAT_GET_NO_BOAT); } else { BoatDTO boatDTO = GenericMapper.MapToBoatDTO(sender.team.boat); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, boatDTO, ConstantResponse.TEAM_BOAT_GET_SUCCESS); } return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); }
public HttpResponseMessage Create([FromBody] Team team) { //Gets the user from token var token = Request.Headers.Authorization.Parameter; string userEmail = UserUtility.GetEmailByToken(token); CustomResponse response; using (M32COMDBSERVER DB = new M32COMDBSERVER()) { //Returns error if team name is not unique if (!_repository.IsTeamNameUnique(team.name)) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, ConstantResponse.TEAM_FAILED); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } //Returns error if the user has already had a team bool userHasTeam = _repository.UserHasTeam(userEmail); if (userHasTeam) { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.BadRequest, true, null, ConstantResponse.HAS_TEAM_ERR); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.BadRequest, response)); } //Inserts the team Team insertedTeam = _repository.InsertTeam(userEmail, team); //Maps the team to its DTO TeamDTO teamDTO = GenericMapper.MapToTeamDTO(insertedTeam); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.Created, false, teamDTO, ConstantResponse.TEAM_CREATED); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.Created, response)); } }
void webServerKayak_RequestReceived(object sender, RequestReceivedEventArgs e) { var cultureInfoEn = System.Globalization.CultureInfo.GetCultureInfo("en-US"); PlayControlEventArgs controlEventArgs = null; if (e.RequestHead.Uri.StartsWith("/reverse")) { e.ResponseHead = ResponseMessageHelper.GetHttpResponseHead("101 Switching Protocols"); e.ResponseHead.Headers["Upgrade"] = "PTTH/1.0"; e.ResponseHead.Headers["Connection"] = "Upgrade"; } else if (e.RequestHead.Uri.StartsWith("/server-info") && e.RequestHead.Method == "GET") { var dict = ResponseMessageHelper.GetServerInfo(); string content = System.Runtime.Serialization.Plists.PlistXmlDocument.CreateDocument(dict); e.ResponseHead.Headers["ContentType"] = @"text/x-apple-plist+xml"; e.ResponseBodyProducer = new BufferedProducer(content); } else if (e.RequestHead.Uri.StartsWith("/playback-info") && e.RequestHead.Method == "GET") { PlayInfoEventArgs ea = new PlayInfoEventArgs(); if (PlayInfo != null) { PlayInfo(this, ea); } var dict = ResponseMessageHelper.GetPlaybackInfo(ea.Position, ea.Duration, ea.Rate); string content = System.Runtime.Serialization.Plists.PlistXmlDocument.CreateDocument(dict); e.ResponseHead.Headers["ContentType"] = @"text/x-apple-plist+xml"; e.ResponseBodyProducer = new BufferedProducer(content); } else if (e.RequestHead.Uri.StartsWith("/slideshow-features") && e.RequestHead.Method == "GET") //photo: get features of this device (transitions, etc.) { } else if (e.RequestHead.Uri.StartsWith("/scrub") && e.RequestHead.Method == "GET") { PlayInfoEventArgs ea = new PlayInfoEventArgs(); if (PlayInfo != null) { PlayInfo(this, ea); } string responsedata = String.Format(cultureInfoEn, "duration: {0:0.000000}\nposition: {1:0.000000}", ea.Duration, ea.Position); e.ResponseHead.Headers["ContentType"] = @"text/html; charset=UTF-8"; e.ResponseBodyProducer = new BufferedProducer(responsedata); } else if (e.RequestHead.Uri.StartsWith("/scrub") && e.RequestHead.Method == "POST") //seek. { Regex regex = new Regex(@"position=([0-9\.]+)"); Match match = regex.Match(e.RequestHead.QueryString); if (match.Success) { double scrubPosition = Convert.ToDouble(match.Groups[1].ToString(), cultureInfoEn); controlEventArgs = new PlayControlSeekEventArgs() { NewPosition = scrubPosition }; } } else if (e.RequestHead.Uri.StartsWith("/rate") && e.RequestHead.Method == "POST") // play/pause { Regex regex = new Regex(@"value=([0-9\.]+)"); Match match = regex.Match(e.RequestHead.QueryString); if (match.Success) { double rate = Convert.ToDouble(match.Groups[1].ToString(), cultureInfoEn); controlEventArgs = new PlayControlSetRateEventArgs() { NewRate = rate }; } } else if (e.RequestHead.Uri.StartsWith("/play") && e.RequestHead.Method == "POST") // URL og position is in body { var contentDict = e.RequestBody.GetContentAsDictionary(); var contentLocation = contentDict["Content-Location"].ToString(); double startPosition = Convert.ToDouble(contentDict["Start-Position"], cultureInfoEn); controlEventArgs = new PlayControlLoadUrlEventArgs() { StartPosition = startPosition, Url = contentLocation }; } else if (e.RequestHead.Uri.StartsWith("/stop") && e.RequestHead.Method == "POST") { controlEventArgs = new PlayControlStopEventArgs(); } else if (e.RequestHead.Uri.StartsWith("/authorize") && e.RequestHead.Method == "POST") { } else if (e.RequestHead.Uri.StartsWith("/photo") && e.RequestHead.Method == "PUT") //photo: show (content is raw jpeg data) { using (MemoryStream content = e.RequestBody.GetMemoryStream()) { controlEventArgs = new PlayControlDisplayImageEventArgs() { Image = System.Drawing.Image.FromStream(content) }; } } else if (e.RequestHead.Uri.StartsWith("/setProperty") && e.RequestHead.Method == "PUT") { } else //Unknown request { } if (PlayControl != null && controlEventArgs != null) { PlayControl(this, controlEventArgs); } }
public void SendStatus(string status) { var message = ResponseMessageHelper.GetStatusMessage(status); webServerKayak.SendRequestToDevice(message); }
public void StartServer() { webServerKayak.StartServer(); publishService = new NetService(_domain, _serviceName, _hostName, _port); publishService.DidPublishService += new NetService.ServicePublished(publishService_DidPublishService); publishService.DidNotPublishService += new NetService.ServiceNotPublished(publishService_DidNotPublishService); publishService.TXTRecordData = NetService.DataFromTXTRecordDictionary(ResponseMessageHelper.GetServerInfo()); publishService.Publish(); }