Exemplo n.º 1
0
        internal static void Log(TriviaMessage message, string destinationDescription, bool messageWasReceived)
        {
            if (TriviaMessageLogger.mLoggingFailed)
            {
                return;
            }

            try
            {
                lock (TriviaMessageLogger.mLockObject)
                {
                    if (TriviaMessageLogger.mLogFileWriter == null)
                    {
                        TriviaMessageLogger.mLogFileWriter = new StreamWriter(File.Open("triviamessages.log", FileMode.Create, FileAccess.ReadWrite, FileShare.Read));
                    }

                    string msgType = messageWasReceived ? "Received" : "Sent";
                    string toFrom = messageWasReceived ? "from" : "to";

                    TriviaMessageLogger.mLogFileWriter.WriteLine(string.Format("{0} - {1} message ({2}) {3} {4}", DateTime.Now.ToLongTimeString(), msgType, message.Command.ToString(), toFrom, destinationDescription));
                    TriviaMessageLogger.mLogFileWriter.Flush();
                }
            }
            catch
            {
                TriviaMessageLogger.mLoggingFailed = true;
            }
        }
Exemplo n.º 2
0
		protected virtual void OnTriviaMessageReceived(object sender, EventArgs e, TriviaMessage message, Socket socket)
		{
			switch (message.Command)
			{
				case TriviaCommand.Chat:
					this.OnChatMessageReceived(message);
					break;
				default:
					throw new InvalidOperationException("Didn't handle a certain message: " + message.Command.ToString());
			}
		}
Exemplo n.º 3
0
		protected virtual void OnChatMessageReceived(TriviaMessage message)
		{
			if (this.ChatMessageReceived != null)
			{
                string messageText;
                string whoSent;

                MessageParser.ParseChatMessage(message, out messageText, out whoSent);

				this.ChatMessageReceived(messageText, whoSent);
			}
		}
Exemplo n.º 4
0
        internal static void Log(TriviaMessage message, Socket socket, bool messageWasReceived)
        {
            string endPointDesc = "unknown socket";

            IPEndPoint ipEP = socket.RemoteEndPoint as IPEndPoint;

            if (ipEP != null)
            {
                endPointDesc = ipEP.Address.ToString();
            }

            // call helper
            TriviaMessageLogger.Log(message, endPointDesc, messageWasReceived);
        }
Exemplo n.º 5
0
		public static string Serialize(TriviaMessage message)
		{
			if (message.Command == TriviaCommand.None)
			{
				throw new InvalidOperationException("Cannot serialize a message w/o a command");
			}

            if (TriviaMessageHelper.mTriviaMessageSerializer == null)
            {
                // Create the serializer for re-use
                TriviaMessageHelper.mTriviaMessageSerializer = new XmlSerializer(typeof(TriviaMessage));
            }

			StringBuilder builder = new StringBuilder(1024);
			StringWriter writer = new StringWriter(builder);
			XmlTextWriter xmlWriter = new XmlTextWriter(writer);
            TriviaMessageHelper.mTriviaMessageSerializer.Serialize(xmlWriter, message);
			
			return builder.ToString();
		}
Exemplo n.º 6
0
		private void OnAddLinkRequestReceived(TriviaMessage message, Socket socket)
		{
			Link link = null;

			MessageParser.ParseAddLinkRequest(message, out link);

            link.Url = link.Url.Trim();
            link.Description = link.Description.Trim();
            link.SubmitterName = link.SubmitterName.Trim();

            // Enforce http:// prefix
            if (!(link.Url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) && 
                !(link.Url.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)))
            {
                link.Url = "http://" + link.Url;
            }
            

            LinkAccess.Submit(link.Description, link.Url, link.SubmitterName);

			TriviaMessage responseMessage = MessageParser.CreateAddLinkResponse(link);

			this.mServer.BroadcastMessage(responseMessage);
		}
