Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
Added Tests
  • Loading branch information
MrDrache333 committed Oct 8, 2022
1 parent c51a4de commit c124ab4
Show file tree
Hide file tree
Showing 15 changed files with 351 additions and 158 deletions.
8 changes: 1 addition & 7 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1 @@
/config.xml
*.stud
*.DS-Store
/out
/StudIP
/.idea/
/lib/
*.DS-Store
14 changes: 14 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion StudIP-Telegram.iml
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<excludeFolder url="file://$MODULE_DIR$/.idea/libraries" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
<excludeFolder url="file://$MODULE_DIR$/lib" />
<excludeFolder url="file://$MODULE_DIR$/target" />
<excludeFolder url="file://$MODULE_DIR$/data/Files" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
Expand Down Expand Up @@ -62,5 +63,9 @@
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-core:5.3.23" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-jcl:5.3.23" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.33" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.8.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.2.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.8.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.1.2" level="project" />
</component>
</module>
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@
<artifactId>snakeyaml</artifactId>
<version>1.33</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
* The type Hauptklasse.
*/
public class Start {
private static StudipTelegramBot studipTelegramBot;


/**
Expand All @@ -38,7 +37,7 @@ public static void main(String[] args) throws IOException, InitializationExcepti
YAMLConfigHandler configHandler = YAMLConfigHandler.getInstance();
Config config = configHandler.loadConfig();

studipTelegramBot = new StudipTelegramBot(config);
StudipTelegramBot studipTelegramBot = new StudipTelegramBot(config);
studipTelegramBot.initialize();

studipTelegramBot.update();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ public class StudipTelegramBot {
private final Config config;

private Uni uni;
private User user;

private StudIPBot studIPBot;

Expand Down Expand Up @@ -69,7 +68,7 @@ public void initialize() throws InitializationException, MalformedURLException {
}

uni = new Uni(new URL(config.getApi_endpoint()));
user = new User();
User user = new User();
user.setCredentials(new Credentials(config.getApi_username(), config.getApi_password()));
studIPBot = new StudIPBot(uni, user);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class ApiResponseParser {
* @param response the response
* @return the array list
*/
public static ArrayList<Course> parseCourse(RequestResponse response) {
public static ArrayList<Course> parseCourses(RequestResponse response) {
if (response == null || response.getResponseMessage() == null) return new ArrayList<>();
JSONObject json = new JSONObject(response.getResponseMessage());

Expand All @@ -31,21 +31,22 @@ public static ArrayList<Course> parseCourse(RequestResponse response) {
} catch (JSONException e) {
return new ArrayList<>();
}
collection.keySet().forEach(k -> {
JSONObject courseJson = collection.getJSONObject(k);
Course course = new Course(courseJson.getString("title"));
course.setId(courseJson.getString("course_id"));
course.setStartSemester(courseJson.getString("start_semester").substring(courseJson.getString("start_semester").lastIndexOf("/") + 1));
try {
course.setEndSemester(courseJson.getString("end_semester").substring(courseJson.getString("end_semester").lastIndexOf("/") + 1));
} catch (JSONException e) {
course.setEndSemester("");
}
courses.add(course);
});
collection.keySet().forEach(k -> courses.add(parseCourse(collection.getJSONObject(k))));
return courses;
}

private static Course parseCourse(JSONObject courseJson) {
Course course = new Course(courseJson.getString("title"));
course.setId(courseJson.getString("course_id"));
course.setStartSemester(courseJson.getString("start_semester").substring(courseJson.getString("start_semester").lastIndexOf("/") + 1));
try {
course.setEndSemester(courseJson.getString("end_semester").substring(courseJson.getString("end_semester").lastIndexOf("/") + 1));
} catch (JSONException e) {
course.setEndSemester("");
}
return course;
}

/**
* Parse semesters array list.
*
Expand All @@ -64,25 +65,28 @@ static ArrayList<Semester> parseSemesters(RequestResponse response) {
}
collection.keySet().forEach(s -> {
JSONObject semesterJson = collection.getJSONObject(s);
Semester semester = new Semester();
semester.setId(semesterJson.getString("id"));
semester.setTitle(semesterJson.getString("title"));
semester.setToken(semesterJson.getString("token"));
semester.setBegin(new Date(semesterJson.getLong("begin") * 1000));
semester.setEnd(new Date(semesterJson.getLong("end") * 1000));

semesters.add(semester);
semesters.add(parseSemester(semesterJson));
});
return semesters;
}

private static Semester parseSemester(JSONObject semesterJson) {
Semester semester = new Semester();
semester.setId(semesterJson.getString("id"));
semester.setTitle(semesterJson.getString("title"));
semester.setToken(semesterJson.getString("token"));
semester.setBegin(new Date(semesterJson.getLong("begin") * 1000));
semester.setEnd(new Date(semesterJson.getLong("end") * 1000));
return semester;
}

/**
* Parse news array list.
*
* @param response the response
* @return the array list
*/
public static ArrayList<News> parseNews(RequestResponse response) {
public static ArrayList<News> parseAllNews(RequestResponse response) {
if (response == null || response.getResponseMessage() == null) return new ArrayList<>();
JSONObject json = new JSONObject(response.getResponseMessage());
ArrayList<News> news = new ArrayList<>();
Expand All @@ -94,17 +98,21 @@ public static ArrayList<News> parseNews(RequestResponse response) {
}
collection.keySet().forEach(c -> {
JSONObject newsJson = collection.getJSONObject(c);
News news1 = new News();
news1.setId(newsJson.getString("news_id"));
news1.setTopic(newsJson.getString("topic"));
news1.setHtml(newsJson.getString("body_html"));
news1.setDate(new Date(newsJson.getLong("date") * 1000));
news1.setAuthor_id(newsJson.getString("user_id"));
news.add(news1);
news.add(parseNews(newsJson));
});
return news;
}

private static News parseNews(JSONObject newsJson) {
News news = new News();
news.setId(newsJson.getString("news_id"));
news.setTopic(newsJson.getString("topic"));
news.setHtml(newsJson.getString("body_html"));
news.setDate(new Date(newsJson.getLong("date") * 1000));
news.setAuthor_id(newsJson.getString("user_id"));
return news;
}

/**
* Parse top folder stud ip folder.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public void fetchModules() throws IOException, NotLoggedInException, RequestExce
RequestResponse response = restapi.fetchUserModules(user.getUserId());
//Set Userinformations

user.setKurse(ApiResponseParser.parseCourse(response));
user.setKurse(ApiResponseParser.parseCourses(response));
} else throw new NotLoggedInException();
}

Expand Down Expand Up @@ -169,7 +169,7 @@ private void fetchSemesters() throws RequestException, IOException, NotLoggedInE
public void fetchNewsForCourse(Course course) throws IOException, RequestException, NotLoggedInException {
if (loggedIn) {
RequestResponse response = restapi.fetchCourseNews(course.getId());
course.setNews(ApiResponseParser.parseNews(response));
course.setNews(ApiResponseParser.parseAllNews(response));
} else throw new NotLoggedInException();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,10 @@
*/
public class RestAPI {

private final Downloader downloader;
private Credentials credentials;
private URL endpoint;

private final Downloader downloader;

/**
* Instantiates a new Rest.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ public class StandardDownloader implements Downloader {

private static final int BUFFER_SIZE = 1024000000;
private static int downloadCount = 0;
private static long downloadSizeSum = 0;

private final Credentials credentials;

Expand Down Expand Up @@ -74,7 +73,6 @@ public void downloadFile(URL url, StudIPFile file, Path path) throws DownloadExc
outputStream.close();
inputStream.close();
downloadCount++;
downloadSizeSum += file.getFileSize();
} else
throw new DownloadException(status, con.getResponseMessage());
con.disconnect();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,8 @@

import de.oelrichsgarcia.studipTelegramBot.studipTelegramBot.telegram.api.RequestException;
import de.oelrichsgarcia.studipTelegramBot.studipTelegramBot.telegram.api.TelegramApi;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Random;

import static de.oelrichsgarcia.studipTelegramBot.studipTelegramBot.utils.Debugger.Sout;

/**
* The type Telegram bot.
*/
Expand Down Expand Up @@ -37,42 +32,4 @@ public void sendMessage(int chat_id, String text, TelegramApi.parseMode type) th
telegramApi.sendMessage(payload);
}

/**
* Configure default telegram chat id long.
*
* @return the long
*/
public long configureDefaultTelegramChatId() {
//Telegram Default ChatId
Sout("Füge den Bot als Admin in deiner Gruppe hinzu und schreibe ihn an, oder direkt. Schreibe Ihm folgende Indentifikations-ID:");
int rand = Math.abs(new Random().nextInt());
Sout("\"" + rand + "\"");
Sout("Warte auf Nachricht...(Abbruch: Strg+C)");
int chatId = 0;
while (true) {
try {
String response = telegramApi.getUpdates();
//System.out.println(response);
JSONObject json = new JSONObject(response);
JSONArray messages = json.getJSONArray("result");
for (int i = 0; i < messages.length(); i++) {
JSONObject message = messages.getJSONObject(i);
String id = message.getJSONObject("message").getString("text");
if (id.equals("" + rand)) {
chatId = message.getJSONObject("message").getJSONObject("chat").getInt("id");
sendMessage(chatId, "Configuration Successfull!\nYour ChatId is: " + chatId, TelegramApi.parseMode.TEXT);
return chatId;
}
}

} catch (Exception ignored) {
}
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,20 @@ public TelegramApi(String token) {

public void sendMessage(JSONObject payload) throws RequestException {
if (token.equals("")) throw new NullPointerException("Telegram BotToken must not be Null");
httpPost(payload.toString(), "sendMessage");
httpPost(payload.toString());

}

/**
* Function to Push the Content of the given Data to the http endpoint
*
* @param Data The Data
* @param methodName The Method Name
* @param Data The Data
*/
private void httpPost(String Data, String methodName) throws RequestException {
private void httpPost(String Data) throws RequestException {
//Nachricht senden, wenn sie gesendet werden soll
try {
//URL erstellen, HTTP Post mit übergebenen Daten durchführen
URL url = new URL("https://api.telegram.org/bot" + token + "/" + methodName);
URL url = new URL("https://api.telegram.org/bot" + token + "/" + "sendMessage");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
Expand Down Expand Up @@ -60,42 +59,6 @@ private void httpPost(String Data, String methodName) throws RequestException {

}

private String httpGet(String methodName) throws RequestException {
//Nachricht senden, wenn sie gesendet werden soll
try {
//URL erstellen, HTTP Post mit übergebenen Daten durchführen
URL url = new URL("https://api.telegram.org/bot" + token + "/" + methodName);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(false);
conn.setDoInput(true);
conn.setRequestMethod("GET");

//Antwortnachricht lesen
int responseCode = conn.getResponseCode();
String responseMessage = conn.getResponseMessage();

if (responseCode != 200) {
throw new RequestException(responseCode, responseMessage);
}

conn.disconnect();
} catch (IOException ignored) {
}
return null;
}

/**
* Gets updates.
*
* @return the updates
*/
public String getUpdates() throws RequestException {
return httpGet("getUpdates");
}


/**
* The enum Parse mode.
*/
Expand Down
Loading

0 comments on commit c124ab4

Please sign in to comment.