Skip to content

Commit

Permalink
Merge pull request #74 from msi-se/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
TobiTgl authored Jun 10, 2024
2 parents 78d9270 + 8826907 commit 0d4c403
Show file tree
Hide file tree
Showing 32 changed files with 1,342 additions and 267 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package de.htwg_konstanz.mobilelearning.helper.moodle;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

/**
* Moodle service that returns moodle courses of a user.
*/
Expand All @@ -35,13 +36,12 @@ public Boolean login() {
// get the token from
// https://moodle.htwg-konstanz.de/moodle/login/token.php?username=USERNAME&password=PASSWORD&service=SERVICESHORTNAME
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet("https://moodle.htwg-konstanz.de/moodle/login/token.php?username="
+ this.username + "&password=" + this.password + "&service=moodle_mobile_app");
HttpGet request = new HttpGet("https://moodle.htwg-konstanz.de/moodle/login/token.php?username=" + this.username + "&password=" + URLEncoder.encode(this.password, "UTF-8") + "&service=moodle_mobile_app");
MoodleTokenResponse tokenResponse = mapper.readValue(client.execute(request).getEntity().getContent(),
MoodleTokenResponse.class);
this.token = tokenResponse.token;
// System.out.println("Successfully logged in as " + this.username + " with
// token " + this.token.substring(0, 5) + "...");
System.out.println("Successfully logged in as " + this.username + " with token " + this.token.substring(0, 5) + "...");
System.out.println(tokenResponse);

// get user id
String wsFunction = "core_webservice_get_site_info";
Expand All @@ -65,6 +65,7 @@ public Boolean login() {

} catch (Exception e) {
System.out.println("Error while logging into moodle: " + e.getMessage());
System.out.println(e);
return false;
}

Expand All @@ -82,7 +83,11 @@ public List<MoodleCourse> getCourses() {

// TEMP: mock the special users (Prof, Student, Admin)
if (this.username.startsWith("Prof") || this.username.startsWith("Student") || this.username.startsWith("Admin")) {
return List.of(new MoodleCourse("1"), new MoodleCourse("2"), new MoodleCourse("3"), new MoodleCourse("940"));
List<MoodleCourse> courses = new ArrayList<MoodleCourse>();
for (Integer i = 1; i <= 1000; i++) {
courses.add(new MoodleCourse(i.toString()));
}
return courses;
}

// if courses are already set return them if not fetch them
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ public Boolean addResult(Result result) {
// check if the user already submitted a result
for (Result r : this.results) {
if (r.hashedUserId != null && r.hashedUserId.equals(result.hashedUserId)) {
System.out.println("User already submitted a result for this question.");
return false;
}
if (r.userId != null && r.userId.equals(result.userId)) {
System.out.println("User already submitted a result for this question.");
return false;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,6 @@ public Integer getParticipantsAnsweredCorrectly(ObjectId id) {
if (result.getGainedPoints() > 0) {
count++;
}
break;
}
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ public class LiveQuizSocket {
@Inject
StatsService statsService;

private void log(String message) {
System.out.println("LiveQuizSocket: " + message);
}

/**
* Method called when a new connection is opened.
* User has to either (student & participant of the session) or owner of the
Expand All @@ -81,33 +85,34 @@ public void onOpen(
// userId from Jwt has to match userId from path
if (!jwtService.getJwtClaims(jwt).getSubject().equals(userId)) {
connections.remove(session.getId());
log(String.format("User %s not authorized (jwt does not match userId)", userId));
session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "User not authorized"));
return;
}

// check if course, form and user exist
Course course = courseRepository.findById(new ObjectId(courseId));
if (course == null) {
System.out.println("Course not found");
log(String.format("Course %s not found", courseId));
session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Course not found"));
return;
}
QuizForm form = course.getQuizFormById(new ObjectId(formId));
if (form == null) {
System.out.println("Form not found");
log(String.format("Form %s not found", formId));
session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Form not found"));
return;
}
User user = userRepository.findById(new ObjectId(userId));
if (user == null) {
System.out.println("User not found");
log(String.format("User %s not found", userId));
session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "User not found"));
return;
}

// check if user is student of the course
if (!course.isStudent(userId) && !course.isOwner(userId)) {
System.out.println("User is not a student of the course");
log(String.format("User %s is not a student of the course %s", user.getUsername(), course.getName()));
session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "User is not a student of the course"));
return;
}
Expand All @@ -116,7 +121,7 @@ public void onOpen(
Boolean isParticipant = form.isParticipant(userId);
Boolean isOwner = course.isOwner(userId);
if (!isParticipant && !isOwner) {
System.out.println(String.format("User %s is not a participant or owner of the form", user.getUsername()));
log(String.format("User %s is not a participant or owner of the form", user.getUsername()));
session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, String.format("User %s is not a participant or owner of the form", user.getUsername())));
return;
}
Expand All @@ -126,6 +131,7 @@ public void onOpen(

// add the connection to the list
SocketConnection socketMember = new SocketConnection(session, courseId, formId, userId, type);
log(String.format("User %s connected as %s", user.getUsername(), type));
connections.put(session.getId(), socketMember);

// send a message to the owner to notify that a new participant has joined
Expand Down Expand Up @@ -195,6 +201,7 @@ private void sendMessageToUser(User user, LiveQuizSocketMessage message) {
@OnClose
public void onClose(Session session, @PathParam("courseId") String courseId, @PathParam("formId") String formId,
@PathParam("userId") String userId) {
log(String.format("User %s disconnected", userId));
connections.remove(session.getId());
}

Expand Down Expand Up @@ -275,6 +282,7 @@ private void broadcast(LiveQuizSocketMessage message, String courseId, String fo

// send the message
String messageString = messageToSend.toJson();
log("SEND: " + messageString);
connection.session.getAsyncRemote().sendObject(messageString, result -> {
if (result.getException() != null) {
System.out.println("Unable to send message: " + result.getException());
Expand All @@ -287,20 +295,31 @@ private Boolean evaluateMessage(LiveQuizSocketMessage quizSocketMessage, String

// evaluate action
if (quizSocketMessage.action == null || quizSocketMessage.action.equals("")) {
System.out.println("Action is null");
log("Action is invalid");
return false;
}

if (quizSocketMessage.action.equals("FUN")) {
return this.fun(quizSocketMessage, formId);
}

log("RECEIVED: " + quizSocketMessage.toJson());

// if the user is not an owner or participant, return
User user = userRepository.findById(new ObjectId(userId));
if (user == null) { return false; }
if (user == null) {
log(String.format("User %s not found", userId));
return false;
}
Course course = courseRepository.findById(new ObjectId(courseId));
if (course == null) { return false; }
if (!course.isOwner(userId) && !course.isStudent(userId)) { return false; }
if (course == null) {
log(String.format("Course %s not found", courseId));
return false;
}
if (!course.isOwner(userId) && !course.isStudent(userId)) {
log(String.format("User %s is not a student or owner of the course", user.getUsername()));
return false;
}

if (quizSocketMessage.action.equals("CHANGE_FORM_STATUS")) {
return this.changeFormStatus(quizSocketMessage, course, formId, user);
Expand All @@ -319,37 +338,36 @@ private Boolean evaluateMessage(LiveQuizSocketMessage quizSocketMessage, String

private Boolean changeFormStatus(LiveQuizSocketMessage quizSocketMessage, Course course, String formId, User user) {

System.out.println("Change form status");

// user must be owner of the course
if (!course.isOwner(user.getId())) {
System.out.println("User is not owner of the course");
log(String.format("User %s is not owner of the course", user.getUsername()));
return false;
}

// evaluate formStatus
if (quizSocketMessage.formStatus == null || quizSocketMessage.formStatus.equals("")
|| FormStatus.valueOf(quizSocketMessage.formStatus) == null) {
System.out.println("Form status is invalid");
log(String.format("Form status %s is invalid", quizSocketMessage.formStatus));
return false;
}

// get the enum value of the formStatus
FormStatus formStatusEnum = FormStatus.valueOf(quizSocketMessage.formStatus);
System.out.println("Form status enum: " + formStatusEnum);

// get the form
QuizForm form = course.getQuizFormById(new ObjectId(formId));
if (form == null) {
System.out.println("Form not found");
log(String.format("Form %s not found", formId));
return false;
}

// change the form status
form.setStatus(formStatusEnum);
log(String.format("Form status of form %s changed to %s", formId, formStatusEnum.toString()));

// if it is set to NOT_STARTED, remove all results
if (formStatusEnum == FormStatus.NOT_STARTED) {
log("Clear results and participants of quiz form");
form.clearResults();
form.clearParticipants();
form.currentQuestionIndex = 0;
Expand All @@ -361,6 +379,7 @@ private Boolean changeFormStatus(LiveQuizSocketMessage quizSocketMessage, Course

// if it is set to STARTED set the timestamp
if (formStatusEnum == FormStatus.STARTED) {
log("Set start timestamp of quiz form");
form.setStartTimestamp();
}

Expand All @@ -370,8 +389,7 @@ private Boolean changeFormStatus(LiveQuizSocketMessage quizSocketMessage, Course

// update the userstats of the participants and the global stats
if (formStatusEnum == FormStatus.FINISHED) {
System.out.println("Update user stats for quiz form");
System.out.println(form.getParticipants().size());
log("Update user stats and increment completed quiz forms");
this.userService.updateUserStatsByQuizForm(form);
this.statsService.incrementCompletedQuizForms();
}
Expand All @@ -385,33 +403,31 @@ private Boolean changeFormStatus(LiveQuizSocketMessage quizSocketMessage, Course

private Boolean addResult(LiveQuizSocketMessage quizSocketMessage, Course course, String formId, User user) {

System.out.println("Add result");

// evaluate resultElementId
if (quizSocketMessage.resultElementId == null || quizSocketMessage.resultElementId.equals("")) {
System.out.println("Result questionwrapper ID is invalid");
log(String.format("Result element ID %s is invalid", quizSocketMessage.resultElementId));
return false;
}

// evaluate resultValue
if (quizSocketMessage.resultValues == null || quizSocketMessage.resultValues.size() < 1
|| quizSocketMessage.resultValues.get(0).equals("")) {
System.out.println("Result value is invalid");
log("Result values are invalid");
return false;
}

// get the form
QuizForm form = course.getQuizFormById(new ObjectId(formId));
if (form == null) {
System.out.println("Form not found");
log(String.format("Form %s not found", formId));
return false;
}

// get the questionwrapper
System.out.println(quizSocketMessage.resultElementId);
QuestionWrapper questionwrapper = form.getQuestionById(new ObjectId(quizSocketMessage.resultElementId));
if (questionwrapper == null) {
System.out.println("Element not found");
log(String.format("Questionwrapper %s not found", quizSocketMessage.resultElementId));
return false;
}

Expand All @@ -420,14 +436,14 @@ private Boolean addResult(LiveQuizSocketMessage quizSocketMessage, Course course
Result result = new Result(hashedUserId, quizSocketMessage.resultValues);
Boolean wasResultAdded = questionwrapper.addResult(result);
if (!wasResultAdded) {
System.out.println("Result was not added (user probably already submitted a result)");
log(String.format("Result for user %s was not added", user.getUsername()));
return false;
}

// check if the score of the user has to be updated
QuizQuestion question = course.getQuizQuestionById(questionwrapper.getQuestionId());
if (question == null) {
System.out.println("Question not found");
log(String.format("Question %s not found", questionwrapper.getQuestionId()));
return false;
}
if (question.getHasCorrectAnswers()) {
Expand Down Expand Up @@ -457,25 +473,26 @@ private Boolean addResult(LiveQuizSocketMessage quizSocketMessage, Course course

private Boolean next(LiveQuizSocketMessage quizSocketMessage, Course course, String formId, User user) {

System.out.println("Next");

// user must be owner of the course
if (!course.isOwner(user.getId())) {
System.out.println("User is not owner of the course");
log(String.format("User %s is not owner of the course", user.getUsername()));
return false;
}

// get the form
QuizForm form = course.getQuizFormById(new ObjectId(formId));
if (form == null) {
System.out.println("Form not found");
log(String.format("Form %s not found", formId));
return false;
}

// next question / finish question / finish quiz
List<String> events = form.next();
courseRepository.update(course);

log(String.format("NEXT produced events: %s", events));
log(String.format("Current question index: %d; Current question finished: %b", form.currentQuestionIndex, form.currentQuestionFinished));

// for all events, send a message
events.forEach(event -> {
LiveQuizSocketMessage outgoingMessage = new LiveQuizSocketMessage(event, form.status.toString(), null, null, form);
Expand All @@ -486,8 +503,6 @@ private Boolean next(LiveQuizSocketMessage quizSocketMessage, Course course, Str
}

private Boolean fun(LiveQuizSocketMessage quizSocketMessage, String formId) {

System.out.println("Throw paper plane");

quizSocketMessage = new LiveQuizSocketMessage(quizSocketMessage.action, quizSocketMessage.fun);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import de.htwg_konstanz.mobilelearning.helper.ObjectIdTypeAdapter;
import de.htwg_konstanz.mobilelearning.models.quiz.QuizForm;

Expand Down Expand Up @@ -45,10 +46,10 @@ public LiveQuizSocketMessage(String message) {
this.fun = quizSocketMessage.fun;
this.form = null;

System.out.println("Action: " + this.action);
System.out.println("Form status: " + this.formStatus);
System.out.println("Result element ID: " + this.resultElementId);
System.out.println("Result value: " + this.resultValues);
// System.out.println("Action: " + this.action);
// System.out.println("Form status: " + this.formStatus);
// System.out.println("Result element ID: " + this.resultElementId);
// System.out.println("Result value: " + this.resultValues);
}

public LiveQuizSocketMessage(String action, Fun fun) {
Expand Down
Loading

0 comments on commit 0d4c403

Please sign in to comment.