Exemplo n.º 7
0
        private void OnAddNoteReceived(TriviaMessage message, Socket socket)
        {
            Note note = null;

            MessageParser.ParseAddNoteMessage(message, out note); // Save it to the database

            NoteAccess.AddNote(note);

            // Re-broadcast
            this.mServer.BroadcastMessage(message);
        }
Exemplo n.º 8
0
		protected override void OnChatMessageReceived(TriviaMessage message)
		{
			base.OnChatMessageReceived (message);

            message.SenderName = "broadcast";  // "...sent to broadcast"

			// Rebroadcast
			this.mServer.BroadcastMessage(message);
		}
Exemplo n.º 9
0
        private void OnGetGlobalDataRequestReceived(TriviaMessage message, Socket socket)
		{
            Stats stats = new Stats();

            stats.PointsEarnedByHour = StatsAccess.PointsEarnedByHour() ?? new int[0];
            stats.PointsMaximumByHour = StatsAccess.PointsMaxByHour() ?? new int[0];

            GlobalData gd = new GlobalData
            {
                Links = LinkAccess.GetAllLinks(),
                CurrentCaller = "mgncallerhardcoded",
                Stats = stats
            };

			TriviaMessage responseMessage = MessageParser.CreateGetGlobalDataResponse(gd);

			this.mServer.SendMessageToSpecificClient(responseMessage, socket);
		}
Exemplo n.º 10
0
        public void BroadcastMessage(TriviaMessage message)
		{
            this.BroadcastMessage(message, null);
		}
Exemplo n.º 11
0
		public void SendMessageToSpecificClient(TriviaMessage message, Socket clientSocket)
		{
            try
            {
                this.Send(clientSocket, TriviaMessageHelper.Serialize(message));
            }
            catch (CommunicationException e)
            {
                if (this.ExceptionOccurred != null)
                {
                    this.ExceptionOccurred(e);
                }

                // Server must go on!
                return;
            }

            if (this.TriviaMessageSent != null)
            {
                this.TriviaMessageSent(message, clientSocket);
            }

            if (this.mLogging != TriviaMessageLogging.None)
            {
                TriviaMessageLogger.Log(message, clientSocket, false);
            }
		}
Exemplo n.º 12
0
		private void OnUpdateAnswerRequestReceived(TriviaMessage message, Socket socket)
		{
			Answer a;
            bool partialChanged;

			MessageParser.ParseUpdateAnswerRequest(message, out a, out partialChanged);

            a.TimeCalledIn = DateTime.Now; // The server should be the authority for the timestamping

			AnswerAccess.Update(a);

			TriviaMessage responseMessage = MessageParser.CreateUpdateAnswerResponse(a, partialChanged);

			this.mServer.BroadcastMessage(responseMessage);

            // Update the Caller if necessary
            this.MaybeSendCurrentCallerChanged(message.SenderName);
		}
Exemplo n.º 13
0
        private void OnAuthenticateRequestReceived(TriviaMessage message, Socket socket)
        {
            string password;
            string version;

            MessageParser.ParseAuthenticateRequest(message, out password, out version);

            password = password.Replace(" ", string.Empty);  // Strip whitespace

            TriviaMessage responseMessage = null;

            if (!(string.Equals(password, this.mPassword, StringComparison.OrdinalIgnoreCase)))
            {
                responseMessage = MessageParser.CreateAuthenticateResponse(
                    new AuthenticationResponse
                    {
                        IsSuccessfulAuthentication = false,
                        Message = "Incorrect password"
                    });
            }
            else if (float.Parse(this.mRequiredVersion) > float.Parse(version))
            {
                string oldVersionMessage = string.Format("The version of the Trivia Client you are running is too old.  You need to download the latest version ({0}).  You are running version ({1}).", this.mRequiredVersion, version);

                responseMessage = MessageParser.CreateAuthenticateResponse(
                    new AuthenticationResponse
                    {
                        IsSuccessfulAuthentication = false,
                        Message = oldVersionMessage
                    });
            }
            else
            {
                int latestHour = this.CalculateLatestHour();

                responseMessage = MessageParser.CreateAuthenticateResponse(
                    new AuthenticationResponse
                    {
                        IsSuccessfulAuthentication = true,
                        Message = "Authenticated successfully",
                        TeamNumber = this.mTeamNumber,
                        AudioTriviaUrlFormat = this.mAudioTriviaUrlFormat,
                        RadioStationStreamUrl = this.mAudioTriviaRecorder.RadioStationStreamUrl,
                        CurrentHourData = GetCompleteHourData(latestHour),
                        GlobalData = CreateGlobalData(),
                        Players = this.mGetPlayersFunction()
                    });

                if (!(this.mAuthenticatedSockets.Contains(socket)))
                {
                    this.mAuthenticatedSockets.Add(socket);
                }
            }

            this.mServer.SendMessageToSpecificClient(responseMessage, socket);
        }
