Skip to content

Commit

Permalink
Merge pull request #65 from Academic-Weapons/dev
Browse files Browse the repository at this point in the history
merge dev into main
  • Loading branch information
mathiasbk1 authored Mar 25, 2023
2 parents efba7ec + 02e8e1e commit df7b154
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 57 deletions.
9 changes: 5 additions & 4 deletions .github/workflows/dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ jobs:
runs-on: ubuntu-latest

steps:
- name: Selenium Test
run: |
python3 /root/ITU2023-DevOps/MiniTwit/tests/selenium_tests.py

- name: Checkout
uses: actions/checkout@v3

Expand Down Expand Up @@ -86,12 +83,16 @@ jobs:
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_KEY }}
script: |
python3 ${{ secrets.TESTS_PATH }}
docker pull magmose1/minitwitimagedev:latest
docker stop minidev || true && docker rm minidev || true
docker run -d -p 8082:8080 --name minidev magmose1/minitwitimagedev:latest
docker ps


# - name: Deploy to server
# # Configure the ~./bash_profile and deploy.sh file on the Vagrantfile
# run: |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,43 @@ public class MiniTwitController {


@GetMapping("/")
public String timeline() {
return "redirect:/public";
public String timeline(Model model, HttpServletRequest request) {
HttpSession session = request.getSession(false);
boolean loggedIn = addUserToModel(model, session);
if (!loggedIn) return "redirect:/public";

List<Object> args = new ArrayList<>();

args.add(session.getAttribute("user_id"));
args.add(session.getAttribute("user_id"));
args.add(PER_PAGE);
List<Map<String, Object>> messages;

try {
messages = sqLite.queryDb(
"select message.*, " +
"user.* from message, " +
"user where message.flagged = 0 " +
"and message.author_id = user.user_id " +
"and (user.user_id = ? or user.user_id in (select whom_id from follower where who_id = ?))" +
"order by message.pub_date desc limit ?"
, args);
System.out.println(messages);
} catch (SQLException e) {
System.out.println("ERROR_" + e);
return "Error";

} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
// System.out.println(messages);
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");
addDatesAndGravatarURLs(messages);

model.addAttribute("messages", messages);
model.addAttribute("messagesSize", messages.size());

return "timeline.html";
}

@RequestMapping(value = "/public", method = RequestMethod.GET)
Expand Down Expand Up @@ -71,18 +106,18 @@ public Object publicTimeline(Model model, HttpServletRequest request) {
}

@GetMapping("/favourites")
public String favourites (HttpServletRequest request, Model model) throws SQLException {
public String favourites(HttpServletRequest request, Model model) throws SQLException {
HttpSession session = request.getSession(false);
model.addAttribute("public", "false");
Boolean loggedIn = addUserToModel(model, session);
if (!loggedIn) {
return "redirect:/public";
return "redirect:/public";
}

List<Map<String, Object>> messages;
try {
List<Object> args = new ArrayList<>();
args.add(getUserID((String)session.getAttribute("user")));
args.add(getUserID((String) session.getAttribute("user")));
args.add(PER_PAGE);
messages = sqLite.queryDb("select message.*, user.* from message inner join user on message.author_id = user.user_id inner join favourite on message.message_id = favourite.message_id where favourite.user_id = ? order by message.pub_date desc limit ?", args);
System.out.println(messages);
Expand All @@ -91,7 +126,7 @@ public String favourites (HttpServletRequest request, Model model) throws SQLExc
return "Error";
}
addDatesAndGravatarURLs(messages);

model.addAttribute("messages", messages);
model.addAttribute("messagesSize", messages.size());

Expand All @@ -105,14 +140,15 @@ public String userTimeLine(@PathVariable("username") String username, HttpServle
model.addAttribute("public", "false");
model.addAttribute("username", username);
Boolean loggedIn = addUserToModel(model, session);

List<Object> arg = new ArrayList<>(); //
arg.add(username); //
List<Map<String, Object>> users; // check if there is a user with this name
users = sqLite.queryDb("select * from user where user.username = ?", arg); // redirect to public if there is no such user
if (users.size()==0) return "redirect:/public"; // todo redirect to error page insted


if (users.size() == 0)
return "redirect:/public"; // todo redirect to error page insted


if (loggedIn) {
//TODO bliver kaldt af favicon ??
// System.out.println("username: " + username);
Expand Down Expand Up @@ -168,7 +204,6 @@ private static boolean addUserToModel(Model model, HttpSession session) {
return true;
} else {
model.addAttribute("user", "false");
System.out.println("no sesh");
return false;
}
}
Expand All @@ -187,7 +222,7 @@ private void addDatesAndGravatarURLs(List<Map<String, Object>> messages) {
public String followUser(@PathVariable("username") String username, HttpServletRequest request, Model model) throws SQLException, ClassNotFoundException {
HttpSession session = request.getSession(false);
// model.addAttribute("public", "false");
Boolean loggedIn = addUserToModel(model, session);
boolean loggedIn = addUserToModel(model, session);

if (!loggedIn) return "redirect:/login";
Integer whomId = getUserID(username);
Expand All @@ -205,7 +240,7 @@ public String followUser(@PathVariable("username") String username, HttpServletR
public String unfollowUser(@PathVariable("username") String username, HttpServletRequest request, Model model) throws SQLException, ClassNotFoundException {
HttpSession session = request.getSession(false);
// model.addAttribute("public", "false");
Boolean loggedIn = addUserToModel(model, session);
boolean loggedIn = addUserToModel(model, session);

if (!loggedIn) return "redirect:/login";
Integer whomId = getUserID(username);
Expand All @@ -215,15 +250,15 @@ public String unfollowUser(@PathVariable("username") String username, HttpServle
List<Object> args = new ArrayList<>();
args.add(session.getAttribute("user_id"));
args.add(whomId);
int result = sqLite.updateDb("delete from follower where who_id=? and whom_id=?", args);
sqLite.updateDb("delete from follower where who_id=? and whom_id=?", args);
return "redirect:/" + username;

}

@PostMapping("/add_message")
public String addMessage(AddMessage text, HttpServletRequest request, Model model) throws SQLException {
HttpSession session = request.getSession(false);


if (session != null && session.getAttribute("user_id") == null) {
//abort 401
Expand All @@ -234,20 +269,20 @@ public String addMessage(AddMessage text, HttpServletRequest request, Model mode
args.add(session.getAttribute("user_id"));
args.add(text.getText());
args.add(System.currentTimeMillis() / 1000);
int result = sqLite.updateDb("insert into message (author_id, text, pub_date, flagged) values (?, ?, ?, 0)", args);
sqLite.updateDb("insert into message (author_id, text, pub_date, flagged) values (?, ?, ?, 0)", args);

}

return "redirect:/public";
}

@GetMapping("/addMessageToFavourites/{messageID}")
public String addMessageToFavourites(@PathVariable("messageID") String messageID, HttpServletRequest request, Model model) throws SQLException, ClassNotFoundException {
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("user_id") == null) {
return "401";
}

List<Object> args = new ArrayList<>();
args.add(session.getAttribute("user_id"));
args.add(messageID);
Expand Down
24 changes: 8 additions & 16 deletions MiniTwit/src/main/java/dk/itu/minitwit/database/SQLite.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Expand All @@ -32,9 +31,6 @@ public class SQLite {



// private Connection connectDb() throws SQLException, ClassNotFoundException {
// return DriverManager.getConnection("jdbc:sqlite:" + DATABASE_URL);
// }

private Connection connectDb() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Expand Down Expand Up @@ -112,41 +108,38 @@ public int updateDb(String query, List<Object> args) throws SQLException {
}


public int insertMessage(int userId, SimData data) throws SQLException, ClassNotFoundException {
public void insertMessage(int userId, SimData data) throws SQLException, ClassNotFoundException {
String query = "INSERT INTO message (author_id, text, pub_date, flagged) VALUES (?, ?, ?, 0)";
try (Connection conn = connectDb();
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setInt(1, userId);
stmt.setString(2, data.getContent());
stmt.setInt(3, (int) (System.currentTimeMillis()));
int rs = stmt.executeUpdate();
return rs;
stmt.setLong(3, System.currentTimeMillis()/1000);
stmt.executeUpdate();
}
}

public int register(Register register) throws SQLException {
public void register(Register register) throws SQLException {
String query = "insert into user (username, email, pw_hash) values (?, ?, ?)";
try (Connection conn = connectDb();
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setString(1, register.getUsername());
stmt.setString(2, register.getEmail());
stmt.setString(3, passwordEncoder.encode(register.getPwd()));
int rs = stmt.executeUpdate();
return rs;
stmt.executeUpdate();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}

public int unfollow(int userId, int unfollowsUserId) throws SQLException, ClassNotFoundException {
public void unfollow(int userId, int unfollowsUserId) throws SQLException, ClassNotFoundException {
String query = "DELETE FROM follower WHERE who_id=? AND whom_id=?";
try (Connection conn = connectDb();
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setInt(1, userId);
stmt.setInt(2, unfollowsUserId);

int rs = stmt.executeUpdate();
return rs;
stmt.executeUpdate();
}
}

Expand All @@ -156,8 +149,7 @@ public int follow(int userId, int followUserId) throws SQLException {
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setInt(1, userId);
stmt.setInt(2, followUserId);
int rs = stmt.executeUpdate();
return rs;
return stmt.executeUpdate();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
Expand Down
17 changes: 2 additions & 15 deletions MiniTwit/src/main/resources/templates/timeline.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,17 @@
<head>
<meta charset="UTF-8">
<link th:href="@{/styles/style.css}" rel="stylesheet" type="text/css" href="/styles/style.css" media="all"/>
<!-- <title><!DOCTYPE html>-->
<!-- <html xmlns:th="http://www.thymeleaf.org">-->
<!-- <head>-->
<!-- <title th:if="${request.endpoint == 'public_timeline'}">Public Timeline</title>-->
<!-- <title th:if="${request.endpoint == 'user_timeline'}">-->
<!-- <span th:text="${profile_user.username}"></span>'s Timeline-->
<!-- </title>-->
<!-- <title th:if="${request.endpoint != 'public_timeline' and request.endpoint != 'user_timeline'}">-->
<!-- My Timeline-->
<!-- </title>-->

</head>
<body>
<!--<div th:insert="~{layout.html :: header}"></div>-->
<!--<h2 th:text="Title" class="test"></h2>-->
<!--<div th:if="${g.user}">-->



<!--</div>-->
<div class="page" th:fragment="header">
<h1>MiniTwit</h1>
<div class="navigation">
<div th:if="${user != 'false'}">
<a th:href="@{/{user}(user=${user})}">my timeline</a> |
<a th:href="@{/}">my timeline</a> |
<a th:href="@{/public}">public timeline</a> |
<a th:href="@{/favourites}">my favourites</a> |
<a th:href="@{/logout}">sign out [<span th:text="${user}">Username</span>]</a>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
package dk.itu.minitwit;

import dk.itu.minitwit.database.SQLite;
import dk.itu.minitwit.domain.SimData;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.SQLException;

@SpringBootTest
class MiniTwitApplicationTests {

//
// @Test
// void contextLoads() {
//
// }
//
// @Test
// void simInsertWorksAsIntended () throws SQLException, ClassNotFoundException {
// SQLite sql = new SQLite();
// SimData data = new SimData();
// data.setContent("asd dsa ");
//
// sql.insertMessage(1, data);
// }



}
55 changes: 55 additions & 0 deletions MiniTwit/tests/selenium_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import unittest
from random import choice
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from string import ascii_letters


class MiniTest(unittest.TestCase):

def setUp(self):
options = Options()
options.add_argument('--headless')
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
self.driver = webdriver.Chrome(executable_path="/root/chromedriver",options=options)
self.rand_username = ''.join(choice(ascii_letters) for _ in range(10))
self.rand_password = ''.join(choice(ascii_letters) for _ in range(10))

def test_register_login(self):
driver = self.driver
driver.get("http://146.190.207.33:8081/public")

elem = driver.find_element(By.LINK_TEXT, "sign up")
elem.click()
self.assertIn("Sign Up", driver.title)

wait = WebDriverWait(driver, 5)
wait.until(EC.presence_of_all_elements_located((By.NAME, 'username')))

driver.find_element(By.NAME, 'username').send_keys(self.rand_username)
driver.find_element(By.NAME, 'email').send_keys(f"{self.rand_username}@test.dk")
driver.find_element(By.NAME, 'password').send_keys(self.rand_username)
repass_input = driver.find_element(By.NAME, 'password2')
repass_input.send_keys(self.rand_username)
repass_input.send_keys(Keys.RETURN)

self.assertIn("Sign In", driver.title)

driver.find_element(By.NAME, 'username').send_keys(self.rand_username)
pass_input = driver.find_element(By.NAME, 'password')
pass_input.send_keys(self.rand_username)
pass_input.send_keys(Keys.RETURN)

self.assertIn("my favourites", driver.page_source)


def tearDown(self):
self.driver.close()

if __name__ == "__main__":
unittest.main()

0 comments on commit df7b154

Please sign in to comment.