Credential saving should work, progressed on choices

This commit is contained in:
Thastertyn 2023-04-29 21:12:59 +02:00
parent 2b70c3a283
commit 94ab336ddb
11 changed files with 181 additions and 161 deletions

View File

@ -0,0 +1,121 @@
package xyz.thastertyn.Login;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class LocalCredentials {
/**
* Checks for already saved credentials, at least if its file exists
* @return <ul>
* <li> {@code true} a file exists </li>
* <li> {@code false} doesn't exist </li>
* </ul>
*/
private String path;
private File credentialsFile;
private File credentialsPath;
public boolean checkForExistingCredentials()
{
if(System.getProperty("os.name").equals("Linux"))
{
// /home/user/.local/share/jecnak/...
path = System.getProperty("user.home") + "/.local/share/jecnak/";
}else if(System.getProperty("os.name").contains("Windows"))
{
// C:\Users\\user\AppData\Roaming\...
path = System.getenv("APPDATA") + "\\jecnak\\";
}else{
return false;
}
credentialsPath = new File(path);
credentialsFile = new File(credentialsPath, "credentials.txt");
if(!credentialsFile.exists())
{
return false;
}
return true;
}
public String[] getCredentialsFile()
{
String[] result = new String[2];
if(credentialsFile == null)
{
return null;
}
try {
BufferedReader reader = new BufferedReader(new FileReader(credentialsFile));
String line = "";
while((line = reader.readLine()) != null)
{
String[] currentValue = line.split("=");
if(currentValue[0].equals("user"))
{
result[0] = currentValue[1];
}else if(currentValue[0].equals("pass"))
{
result[1] = currentValue[1];
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
if(result[0] == null || result[1] == null)
{
return null;
}
return result;
}
public boolean saveCredentials(String[] credentials)
{
if(credentialsFile == null)
{
return false;
}
if(!credentialsFile.exists())
{
try{
credentialsPath.mkdirs();
credentialsFile.createNewFile();
}catch(IOException e)
{
return false;
}
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(credentialsFile));
writer.append("user=" + credentials[0]);
writer.append("\n");
writer.append("pass=" + credentials[1]);
writer.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}

View File

@ -1,12 +1,9 @@
package xyz.thastertyn.Login;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.concurrent.TimeoutException;
import javax.security.auth.login.CredentialException;
@ -21,6 +18,7 @@ public class LoginController {
private WindowBasedTextGUI textGUI;
private xyz.thastertyn.Login.CredentialsInput dialog;
private LocalCredentials localCredentials = new LocalCredentials();
private xyz.thastertyn.Login.Login login = new xyz.thastertyn.Login.Login();
public LoginController(WindowBasedTextGUI textGUI)
@ -30,26 +28,36 @@ public class LoginController {
public void login()
{
dialog = new CredentialsInput();
if(checkForCredentials()) // Credentials exist
String[] credentials;
if(localCredentials.checkForExistingCredentials()) // Credentials exist
{
if(loginUsingCredentials()) // They are accessible and can read them
credentials = localCredentials.getCredentialsFile();
}else{
dialog = new CredentialsInput();
Triplet<String, String, Boolean> data = dialog.showDialog(textGUI); // Failed to get credentials to log in, get them from user
credentials = new String[] {data.getValue0(), data.getValue1()};
if(data.getValue2())
{
return;
localCredentials.saveCredentials(credentials);
}
}
Triplet<String, String, Boolean> data = dialog.showDialog(textGUI); // Failed to get credentials to log in, get them from user
try
{
login.loginJecna(data.getValue0(), data.getValue1());
loginUsingCredentials(credentials);
}
private void loginUsingCredentials(String[] credentials)
{
try {
login.loginJecna(credentials[0], credentials[1]);
}catch (TimeoutException e)
{
MessageDialog.showMessageDialog(textGUI, "Timeout", "The attempt to connect took too long.", MessageDialogButton.Retry,
MessageDialogButton.Abort);
} catch (UnknownHostException e) {
MessageDialog.showMessageDialog(textGUI, "No Internet connection",
"There seems to be no internet connection, reverting to cached data",
"There seems to be a problem with your internet connection",
MessageDialogButton.OK);
login();
} catch (CredentialException e)
@ -66,127 +74,4 @@ public class LoginController {
login();
}
}
/**
* Zkontroluje zda jiz neexistuji ulozene udaje na systemu
* @return <ul>
* <li> {@code true} soubor existuje a neni prazdny </li>
* <li> {@code false} neexistuje, nebo je prazdny </li>
* </ul>
*/
private boolean checkForCredentials()
{
return false;
//File credentials = null;
//if(System.getProperty("os.name").equals("Linux"))
//{
// credentials = new File("~/.local/share/jecnak/credentials.json");
//}else if(System.getProperty("os.name").contains("Windows"))
//{
// credentials = new File(System.getenv("APPDATA\\jecnak\\"));
//}
//if(!credentials.exists() || credentials.length() == 0)
//{
// return false;
//}
//return true;
}
public boolean saveCredentials(String user, String pass)
{
File credentials;
if(System.getProperty("os.name").equals("Linux"))
{
credentials = new File("~/.local/share/jecnak/credentials.json");
}else if(System.getProperty("os.name").contains("Windows"))
{
credentials = new File(System.getenv("APPDATA\\jecnak\\"));
}else{
return false;
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(credentials));
writer.append("username=" + user);
writer.append("password=" + pass);
writer.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private boolean loginUsingCredentials()
{
File credentials;
if(System.getProperty("os.name").equals("Linux"))
{
credentials = new File("~/.local/share/jecnak/credentials.json");
}else if(System.getProperty("os.name").contains("Windows"))
{
credentials = new File(System.getenv("APPDATA\\jecnak\\"));
}else{
return false;
}
if(!credentials.exists() || credentials.length() == 0)
{
return false;
}
String user = "";
String pass = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(credentials));
String line = "";
while((line = reader.readLine()) != null)
{
if(line.matches("^[a-z]\\=.*$"))
{
String key = line.split("=")[0];
String value = line.split("=")[1];
switch(key)
{
case "username":
user = value;
break;
case "password":
pass = value;
break;
default:
continue;
}
}else{
continue;
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
try {
login.loginJecna(user, pass);
} catch (CredentialException | IOException | TimeoutException e) {
e.printStackTrace();
return false;
}
return true;
}
}

View File

@ -0,0 +1,10 @@
package xyz.thastertyn.Scrape;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public abstract class JecnaScrape {
public abstract void download() throws SocketTimeoutException, UnknownHostException, IOException;
}

View File

@ -1,6 +1,7 @@
package xyz.thastertyn.Scrape;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.regex.Pattern;
@ -9,7 +10,6 @@ import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import xyz.thastertyn.Tuples.Pair;
import xyz.thastertyn.Types.Choice;
import xyz.thastertyn.Types.Option;
import xyz.thastertyn.Types.Options;
@ -32,7 +32,7 @@ public class Znamky {
download("https://www.spsejecna.cz/score/student");
}
public void downloadZnamky(Choice choice) throws UnknownHostException, IOException
public void downloadZnamky(Choice choice) throws SocketTimeoutException, UnknownHostException, IOException
{
download(String.format(
"https://www.spsejecna.cz/score/student?schoolYearId=%s&schoolYearHalfId=%s",
@ -67,7 +67,13 @@ public class Znamky {
.map(m -> m.group(1))
.orElse(plnyNazevPredmetu);
predmety.add(new Predmet(jmenoPredmetu));
if(radkyPredmetuHTML[i].get(2).childrenSize() == 0) // Predmet jeste nema vyslednou znamku
{
predmety.add(new Predmet(jmenoPredmetu));
}else{
String vyslednaZnamka = radkyPredmetuHTML[i].get(2).select("a.scoreFinal").text();
predmety.add(new Predmet(jmenoPredmetu, Integer.parseInt(vyslednaZnamka)));
}
for(Element znamkaElement : radkyPredmetuHTML[i].get(1).select("a.score"))
{
@ -77,7 +83,8 @@ public class Znamky {
String textZnamky = znamkaElement.select("span.value").text();
znamka = textZnamky.matches("\\d") ?
Integer.parseInt(textZnamky) :
Integer.parseInt(textZnamky)
:
-1; // Nejspis se jedna o N (Nehodnocen)
// Mala znamka se bude pocitat jako polovicni vaha
@ -112,9 +119,9 @@ public class Znamky {
return predmety;
}
public Pair<Options, Options> getOptions()
public Options[] getOptions()
{
return new Pair<Options, Options>(schoolYearOptions, schoolHalfYearOptions);
return new Options[] {schoolYearOptions, schoolHalfYearOptions};
}
@Override

View File

@ -22,6 +22,6 @@ public class Option {
}
@Override
public String toString() {
return value;
return text;
}
}

View File

@ -16,7 +16,7 @@ import xyz.thastertyn.UserInterface.UpdateListener;
public abstract class JecnaContent {
protected Panel mainPanel;
protected Boolean hasStarted;
protected boolean hasStarted = false;
protected Label borderLabel;
protected UpdateListener listener;
@ -32,7 +32,7 @@ public abstract class JecnaContent {
public boolean hasStarted()
{
return hasStarted.booleanValue();
return hasStarted;
}
public Label getLabel()

View File

@ -48,13 +48,10 @@ public class Znamky extends JecnaContent {
private xyz.thastertyn.Scrape.Znamky znamky;
private UpdateListener listener;
private Boolean hasStarted = Boolean.valueOf(false);
public Znamky(UpdateListener listener)
{
super.mainPanel = this.mainPanel;
super.hasStarted = this.hasStarted;
super.borderLabel = this.borderLabel;
this.listener = listener;
}
@ -79,7 +76,7 @@ public class Znamky extends JecnaContent {
setGUI();
}
hasStarted = true;
super.hasStarted = true;
}
@Override
@ -134,17 +131,16 @@ public class Znamky extends JecnaContent {
}
double prumer = predmet.getVyslednaZnamka();
String pr;
String prumerAsString;
if(predmet.isFinal())
{
int i = (int) prumer;
pr = i + "";
prumerAsString = ((int) prumer) + "";
}else{
pr = String.format("%.2f", prumer);
prumerAsString = String.format("%.2f", prumer);
}
Label vysl = new Label(pr);
Label vysl = new Label(prumerAsString);
vysl.setTheme(colors.get((int) Math.round(prumer)));
@ -155,7 +151,7 @@ public class Znamky extends JecnaContent {
@Override
public void showOptions(WindowBasedTextGUI textGUI) throws IOException {
OptionsDialog d = new OptionsDialog(znamky.getOptions().getValue0(), znamky.getOptions().getValue1());
OptionsDialog d = new OptionsDialog(znamky.getOptions());
Choice c = d.showDialog(textGUI);

View File

@ -25,7 +25,7 @@ public class OptionsDialog extends DialogWindow {
private boolean useData = false;
public OptionsDialog(Options... options)
public OptionsDialog(Options[] options)
{
super("Choose from below");

View File

@ -52,15 +52,14 @@ public class MainWindow {
window.setComponent(mainPanel);
String title = "Jecnak";
Panel content = new Panel();
mainPanel.addComponent(content.withBorder(Borders.singleLine(title)));
mainPanel.addComponent(content.withBorder(Borders.singleLine("Jecnak")));
LoginController controller = new LoginController(textGUI);
controller.login();
window.addWindowListener(new WindowSwitchListener(content, title, textGUI));
window.addWindowListener(new WindowSwitchListener(content, textGUI));
textGUI.addWindowAndWait(window);

View File

@ -1,6 +1,8 @@
package xyz.thastertyn.UserInterface;
public interface UpdateListener {
/**
* Redraw the screen when panel changes due to Choice being used
*/
public void updatePanel();
}

View File

@ -42,7 +42,7 @@ public class WindowSwitchListener implements WindowListener, UpdateListener {
int current = contents.length - 1;
public WindowSwitchListener(Panel holder, String title, WindowBasedTextGUI textGUI)
public WindowSwitchListener(Panel holder, WindowBasedTextGUI textGUI)
{
this.textGUI = textGUI;
holder.addComponent(tabsPanel);