Exemplo n.º 14
0
		private void OnUpdateQuestionRequestReceived(TriviaMessage message, Socket socket)
		{
			QuestionChanges changes;

            MessageParser.ParseUpdateQuestionRequest(message, out changes);

			QuestionAccess.Update(changes);

            Question questionFromDatabase = QuestionAccess.GetQuestion(changes.Hour, changes.Number);

            TriviaMessage responseMessage = MessageParser.CreateUpdateQuestionResponse(questionFromDatabase, changes.PlayerInitiatedUpdate);
            
			this.mServer.BroadcastMessage(responseMessage);
		}
Exemplo n.º 15
0
        private void OnEditingQuestionMessageReceived(TriviaMessage message, Socket socket)
        {
            EditingQuestionData data;

            MessageParser.ParseEditingQuestionMessage(message, out data);

            // Simply broadcast the data to all clients

            TriviaMessage responseMessage = MessageParser.CreateEditingQuestionMessage(data);

            this.mServer.BroadcastMessage(responseMessage);
        }
Exemplo n.º 16
0
        public void BroadcastLatestHourMessage()
        {
            TriviaMessage message = new TriviaMessage();
            message.Command = TriviaCommand.GetLatestHourResponse;
            message.Blob = this.CalculateLatestHour().ToString();

            this.mServer.BroadcastMessage(message);
        }
Exemplo n.º 17
0
		private void OnGetLatestHourRequestReceived(TriviaMessage message, Socket socket)
		{
            int latestHour = this.CalculateLatestHour();

			// This one's massively easy
			TriviaMessage responseMessage = new TriviaMessage();
			responseMessage.Command = TriviaCommand.GetLatestHourResponse;
			responseMessage.Blob = latestHour.ToString();

			this.mServer.SendMessageToSpecificClient(responseMessage, socket);
		}
Exemplo n.º 18
0
		private void OnOpenQuestionRequestReceived(TriviaMessage message, Socket socket)
		{
			int hour;
			int number;

			MessageParser.ParseOpenQuestionRequest(message, out hour, out number);

			bool successful = true;
            string failureMessage = null;

			lock(this)
			{

                try
                {
                    QuestionAccess.InitializeForOpen(hour, number, message.SenderName);

                    Question openedQuestion = QuestionAccess.GetQuestion(hour, number);

                    // (this is correct)
                    TriviaMessage updateMessage = MessageParser.CreateUpdateQuestionResponse(openedQuestion, true);
                    this.mServer.BroadcastMessage(updateMessage);
                }
                catch (AlreadyOpenedException e)
                {
                    successful = false;
                    failureMessage = string.Format("Question {0} is already being opened by {1}", number, e.PersonWhoOpened);
                }
                catch (QuestionOpenedInWrongHourException e)
                {
                    successful = false;
                    failureMessage = string.Format("Question {0} in Hour {1} cannot be opened since Hour {2} is not complete yet, make sure that you're opening it in the appropriate hour", number, e.HourAttemptedToOpenIn, e.HourExpectedToOpenIn);
                }
			}

            TriviaMessage responseMessage = MessageParser.CreateOpenQuestionResponse(hour, number, successful, failureMessage);

			this.mServer.SendMessageToSpecificClient(responseMessage, socket);
		}
