1
0
forked from PGL/Clyde

Merge pull request 'Forum for messaging extension' (#157) from tonitch/Clyde:forum into master

Reviewed-on: PGL/Clyde#157
This commit is contained in:
Debucquoy Anthony 2024-04-21 09:44:25 +02:00
commit 33eb5c0f0c
19 changed files with 593 additions and 86 deletions

View File

@ -13,6 +13,7 @@ import ovh.herisson.Clyde.Tables.UserCurriculum;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@ -149,13 +150,13 @@ public class CourseController {
//Get all the courses followed by an user
@GetMapping("/usercourses/{userId}")
public ResponseEntity<ArrayList<Course>> getAllUserCourses(@PathVariable long userId){
User u = userService.getUserById(userId);
@GetMapping("/usercourses")
public ResponseEntity<List<Course>> getAllUserCourses(@RequestHeader("Authorization") String token){
User u = authServ.getUserFromToken(token);
//We get all the actual curriculums of the user
ArrayList<UserCurriculum> userCurricula = userCurriculumService.findByStudentAndActual(u, true);
ArrayList<Course> toReturn = new ArrayList<>();
List<UserCurriculum> userCurricula = userCurriculumService.findByStudentAndActual(u, true);
List<Course> toReturn = new ArrayList<>();
//We iterate through all the curriculums and we extract the courses
for (int i = 0; i < userCurricula.size(); i++){

View File

@ -0,0 +1,113 @@
package ovh.herisson.Clyde.EndPoints.Msg;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import jakarta.websocket.server.PathParam;
import lombok.AllArgsConstructor;
import ovh.herisson.Clyde.Repositories.CourseRepository;
import ovh.herisson.Clyde.Repositories.Msg.AnswerRepository;
import ovh.herisson.Clyde.Repositories.Msg.ForumRepository;
import ovh.herisson.Clyde.Repositories.Msg.TopicRepository;
import ovh.herisson.Clyde.Responses.UnauthorizedResponse;
import ovh.herisson.Clyde.Services.AuthenticatorService;
import ovh.herisson.Clyde.Services.CourseService;
import ovh.herisson.Clyde.Services.Msg.ForumService;
import ovh.herisson.Clyde.Tables.Course;
import ovh.herisson.Clyde.Tables.Role;
import ovh.herisson.Clyde.Tables.Token;
import ovh.herisson.Clyde.Tables.User;
import ovh.herisson.Clyde.Tables.Msg.Answer;
import ovh.herisson.Clyde.Tables.Msg.Forum;
import ovh.herisson.Clyde.Tables.Msg.Topic;
@RestController
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
@AllArgsConstructor
public class ForumController {
private CourseRepository courseRepo;
private AuthenticatorService authServ;
private ForumService forumServ;
private ForumRepository forumRepo;
private TopicRepository topicRepo;
//// Endpoints to get and create new forums
@GetMapping("/forums/{id}")
public ResponseEntity<List<Forum>> getForumFromCourseId(@RequestHeader("Authorization") String token, @PathVariable long id){
User u = authServ.getUserFromToken(token);
if(u == null){
return new UnauthorizedResponse<>(null);
}
return new ResponseEntity<>(courseRepo.findById(id).getForums(), HttpStatus.OK);
}
@PostMapping("/forums/{id}")
public ResponseEntity<Forum> createForumOfCourse(@RequestHeader("Authorization") String token, @PathVariable long id, @RequestBody Forum data){
User u = authServ.getUserFromToken(token);
Course c = courseRepo.findById(id);
if(!(c.getOwner().equals(u) || u.getRole() == Role.Admin)){
return new UnauthorizedResponse<>(null);
}
forumServ.createForum(c, data);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
//// Endpoints to get and create forum's topic
@GetMapping("/forum/{id}")
public ResponseEntity<List<Topic>> getTopicsFromForumId(@RequestHeader("Authorization") String token, @PathVariable long id){
User u = authServ.getUserFromToken(token);
if(u == null){
return new UnauthorizedResponse<>(null);
}
return new ResponseEntity<>(forumRepo.findById(id).orElse(null).getTopics(), HttpStatus.OK);
}
@PostMapping("/forum/{id}")
public ResponseEntity<Topic> postTopicToForum(@RequestHeader("Authorization") String token, @PathVariable long id, @RequestBody Topic data){
User u = authServ.getUserFromToken(token);
Forum f = forumRepo.findById(id).orElse(null);
if(!(f.getWriters().contains(u) || u.getRole() == Role.Admin)){
return new UnauthorizedResponse<>(null);
}
forumServ.createTopic(f, data);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
//// Endpoints related to topics and messages
@GetMapping("/forum/post/{id}")
public ResponseEntity<Topic> getPost(@RequestHeader("Authorization") String token, @PathVariable long id){
User u = authServ.getUserFromToken(token);
if(u == null){
return new UnauthorizedResponse<>(null);
}
Topic t = topicRepo.findById(id).orElse(null);
return new ResponseEntity<>(t, HttpStatus.OK);
}
@PostMapping("/forum/post/{id}")
public ResponseEntity<Topic> postTopicToForum(@RequestHeader("Authorization") String token, @PathVariable long id, @RequestBody Answer data){
User u = authServ.getUserFromToken(token);
Topic t = topicRepo.findById(id).orElse(null);
if(t.isLocked() && u.getRole() != Role.Admin){
return new UnauthorizedResponse<>(null);
}
System.out.println(data);
forumServ.answerTopic(t, data, u);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
}

View File

@ -0,0 +1,10 @@
package ovh.herisson.Clyde.Repositories.Msg;
import org.springframework.data.repository.CrudRepository;
import ovh.herisson.Clyde.Tables.Msg.Answer;
public interface AnswerRepository extends CrudRepository<Answer, Long> {
}

View File

@ -0,0 +1,9 @@
package ovh.herisson.Clyde.Repositories.Msg;
import org.springframework.data.repository.CrudRepository;
import ovh.herisson.Clyde.Tables.Msg.Forum;
public interface ForumRepository extends CrudRepository<Forum, Long> {
}

View File

@ -0,0 +1,10 @@
package ovh.herisson.Clyde.Repositories.Msg;
import org.springframework.data.repository.CrudRepository;
import ovh.herisson.Clyde.Tables.Msg.Topic;
public interface TopicRepository extends CrudRepository<Topic, Long> {
}

View File

@ -0,0 +1,38 @@
package ovh.herisson.Clyde.Services.Msg;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;
import ovh.herisson.Clyde.Repositories.CourseRepository;
import ovh.herisson.Clyde.Repositories.Msg.ForumRepository;
import ovh.herisson.Clyde.Repositories.Msg.TopicRepository;
import ovh.herisson.Clyde.Tables.Course;
import ovh.herisson.Clyde.Tables.User;
import ovh.herisson.Clyde.Tables.Msg.Answer;
import ovh.herisson.Clyde.Tables.Msg.Forum;
import ovh.herisson.Clyde.Tables.Msg.Topic;
@Service
@AllArgsConstructor
public class ForumService {
private CourseRepository courseRepo;
private ForumRepository forumRepo;
private TopicRepository topicRepo;
public void createForum(Course c, Forum f){
c.addForum(f);
courseRepo.save(c);
}
public void createTopic(Forum f, Topic data) {
f.addTopic(data);
forumRepo.save(f);
}
public void answerTopic(Topic t, Answer data, User u) {
data.setAuthor(u);
t.addAnswer(data);
topicRepo.save(t);
}
}

View File

@ -51,7 +51,7 @@ public class ProtectionService {
HashMap<String ,Object> toReturn = new HashMap<>();
toReturn.put("courseId",course.getCourseID());
toReturn.put("courseID",course.getCourseID());
toReturn.put("credits",course.getCredits());
toReturn.put("title", course.getTitle());
toReturn.put("owner", userWithoutPassword(course.getOwner()));

View File

@ -1,10 +1,20 @@
package ovh.herisson.Clyde.Tables;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import ovh.herisson.Clyde.Tables.Msg.Forum;
import java.util.List;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@ -17,39 +27,18 @@ public class Course {
@JoinColumn(name = "Users")
private User owner;
//// Extension Messagerie /////
@OneToMany(cascade = CascadeType.ALL)
private List<Forum> forums;
public void addForum(Forum f){
forums.add(f);
}
///////////////////////////////
public Course(int credits, String title, User owner){
this.credits = credits;
this.title = title;
this.owner = owner;
}
public Course() {}
public int getCourseID() {
return courseID;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits){
this.credits = credits;
}
public String getTitle() {
return title;
}
public void setTitle(String title){
this.title = title;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
}

View File

@ -0,0 +1,29 @@
package ovh.herisson.Clyde.Tables.Msg;
import java.util.Date;
import org.hibernate.annotations.CreationTimestamp;
import jakarta.persistence.*;
import lombok.Data;
import ovh.herisson.Clyde.Tables.User;
@Entity
@Data
public class Answer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@CreationTimestamp
private Date creation;
private String content;
@ManyToOne(cascade=CascadeType.ALL)
private User author;
private boolean anonymous;
}

View File

@ -0,0 +1,35 @@
package ovh.herisson.Clyde.Tables.Msg;
import java.util.List;
import jakarta.persistence.*;
import lombok.Data;
import ovh.herisson.Clyde.Tables.Course;
import ovh.herisson.Clyde.Tables.User;
@Entity
@Data
public class Forum {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToOne
private Course course;
private String name;
@OneToMany(cascade = CascadeType.ALL)
private List<Topic> topics;
public void addTopic(Topic t) {
topics.add(t);
}
@OneToMany
private List<User> writers; // User who are authorized to create a post
@OneToMany
private List<User> register;
}

View File

@ -0,0 +1,31 @@
package ovh.herisson.Clyde.Tables.Msg;
import java.util.List;
import jakarta.persistence.*;
import lombok.Data;
import ovh.herisson.Clyde.Tables.User;
@Entity
@Data
public class Topic {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String subject, content;
@ManyToOne
private User author;
@OneToMany(cascade = CascadeType.ALL)
private List<Answer> answers;
public void addAnswer(Answer a){
answers.add(a);
}
private boolean locked; // true if new messages can be posted
}

View File

@ -11,6 +11,7 @@ import ovh.herisson.Clyde.Tables.Msg.Message;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name = "Users")
public class User {
@ -27,7 +28,6 @@ public class User {
private Date birthDate;
private String profilePictureUrl;
private Role role;
@JsonIgnore
private String password;

View File

@ -1,10 +1,17 @@
package ovh.herisson.Clyde.Tables;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserCurriculum {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@ -26,48 +33,10 @@ public class UserCurriculum {
//True if the user has that curriculum at the moment false if not
private boolean actual;
public UserCurriculum(User user, Curriculum curriculum, int year, boolean actual){
this.user = user;
this.curriculum = curriculum;
public UserCurriculum(User u, Curriculum cu, int year, boolean actual){
this.user = u;
this.curriculum = cu;
this.year = year;
this.actual = actual;
}
public UserCurriculum() {}
public int getId() {
return id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Curriculum getCurriculum() {
return curriculum;
}
public void setCurriculum(Curriculum curriculum) {
this.curriculum = curriculum;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public void setActual(boolean actual) {
this.actual = actual;
}
public boolean isActual() {
return actual;
}
}

View File

@ -60,6 +60,9 @@ Curriculum=curriculum
Credits=Credits
InscriptionService=I.S.
faculty=Faculty
forum.create=Create forum
forum.create.name=New forum's name
forum.post.create.name=New post's title
firstname/name=Firstname/Name
regNo=regNo
From=From

View File

@ -60,6 +60,9 @@ Curriculum=Cursus
Credits=Credits
InscriptionService=S.I.
faculty=Faculté
forum.create=Créer un forum
forum.create.name=Nom du forum
forum.post.create.name=Titre du post
firstname/name=Prénom/Nom
regNo=Matricule
From=De

View File

@ -0,0 +1,215 @@
<!----------------------------------------------------
File: Forums.vue
Author: Anthony Debucquoy
Scope: Extension messagerie
Description: Forum des étudiants
----------------------------------------------------->
<script setup>
import { ref, reactive } from 'vue'
import i18n from '@/i18n.js'
import { getCourses, getUserActualCourses } from '@/rest/courses.js'
import { ForumsOfCurrentCourse, getForumsOfCourse, createForum } from '@/rest/forum.js'
import { PostsOfCurrentForum, getPostsOfForum, createPost } from '@/rest/forum.js'
import { fetchedPost, fetchPost, sendAnswer } from '@/rest/forum.js'
import { getSelf } from '@/rest/Users.js'
const Role = (await getSelf()).role;
const courses = Role === 'Admin' || Role === 'Secretary' ? await reactive(getCourses()) : await reactive(getUserActualCourses());
const selectedCourse = ref();
const selectedForum = ref();
const addForumName = ref("");
const addPost = ref(false);
const addPostSubject = ref("");
const addPostContent = ref("");
</script>
<template>
<div id="app">
<div id="ForumSelector">
<select id="cours" value="" v-model="selectedCourse" @change="getForumsOfCourse(selectedCourse)">
<option v-for="course in courses" :value="course.courseID">{{course.title}}</option>
</select>
<select id="forum" value="" v-model="selectedForum" @change="getPostsOfForum(selectedForum !== 'create' ? selectedForum : null)" v-if="ForumsOfCurrentCourse != null">
<option v-for="forum in ForumsOfCurrentCourse" :value=forum.id>{{forum.name}}</option>
<option v-if="(Role === 'Admin' || Role === 'Teacher') && ForumsOfCurrentCourse != null" value="create">{{ i18n("forum.create") }}</option>
</select>
</div>
<div id="PostSelector" v-if="PostsOfCurrentForum != null">
<div @click="fetchPost(post.id)" class="postItem" v-for="post in PostsOfCurrentForum" :key="post.id">{{ post.subject }}</div>
<button v-if="Role === 'Admin' || Role === 'Teacher' " id="createPost" @click="addPost = true">+</button>
</div>
<div id="PostViewer" v-if="fetchedPost != null">
<div id="Post">
<h1>{{ fetchedPost.subject }}</h1>
{{fetchedPost.content}}
</div>
<div id="Messages">
<p v-for="msg in fetchedPost.answers">{{msg.author.firtName}} {{msg.author.lastName}} - {{msg.content}}</p>
<input v-if=!fetchedPost.locked type="text" placeholder="response" @keyup.enter="sendAnswer(fetchedPost.id, $event.target.value); $event.target.value = ''"/>
</div>
</div>
</div>
<div class=popup v-if="selectedForum === 'create' || addPost" @click.self="selectedForum = ''; addPost = false" >
<!-- Popup to add forum -->
<div id="addForumForm" v-if="selectedForum === 'create'" @keyup.enter="createForum(selectedCourse, addForumName); selectedForum = '';">
<label>{{ i18n("forum.create.name") }}</label>
<input type="text" placeholder="Name" v-model=addForumName />
</div>
<!-- Popup to add Post -->
<div id="addPostForm" v-if=addPost>
<label>{{ i18n("forum.post.create.name") }}</label>
<input type="text" placeholder="subject" v-model=addPostSubject @keyup.enter="createPost(selectedForum, addPostSubject, addPostContent); addPost = false;"/>
<textarea v-model="addPostContent" placeholder=content></textarea>
<input type="submit" value="send" @click="createPost(selectedForum, addPostSubject, addPostContent); addPost = false;">
</div>
</div>
</template>
<style scoped>
.popup{
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #00000022;
z-index: 9;
}
#addForumForm{
position: relative;
width: 30%;
left: calc(50% - 30% / 2);
top: calc(50% - 10% / 2);
border-radius: 10px;
height: 10%;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
#addPostForm{
position: relative;
width: 30%;
left: calc(50% - 30% / 2);
top: calc(50% - 50% / 2);
border-radius: 10px;
height: 50%;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
gap: 10px;
}
#app{
display: grid;
width: 100%;
height: 100%;
grid-template: 5em auto / 25% 75%;
}
#ForumSelector{
background-color: #FFFFFF0E;
grid-column: 1 / 3;
border-radius: 100px;
margin: 10px;
display: flex;
justify-content: space-around;
}
#ForumSelector select{
background-color: #ffa000;
border: none;
margin: 10px;
border-radius: 10px;
width: 200px;
text-align: center;
}
#PostSelector button{
background-color: green;
color: white;
border: none;
height: 4vh;
margin: 5px;
border-radius: 0 30px 30px 0;
align-items: center;
justify-content: center;
}
#PostSelector{
background-color: #FFFFFF0E;
border-radius: 0 25px 25px 0;
margin: 10px 0 10px 10px;
overflow: hidden;
padding: 10px;
display: flex;
flex-direction: column;
}
.postItem{
color: darkorange;
display: flex;
font-family: sans-serif;
font-weight: bold;
height: 4vh;
margin: 5px;
border-radius: 0 30px 30px 0;
align-items: center;
justify-content: center;
border: 1px solid darkorange;
}
.postItem:hover{
background-color: gray;
}
#PostViewer{
background-color: #FFFFFF0E;
border-radius: 25px;
margin: 10px;
max-height: 100%;
overflow: scroll;
}
#Post{
padding: 25px;
color: white;
}
#Post > h1{
text-align: center;
text-decoration: underline;
}
#Messages{
padding: 25px;
border-top: 3px dotted white;
}
#Messages > p {
background-color: orange;
}
</style>

View File

@ -9,6 +9,7 @@ import Courses from "@/Apps/ManageCourses.vue"
import Users from "@/Apps/UsersList.vue"
import Students from "@/Apps/StudentsList.vue"
import Msg from "@/Apps/Msg.vue"
import Forums from '@/Apps/Forums.vue'
import Payments from "@/Apps/Inscription/PaymentInfo.vue";
import ManageRequests from "@/Apps/Inscription/ManageRequests.vue";
@ -20,13 +21,14 @@ const apps = {
'/users-list' : Users,
'/students-list' : Students,
'/msg' : Msg,
'/forums': Forums,
'/payments': Payments
}
const appsList = {
'Msg': { path: '#/msg', icon: 'fa-comment', text: i18n("app.messages") },
'Notification': { path: '#/notifs', icon: 'fa-bell', text: i18n("app.notifications") },
'Forum': { path: '#/forum', icon: 'fa-envelope', text: i18n("app.forum") },
'Forum': { path: '#/forums', icon: 'fa-envelope', text: i18n("app.forum") },
'Schedule': { path: '#/schedule', icon: 'fa-calendar-days', text: i18n("app.schedules") },
'Requests': { path: '#/requests', icon: 'fa-users', text: "Requests" },
'ManageCourses': { path: '#/manage-courses', icon: 'fa-book', text: i18n("app.manage.courses") },

View File

@ -76,6 +76,6 @@ export async function alterCourse(id, changes){
* Return a list containing all the actual courses of a user
*/
export async function getUserActualCourses(userId){
return restGet("/usercourses/"+userId)
export async function getUserActualCourses(){
return restGet("/usercourses")
}

View File

@ -0,0 +1,50 @@
/*******************************************************
* File: forum.js
* Author: Anthony Debucquoy
* Scope: Extension messagerie
* Description: Forum related functions and calls
*******************************************************/
import { ref } from 'vue'
import { restGet, restPost, restDelete, restPatch } from './restConsumer.js'
/**
* List forums of a course
*/
export async function getForumsOfCourse(id){
ForumsOfCurrentCourse.value = await restGet("/forums/" + id)
}
export const ForumsOfCurrentCourse = ref();
export function createForum(id, name){
restPost("/forums/" + id, {name: name}).then(_ => getForumsOfCourse(id));
}
/**
* List post of a specified forum
*/
export async function getPostsOfForum(id){
if(id != null){
PostsOfCurrentForum.value = await restGet("/forum/" + id);
}
}
export function createPost(id, subject, content){
restPost("/forum/" + id, {subject: subject, content: content}).then(_ => getPostsOfForum(id));
}
export const PostsOfCurrentForum = ref();
/**
* Get a post and its responses
*/
export async function fetchPost(id){
fetchedPost.value = await restGet("/forum/post/" + id);
}
export function sendAnswer(id, content){
restPost("/forum/post/" + id, {content: content}).then(_ => fetchPost(id))
}
export const fetchedPost = ref();