Exemplo n.º 19
0
        private void OnDeleteNoteReceived(TriviaMessage message, Socket socket)
        {
            int noteId;

            MessageParser.ParseDeleteNoteMessage(message, out noteId);

            NoteAccess.DeleteNote(noteId);

            // Re-broadcast
            this.mServer.BroadcastMessage(message);
        }
Exemplo n.º 20
0
		private void OnStartAudioTriviaRecordingRequestReceived(TriviaMessage message, Socket socket)
		{
			int hour;
			int number;

			MessageParser.ParseStartAudioTriviaRecordingRequest(message, out hour, out number);

			string filename = string.Format("AudioTrivia{0}-{1}", hour, number);

			bool successful = this.mAudioTriviaRecorder.StartRecording(this.mAudioTriviaFilePath, filename);

			TriviaMessage responseMessage = MessageParser.CreateStartAudioTriviaRecordingResponse(successful);

			this.mServer.SendMessageToSpecificClient(responseMessage, socket);
		}
Exemplo n.º 21
0
 private void OnPingMessageReceived(TriviaMessage message, Socket socket)
 {
     // Just send the ping back
     this.mServer.SendMessageToSpecificClient(message, socket);
 }
Exemplo n.º 22
0
		public void SendMessageToServer(TriviaMessage message)
		{
			this.Send(TriviaMessageHelper.Serialize(message));

            if (this.TriviaMessageSent != null)
            {
                this.TriviaMessageSent(message, this.mSocket);
            }

            if (this.mLogging != TriviaMessageLogging.None)
            {
                TriviaMessageLogger.Log(message, "the server", false);
            }
		}
Exemplo n.º 23
0
        protected override void OnTriviaMessageReceived(object sender, EventArgs e, TriviaMessage message, Socket socket)
		{
            if (message.Command != TriviaCommand.AuthenticateRequest &&
                !(this.mAuthenticatedSockets.Contains(socket)))
            {
                // If the user's not authenticated... reject 'em\
                if (this.ExceptionOccurred != null)
                {
                    this.ExceptionOccurred(new Exception("Rejected an unauthenticated message " + message.Command.ToString()));
                }

                return;
            }

			try
			{
				switch (message.Command)
				{
                    // Not used... I think
                    //case TriviaCommand.GetAllQuestionsRequest:
                    //    this.OnGetAllQuestionsRequestReceived(message, socket);
                    //    break;
					case TriviaCommand.OpenQuestionRequest:
						this.OnOpenQuestionRequestReceived(message, socket);
						break;
					case TriviaCommand.GetLatestHourRequest:
						this.OnGetLatestHourRequestReceived(message, socket);
						break;
					case TriviaCommand.UpdateQuestionRequest:
						this.OnUpdateQuestionRequestReceived(message, socket);
						break;
                    case TriviaCommand.EditingQuestion:
                        this.OnEditingQuestionMessageReceived(message, socket);
                        break;
					case TriviaCommand.StartAudioTriviaRecordingRequest:
						this.OnStartAudioTriviaRecordingRequestReceived(message, socket);
						break;
					case TriviaCommand.StopAudioTriviaRecordingRequest:
						this.OnStopAudioTriviaRecordingRequestReceived(message, socket);
						break;
					case TriviaCommand.UpdateAnswerRequest:
						this.OnUpdateAnswerRequestReceived(message, socket);
						break;
					case TriviaCommand.SubmitAnswerRequest:
						this.OnSubmitAnswerRequestReceived(message);
						break;
					case TriviaCommand.GetCompleteHourDataRequest:
						this.OnGetCompleteHourDataRequestReceived(message, socket);
						break;
					case TriviaCommand.GetGlobalDataRequest:
						this.OnGetGlobalDataRequestReceived(message, socket);
						break;
					case TriviaCommand.AddLinkRequest:
						this.OnAddLinkRequestReceived(message, socket);
						break;
                    case TriviaCommand.AuthenticateRequest:
                        this.OnAuthenticateRequestReceived(message, socket);
                        break;
                    case TriviaCommand.ResearcherChanged:
                        this.OnResearcherChangedRequestReceived(message, socket);
                        break;
                    case TriviaCommand.AddNote:
                        this.OnAddNoteReceived(message, socket);
                        break;
                    case TriviaCommand.DeleteNote:
                        this.OnDeleteNoteReceived(message, socket);
                        break;
                    case TriviaCommand.Ping:
                        this.OnPingMessageReceived(message, socket);
                        break;
					default:
						base.OnTriviaMessageReceived(sender, e, message, socket);
						break;
				}

				// Send the generic event up if necessary (for logging)
				if (this.TriviaMessageReceived != null)
				{
					this.TriviaMessageReceived(message);
				}
			}
			catch (Exception ex)
			{
				if (this.ExceptionOccurred != null)
				{
					this.ExceptionOccurred(ex);
				}
				else
				{
					throw;
				}
			}
		}
Exemplo n.º 24
0
		private void OnSubmitAnswerRequestReceived(TriviaMessage message)
		{
			Answer a;

			MessageParser.ParseSubmitAnswerRequest(message, out a);

			AnswerAccess.Submit(a);

			TriviaMessage responseMessage = MessageParser.CreateSubmitAnswerResponse(a);

			this.mServer.BroadcastMessage(responseMessage);
		}
Exemplo n.º 25
0
        public void BroadcastMessage(TriviaMessage message, Socket excludedSocket)
        {
            try
            {
                this.Broadcast(TriviaMessageHelper.Serialize(message), excludedSocket);
            }
            catch (CommunicationException e)
            {
                if (this.ExceptionOccurred != null)
                {
                    this.ExceptionOccurred(e);
                }

                // Server must go on!
                return;
            }

            if (this.TriviaMessageSent != null)
            {
                this.TriviaMessageSent(message, null);
            }

            if (this.mLogging != TriviaMessageLogging.None)
            {
                TriviaMessageLogger.Log(message, "broadcast receipients", false);
            }
        }
Exemplo n.º 26
0
		private void OnGetCompleteHourDataRequestReceived(TriviaMessage message, Socket socket)
        {
            int hourNumber;

            MessageParser.ParseGetCompleteHourDataRequest(message, out hourNumber);

            CompleteHourData chd = GetCompleteHourData(hourNumber);

            int latestHour = this.CalculateLatestHour();
            chd.IsNoLongerCurrentHour = hourNumber < latestHour;

            TriviaMessage responseMessage = MessageParser.CreateGetCompleteHourDataResponse(chd);

            this.mServer.SendMessageToSpecificClient(responseMessage, socket);
        }
Exemplo n.º 27
0
		private void OnStopAudioTriviaRecordingRequestReceived(TriviaMessage message, Socket socket)
		{
			int hour;
			int number;

			MessageParser.ParseStopAudioTriviaRecordingRequest(message, out hour, out number);

			string filename;

			bool successful = this.mAudioTriviaRecorder.StopRecording(out filename);

			TriviaMessage responseMessage = MessageParser.CreateStopAudioTriviaRecordingResponse(successful, filename);

			this.mServer.SendMessageToSpecificClient(responseMessage, socket);
		}
Exemplo n.º 28
0
        private void OnResearcherChangedRequestReceived(TriviaMessage message, Socket socket)
        {
            message.SenderName = "broadcast";  // "...sent to broadcast"

            // 2016 - Purposely not storing / sending researcher state to new players just joining / hour changes.  They'll catch up sooner or later :).

            // Rebroadcast (to everyone)
            this.mServer.BroadcastMessage(message);
        }