diff --git a/downloader/CurseForgeModFile.java b/downloader/CurseForgeModFile.java index dd364c4..21ca2f1 100644 --- a/downloader/CurseForgeModFile.java +++ b/downloader/CurseForgeModFile.java @@ -1,30 +1,30 @@ package downloader; -public class CurseForgeModFile extends ProjectInfo{ +public class CurseForgeModFile extends ProjectInfo { + private int projectID; + private int fileID; + private boolean clientOnly; + + public CurseForgeModFile(ProjectInfo pj, int projectID, int fileID, boolean clientOnly) { + this(pj.getSlug(), pj.getName(), pj.getDesc(), projectID, fileID, clientOnly); + } - private int projectID; - private int fileID; - private boolean clientOnly; - - public CurseForgeModFile(ProjectInfo pj,int projectID,int fileID,boolean clientOnly) - { - this(pj.getSlug(),pj.getName(),pj.getDesc(),projectID,fileID,clientOnly); - } - - public CurseForgeModFile(String slug, String name, String desc,int projectID,int fileID,boolean clientOnly) { - super(slug, name, desc); - this.projectID=projectID; - this.fileID=fileID; - this.clientOnly=clientOnly; - } - - public int getFileID() { - return fileID; - } - public int getProjectID() { - return projectID; - } - public boolean isClientOnly() { - return clientOnly; - } + public CurseForgeModFile(String slug, String name, String desc, int projectID, int fileID, boolean clientOnly) { + super(slug, name, desc); + this.projectID = projectID; + this.fileID = fileID; + this.clientOnly = clientOnly; + } + + public int getFileID() { + return this.fileID; + } + + public int getProjectID() { + return this.projectID; + } + + public boolean isClientOnly() { + return this.clientOnly; + } } diff --git a/downloader/DBConnector.java b/downloader/DBConnector.java index 163ff64..efccb25 100644 --- a/downloader/DBConnector.java +++ b/downloader/DBConnector.java @@ -8,36 +8,28 @@ import java.sql.SQLException; public class DBConnector { private Connection conn; - /** - * Connect to a sample database - * - * @throws SQLException - */ public void connect(String dbFile) throws SQLException { - conn = null; + this.conn = null; try { - // db parameters String url = "jdbc:sqlite:" + dbFile; - Log.i("DB",url); - // create a connection to the database - conn = DriverManager.getConnection(url); - + Log.i("DB", url); + this.conn = DriverManager.getConnection(url); } catch (SQLException e) { System.out.println(e.getMessage()); throw e; - } + } } public void close() throws SQLException { - conn.close(); + this.conn.close(); } public ResultSet executeRequest(String sql) { try { - return conn.createStatement().executeQuery(sql); + return this.conn.createStatement().executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); - } - return null; + return null; + } } -} \ No newline at end of file +} diff --git a/downloader/Database.java b/downloader/Database.java index 63f8091..b375eef 100644 --- a/downloader/Database.java +++ b/downloader/Database.java @@ -1,5 +1,8 @@ package downloader; +import com.google.gson.Gson; +import downloader.forgeSvc.ForgeSvcEntry; +import downloader.forgeSvc.ForgeSvcFile; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; @@ -7,220 +10,211 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; +import java.io.InputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.sql.ResultSet; import java.sql.SQLException; - import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.utils.IOUtils; -import com.google.gson.Gson; - -import downloader.forgeSvc.ForgeSvcEntry; -import downloader.forgeSvc.ForgeSvcFile; - public class Database { - String version; + DBConnector connector; + Gson gson; + IntegrityChecker integrityChecker; - File dbVer; - + + File dbVer = new File("dbVersion"); + public Database() { - dbVer = new File("dbVersion"); - if (dbVer.exists()) { + if (this.dbVer.exists()) { try { - BufferedReader bfr = new BufferedReader(new FileReader(dbVer)); + BufferedReader bfr = new BufferedReader(new FileReader(this.dbVer)); this.version = bfr.readLine(); bfr.close(); - - connector = new DBConnector(); - connector.connect(new File("database.dat").getAbsolutePath()); - - } catch (IOException | SQLException e) { - dbVer.delete(); - version = ""; - } + this.connector = new DBConnector(); + this.connector.connect((new File("database.dat")).getAbsolutePath()); + } catch (IOException|SQLException e) { + this.dbVer.delete(); + this.version = ""; + } } else { - version = ""; - } - gson = new Gson(); - integrityChecker = new IntegrityChecker(); - + this.version = ""; + } + this.gson = new Gson(); + this.integrityChecker = new IntegrityChecker(); } - + public void updateDatabase() { try { + File decompressedDatabase; String dbVersion = HttpHelper.readStringFromUrl("http://files.mcdex.net/data/latest.v5"); - if (dbVersion.equals(version)) { + if (dbVersion.equals(this.version)) { Log.i("DB", "alredy up to date"); return; - } - if (dbVersion.equals("error")) { + } + if (dbVersion.equals("error") || dbVersion.trim().equals("")) { Log.i("DB", "an error ocured"); - return; - } - + System.exit(1); + } + Log.i("DB", "newer version found"); if (!this.version.isEmpty()) { Log.i("DB", "current=" + this.version + " remote=" + dbVersion); } else { Log.i("DB", "new=" + dbVersion); - } - - Log.i("DB", "fetching=" + "http://files.mcdex.net/data/mcdex-v5-" + dbVersion + ".dat.bz2"); + } + Log.i("DB", "fetching=http://files.mcdex.net/data/mcdex-v5-" + dbVersion + ".dat.bz2"); File archive = HttpHelper.readFileFromUrl("http://files.mcdex.net/data/mcdex-v5-" + dbVersion + ".dat.bz2"); Log.i("DB", "download finished"); Log.i("DB", "decompressing db"); - File decompressedDatabase; try { decompressedDatabase = decompressBz2(archive, "database.dat"); } catch (IOException e) { Log.i("DB", "cannot extract database"); return; - } + } Log.i("DB", "done"); Log.i("DB", "loading the database"); - connector = new DBConnector(); + this.connector = new DBConnector(); try { - connector.connect(decompressedDatabase.getAbsolutePath()); + this.connector.connect(decompressedDatabase.getAbsolutePath()); } catch (SQLException e) { return; - } + } Log.i("DB", "database loaded"); this.version = dbVersion; Log.i("DB", "saving db data"); - dbVer.delete(); + this.dbVer.delete(); try { - dbVer.createNewFile(); - PrintWriter p = new PrintWriter(dbVer); - p.print(version); + this.dbVer.createNewFile(); + PrintWriter p = new PrintWriter(this.dbVer); + p.print(this.version); p.close(); } catch (Exception e) { Log.e("DB", "failed to save db"); - } + } } catch (MalformedURLException e) { Log.i("DB", "database link is dead"); System.exit(1); - } + } } - + private File decompressBz2(File inputFile, String outputFile) throws IOException { BZip2CompressorInputStream input = new BZip2CompressorInputStream( - new BufferedInputStream(new FileInputStream(inputFile))); + new BufferedInputStream(new FileInputStream(inputFile))); File decompressedFile = new File(outputFile); FileOutputStream output = new FileOutputStream(decompressedFile); - IOUtils.copy(input, output); + IOUtils.copy((InputStream)input, output); return decompressedFile; } - + private int findProjectBySlug(String slug, int ptype) { int modID = -1; - ResultSet rs = connector.executeRequest("select projectid from projects where type =" + ptype + " and slug =\"" - + slug.trim().toLowerCase() + "\""); + ResultSet rs = this.connector.executeRequest("select projectid from projects where type =" + ptype + " and slug =\"" + + slug.trim().toLowerCase() + "\""); try { if (rs.next()) { modID = rs.getInt("projectid"); } else { Log.e("DB", "not found " + slug); return -1; - } + } } catch (SQLException e) { e.printStackTrace(); return -1; - } + } return modID; } - + private int findModBySlug(String slug) { return findProjectBySlug(slug, 0); } - + private ProjectInfo getProjectInfo(int projectId) { - ResultSet rs = connector.executeRequest( - "select slug, name, description from projects where projectid = " + projectId + " and type = 0"); + ResultSet rs = this.connector.executeRequest( + "select slug, name, description from projects where projectid = " + projectId + " and type = 0"); try { - if (rs.next()) { - return new ProjectInfo(rs.getString("slug"), rs.getString("name"), rs.getString("description")); - } - } catch (SQLException e) { - } + if (rs.next()) + return new ProjectInfo(rs.getString("slug"), rs.getString("name"), rs.getString("description")); + } catch (SQLException sQLException) {} return null; } - + public boolean fetchMod(String string) { String name = string.split("/")[5]; int modID = findModBySlug(name); if (modID == -1) { Log.e("DB", "could not find mod id"); return false; - } - + } ProjectInfo pj = getProjectInfo(modID); if (pj == null) - return false; + return false; CurseForgeModFile modfile = new CurseForgeModFile(pj, modID, -1, false); ForgeSvcFile file = getLastestFile("1.12.2", modfile); - if (file != null) { try { - String downloadUrl = file.getDownloadUrl(modID); - - Log.i("MOD", "checking " + pj.getName().replace(" ", "-")); - // si on connais le mod alors on se base si son fichier sinon on essay de le - // trouver boolean upToDate; - if (integrityChecker.isModIdKnown(modID)) { - Log.i("DB", "found"); - upToDate = integrityChecker - .checkAndDelete(new File("mods/" + HttpHelper.getFileNameFromURL(downloadUrl)), modID); + String downloadUrl = file.getDownloadUrl(modID); + if (Main.isVersbose()) + Log.i("MOD", "checking " + pj.getName().replace(" ", "-")); + if (this.integrityChecker.isModIdKnown(modID)) { + if (Main.isVersbose()) + Log.i("DB", "found " + name); + upToDate = this.integrityChecker + .checkAndDelete(new File("mods/" + HttpHelper.getFileNameFromURL(downloadUrl)), modID); } else { - Log.i("DB", "NEW MOD DETECTED "+modID); - upToDate = integrityChecker.checkAndDelete( - new File("mods/" + HttpHelper.getFileNameFromURL(downloadUrl)), pj.getSlug()); - } + Log.i("DB", "NEW MOD DETECTED " + modID); + upToDate = this.integrityChecker.checkAndDelete( + new File("mods/" + HttpHelper.getFileNameFromURL(downloadUrl)), pj.getSlug()); + } if (!upToDate) { - // on remplace les espace par des tiret pour eviter toute confusion - Log.i("MOD", "downloading " + pj.getName().replace(" ", "-")); - HttpHelper.readFileFromUrlToFolder(downloadUrl, "mods"); - Log.i("MOD", "download finished"); - if (!integrityChecker.isModIdKnown(modID)) { - integrityChecker.addModsToTheList(HttpHelper.getFileNameFromURL(downloadUrl), modID); - Log.i("DB", "added a mod to the registry"); - } - } + if (Main.isVersbose()) + Log.i("MOD", "downloading " + pj.getName().replace(" ", "-")); + if (!Main.isCheckingOnly()) + HttpHelper.readFileFromUrlToFolder(downloadUrl, "mods"); + if (Main.isVersbose()) + Log.i("MOD", "download finished"); + if (!this.integrityChecker.isModIdKnown(modID) && !Main.isCheckingOnly()) { + this.integrityChecker.addModsToTheList(HttpHelper.getFileNameFromURL(downloadUrl), modID); + if (Main.isVersbose()) + Log.i("DB", "added a mod to the registry"); + } + } return true; } catch (MalformedURLException e) { e.printStackTrace(); - } + } } else { Log.e("DB", "no file in server"); - } + } return false; } - + public ForgeSvcFile getLastestFile(String minecraftVer, CurseForgeModFile mod) { - String projectUrl = "https://addons-ecs.forgesvc.net/api/v2/addon/" + mod.getProjectID(); - String jsonProject; + String jsonProject, projectUrl = "https://addons-ecs.forgesvc.net/api/v2/addon/" + mod.getProjectID(); try { jsonProject = HttpHelper.readStringFromUrl(projectUrl); if (jsonProject.equals("error")) - return null; + return null; } catch (MalformedURLException e) { e.printStackTrace(); return null; - } - - ForgeSvcEntry entry = gson.fromJson(jsonProject, ForgeSvcEntry.class); - - for (ForgeSvcFile f : entry.getFiles()) { - if (f.getGameVersion().equals(minecraftVer)) { - return f; - } - } + } + ForgeSvcEntry entry = (ForgeSvcEntry)this.gson.fromJson(jsonProject, ForgeSvcEntry.class); + byte b; + int i; + ForgeSvcFile[] arrayOfForgeSvcFile; + for (i = (arrayOfForgeSvcFile = entry.getFiles()).length, b = 0; b < i; ) { + ForgeSvcFile f = arrayOfForgeSvcFile[b]; + if (f.getGameVersion().equals(minecraftVer)) + return f; + b++; + } return null; } - } diff --git a/downloader/HttpHelper.java b/downloader/HttpHelper.java index 1f6bf63..e3f1669 100644 --- a/downloader/HttpHelper.java +++ b/downloader/HttpHelper.java @@ -4,143 +4,109 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; +import java.nio.file.attribute.FileAttribute; public class HttpHelper { - - public static String readStringFromUrl(String urlToFetch) throws MalformedURLException { - URL url = new URL(urlToFetch); HttpURLConnection con; + URL url = new URL(urlToFetch); try { - con = (HttpURLConnection) url.openConnection(); + con = (HttpURLConnection)url.openConnection(); } catch (IOException e1) { e1.printStackTrace(); return "error"; - } - + } String str = ""; - - try (InputStream in = con.getInputStream()) { - // par tranche de 4mo - for (;;) { - byte[] buffer = new byte[4096]; - int nbBytesRead = in.read(buffer); - if (nbBytesRead < 0) - break; - - for (int i = 0; i < nbBytesRead; i++) { - str += (char) buffer[i]; - } - } - - } catch (IOException e) { - } - + try { + Exception exception2, exception1 = null; + } catch (IOException iOException) {} return str; } - + public static File readFileFromUrl(String urlToFetch) throws MalformedURLException { String[] url = urlToFetch.split("/"); if (url.length == 0) - throw new MalformedURLException(); - + throw new MalformedURLException(); return readFileFromUrl(urlToFetch, url[url.length - 1]); } - + public static File readFileFromUrl(String urlToFetch, String filename) throws MalformedURLException { return readFileFromUrl(urlToFetch, new File(filename)); } - + public static File readFileFromUrlToFolder(String urlToFetch, String folder) throws MalformedURLException { String name = getFileNameFromURL(urlToFetch); - if(name == null)throw new MalformedURLException(); - - return readFileFromUrlToFolder(urlToFetch, folder,name); + if (name == null) + throw new MalformedURLException(); + return readFileFromUrlToFolder(urlToFetch, folder, name); } - public static File readFileFromUrlToFolder(String urlToFetch, String folder,String name) throws MalformedURLException { + public static File readFileFromUrlToFolder(String urlToFetch, String folder, String name) throws MalformedURLException { try { - Files.createDirectories(Paths.get(folder)); + Files.createDirectories(Paths.get(folder, new String[0]), (FileAttribute[])new FileAttribute[0]); } catch (IOException e) { - Log.e("HTTPHelper","could not create folder"); + Log.e("HTTPHelper", "could not create folder"); return null; - } - + } if (!folder.endsWith("/")) - folder += "/"; - - return readFileFromUrl(urlToFetch, new File((folder + name.toLowerCase()).trim())); + folder = String.valueOf(folder) + "/"; + return readFileFromUrl(urlToFetch, new File((String.valueOf(folder) + name.toLowerCase()).trim())); } - + private static File readFileFromUrl(String urlToFetch, File destination) throws MalformedURLException { - URL url = new URL(urlToFetch); HttpURLConnection con; + FileOutputStream downloadingWriter; + URL url = new URL(urlToFetch); try { - con = (HttpURLConnection) url.openConnection(); + con = (HttpURLConnection)url.openConnection(); } catch (IOException e1) { e1.printStackTrace(); return null; - } - + } File downloadingFile = destination; System.out.println(downloadingFile.getAbsolutePath()); - - if (downloadingFile.exists()) { - return downloadingFile; - } else { - try { - System.out.println(downloadingFile); - downloadingFile.createNewFile(); - } catch (IOException e) { - Log.e("HTTPHelper","permission error could not write file"); - e.printStackTrace(); - System.exit(1); - } - } - FileOutputStream downloadingWriter; + if (downloadingFile.exists()) + return downloadingFile; + try { + System.out.println(downloadingFile); + downloadingFile.createNewFile(); + } catch (IOException e) { + Log.e("HTTPHelper", "permission error could not write file"); + e.printStackTrace(); + System.exit(1); + } try { downloadingWriter = new FileOutputStream(downloadingFile); } catch (FileNotFoundException e1) { e1.printStackTrace(); return null; - // imposible vu qu'on l'a crée precedament - } - - try (InputStream in = con.getInputStream()) { - //int totalRead = 0; - // on lit par tranche de 4mo - byte[] buffer = new byte[4096]; - - while (true) { - int bytesRead = in.read(buffer); - if (bytesRead < 0) - break; - //totalRead += bytesRead; - downloadingWriter.write(buffer, 0, bytesRead); - //TODO afficher cette valeur si on a un ui - //System.out.println("\r" + totalRead); - } - downloadingWriter.close(); - return downloadingFile; - } catch (IOException e) { - } - return null; - + } + try { + Exception exception1 = null, exception2 = null; + try { + + } finally { + exception2 = null; + if (exception1 == null) { + exception1 = exception2; + } else if (exception1 != exception2) { + exception1.addSuppressed(exception2); + } + } + } catch (IOException iOException) { + return null; + } } - public static String getFileNameFromURL(String url) - { + public static String getFileNameFromURL(String url) { String[] urlsplit = url.split("/"); if (urlsplit.length == 0) - return null; + return null; return urlsplit[urlsplit.length - 1]; } - - } diff --git a/downloader/IntegrityChecker.java b/downloader/IntegrityChecker.java index 77121d1..77bf45c 100644 --- a/downloader/IntegrityChecker.java +++ b/downloader/IntegrityChecker.java @@ -11,150 +11,127 @@ import java.util.TreeMap; import java.util.zip.ZipFile; public class IntegrityChecker { - public String[] fileList; - public SortedMap installedMods; - public File modsMap; + public String[] fileList = (new File("mods")).list(); - @SuppressWarnings("unchecked") - public IntegrityChecker() - { - fileList = new File("mods").list(); - modsMap = new File("mods/modsMap.sav"); - if(modsMap.exists()) - { + public SortedMap installedMods; + + public File modsMap = new File("mods/modsMap.sav"); + + public IntegrityChecker() { + if (this.modsMap.exists()) { try { - ObjectInputStream ois = new ObjectInputStream(new FileInputStream(modsMap)); - installedMods = (SortedMap) ois.readObject(); - if(installedMods == null)installedMods = new TreeMap<>(); + ObjectInputStream ois = new ObjectInputStream(new FileInputStream(this.modsMap)); + this.installedMods = (SortedMap)ois.readObject(); + if (this.installedMods == null) + this.installedMods = new TreeMap<>(); ois.close(); } catch (Exception e) { - installedMods = new TreeMap<>(); - modsMap.delete(); - } - }else { + this.installedMods = new TreeMap<>(); + this.modsMap.delete(); + } + } else { try { - modsMap.createNewFile(); + this.modsMap.createNewFile(); } catch (IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); - } - } + } + } try { - ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(modsMap)); - oos.writeObject(installedMods); + ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(this.modsMap)); + oos.writeObject(this.installedMods); oos.close(); } catch (IOException e) { Log.e("SAV", "erreur pas de sauvegarde"); System.exit(1); - } + } } public boolean checkAndDelete(File modToDownload, int modid) { - String alredyInstalledName = installedMods.get(modid).toLowerCase(); - File alredyInstalledMods= null; - - - //on cherche le fichier local affin de ne pas voir d'erreur avec la casse + String alredyInstalledName = ((String)this.installedMods.get(Integer.valueOf(modid))).toLowerCase(); + File alredyInstalledMods = null; File dir = new File("mods/"); - for(String fileName : dir.list()) - { - if(fileName.equalsIgnoreCase(alredyInstalledName)) - { - alredyInstalledMods = new File("mods/"+fileName); - } - } - if(alredyInstalledMods == null) { - Log.e("IntegrityChecker", "alredy installed mod not found ("+alredyInstalledName+")"); - installedMods.remove(modid); - + byte b; + int i; + String[] arrayOfString; + for (i = (arrayOfString = dir.list()).length, b = 0; b < i; ) { + String fileName = arrayOfString[b]; + if (fileName.equalsIgnoreCase(alredyInstalledName)) + alredyInstalledMods = new File("mods/" + fileName); + b++; + } + if (alredyInstalledMods == null) { + Log.e("IntegrityChecker", "alredy installed mod not found (" + alredyInstalledName + ")"); + this.installedMods.remove(Integer.valueOf(modid)); return false; - } - + } if (alredyInstalledMods.exists()) { try { - //si sa balance une exception sa veut dire que le jar n'est pas lisible - new ZipFile(alredyInstalledMods).close(); + (new ZipFile(alredyInstalledMods)).close(); } catch (IOException e) { - Log.i("integrityChecker","Corruption detected redownloading"); + Log.i("integrityChecker", "Corruption detected redownloading"); alredyInstalledMods.delete(); - installedMods.remove(modid); + this.installedMods.remove(Integer.valueOf(modid)); updateFile(); return false; - } - if(!modToDownload.getAbsolutePath().equalsIgnoreCase(alredyInstalledMods.getAbsolutePath())) - { + } + if (!modToDownload.getAbsolutePath().equalsIgnoreCase(alredyInstalledMods.getAbsolutePath())) { alredyInstalledMods.delete(); - Log.i("integrityChecker","Outdated mod detected redownloading ("+alredyInstalledName+" -> "+modToDownload.getName()+")"); - installedMods.remove(modid); + Log.i("integrityChecker", "Outdated mod detected redownloading (" + alredyInstalledName + " -> " + modToDownload.getName() + ")"); + this.installedMods.remove(Integer.valueOf(modid)); updateFile(); return false; - } + } return true; - }else { - if(modToDownload.exists()) - { - installedMods.put(modid, modToDownload.getName()); - updateFile(); - Log.i("interessting", modToDownload.getName()); - } - } + } + if (modToDownload.exists()) { + this.installedMods.put(Integer.valueOf(modid), modToDownload.getName()); + updateFile(); + Log.i("interessting", modToDownload.getName()); + } return false; } - - public boolean checkAndDelete(File modToDownload, String slug) { - if (modToDownload.exists()) { - try { - //si sa balance une exception sa veut dire que le jar n'est pas lisible - new ZipFile(modToDownload).close(); - } catch (IOException e) { - Log.i("integrityChecker","Corruption detected redownloading"); - modToDownload.delete(); - return false; - } - - for (String s : fileList) { - if (s.contains(slug)) { - if (!modToDownload.getName().contains(s)) { - new File(s).delete(); - Log.i("integrityChecker","Corruption detected redownloading"); - return false; - } - return true; - } - } + if (modToDownload.exists()) + try { + (new ZipFile(modToDownload)).close(); + return true; + } catch (IOException e) { + Log.i("integrityChecker", "Corruption detected redownloading"); + modToDownload.delete(); return false; - - } + } + byte b; + int i; + String[] arrayOfString; + for (i = (arrayOfString = this.fileList).length, b = 0; b < i; ) { + String s = arrayOfString[b]; + if (s.toLowerCase().contains(slug.trim())) { + if (modToDownload.getName().trim().equalsIgnoreCase(s.trim())) + return true; + (new File(s)).delete(); + break; + } + b++; + } return false; } - /** - * un chemin d'acces ne marche pas - * @param fileName - * @param modID - */ - public void addModsToTheList(String fileName,int modID) - { - installedMods.put(modID, fileName); - updateFile(); + public void addModsToTheList(String fileName, int modID) { + this.installedMods.put(Integer.valueOf(modID), fileName); + Main.changes.set(Main.changes.get() + 1); } - public boolean isModIdKnown(int modId) - { - return installedMods.get(modId) != null; + public boolean isModIdKnown(int modId) { + return (this.installedMods.get(Integer.valueOf(modId)) != null); } - private void updateFile() - { + public void updateFile() { try { - modsMap.delete(); - //modsMap.createNewFile(); - ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(modsMap)); - oos.writeObject(installedMods); + this.modsMap.delete(); + ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(this.modsMap)); + oos.writeObject(this.installedMods); oos.close(); - } catch (IOException e) {} + } catch (IOException iOException) {} } - } diff --git a/downloader/Log.java b/downloader/Log.java index e7f5100..95ca52c 100644 --- a/downloader/Log.java +++ b/downloader/Log.java @@ -1,12 +1,11 @@ package downloader; public class Log { - public static void e(String who,String msg) - { - System.err.println(who + " : "+msg); + public static void e(String who, String msg) { + System.err.println(String.valueOf(who) + " : " + msg); } - public static void i(String who,String msg) - { - System.out.println(who +" : "+msg); + + public static void i(String who, String msg) { + System.out.println(String.valueOf(who) + " : " + msg); } } diff --git a/downloader/Main.java b/downloader/Main.java index b9314c4..ae31211 100644 --- a/downloader/Main.java +++ b/downloader/Main.java @@ -8,71 +8,168 @@ import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; +import java.nio.file.attribute.FileAttribute; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; public class Main { - public static void main(String[] args) throws FileNotFoundException, IOException, URISyntaxException { + private static File f = null; + + private static boolean verbose = false; + + private static boolean checkingonly = false; + + public static final AtomicInteger changes = new AtomicInteger(0); + + private static Integer threadNb = null; + + public static void main(String[] args) throws FileNotFoundException, IOException, URISyntaxException { try { - Files.createDirectories(Paths.get("mods")); + Files.createDirectories(Paths.get("mods", new String[0]), (FileAttribute[])new FileAttribute[0]); } catch (IOException e) { - Log.e("HTTPHelper","could not create folder"); + Log.e("HTTPHelper", "could not create folder"); System.exit(0); - } - - + } + interpretArgs(args); + if (f == null) + f = new File("modpack.txt"); + if (!f.exists()) { + System.out.println("file not found"); + System.exit(1); + } IntegrityChecker updateManager = new IntegrityChecker(); Database db = new Database(); db.updateDatabase(); - - File f; - if(args.length == 0)f = new File("modpack.txt"); - else f = new File(args[0]); - BufferedReader in = new BufferedReader(new FileReader(f)); + if (threadNb == null) + threadNb = Integer.valueOf(4); + List threads = new ArrayList<>(threadNb.intValue()); while (in.ready()) { String line = in.readLine(); if (!isAComment(line)) { - if(line.startsWith("direct=")) - { - String url = line.replaceFirst("direct=.*@", ""); - String filename=extractNameFromLink(line); - - //le slug est une nom de mods qui se trouve dans le nom du fichier - String slug = extractSlugFromLink(line); - //on check si le mods est pas déja installé et si il est a jours - boolean upToDate = updateManager.checkAndDelete(new File("mods/"+filename), slug); - if(!upToDate) - { - Log.i("main","downloading "+ filename); - HttpHelper.readFileFromUrlToFolder(url,"mods",filename); - Log.i("main","done"); - } - }else { - if (line.split("/").length >= 5 && !db.fetchMod(line)) { - Log.e("main","error could not get " + line); - } - } - } - } + checkThreadState(threads); + Thread newLineTerpreter = new NewLineInterpreter(line, updateManager, db); + newLineTerpreter.start(); + threads.add(newLineTerpreter); + } + } + checkThreadState(threads); in.close(); + while (threads.size() != 0) { + try { + Thread.sleep(100L); + } catch (InterruptedException interruptedException) {} + checkThreadState(threads); + } + if (changes.get() != 0 && verbose) + Log.i("Main", "changed " + changes.get() + " mod(s)"); Log.i("Main", "finished"); } - private static String extractSlugFromLink(String line) { - char[] chars = new char[line.length()-line.indexOf(";")-"direct=".length()+1]; - line.getChars("direct=".length(), line.indexOf(";"), chars, 0); - return new String(chars); + private static void checkThreadState(List threads) { + do { + if (threads.size() >= threadNb.intValue()) + try { + Thread.sleep(100L); + } catch (InterruptedException interruptedException) {} + Iterator it = threads.iterator(); + while (it.hasNext()) { + Thread t = it.next(); + if (!t.isAlive()) + it.remove(); + } + } while (threads.size() >= threadNb.intValue()); } - private static String extractNameFromLink(String line) { - char[] chars = new char[line.indexOf("@")-line.indexOf(";")]; - line.getChars(line.indexOf(";")+1, line.indexOf("@"), chars, 0); - return new String(chars); + private static void interpretArgs(String[] args) { + Iterator it = Arrays.asList(args).iterator(); + while (it.hasNext()) { + String cmd = it.next(); + if (cmd.startsWith("-")) { + String nbt; + int cores; + String str1; + switch ((str1 = cmd).hashCode()) { + case -1629068440: + if (!str1.equals("--check")) + break; + checkingonly = true; + continue; + case 1511: + if (!str1.equals("-t")) + break; + if (threadNb != null) { + System.out.println("error conflicting arguments --thread and -t"); + System.exit(1); + } + cores = Runtime.getRuntime().availableProcessors(); + if (cores <= 0) { + System.out.println("java think you have no cpu core... sooo lets go for 4"); + threadNb = Integer.valueOf(4); + continue; + } + System.out.println("running on " + cores + " thread"); + threadNb = Integer.valueOf(cores); + continue; + case 1513: + if (!str1.equals("-v")) + break; + verbose = true; + continue; + case 48044553: + if (!str1.equals("--threads")) + break; + if (threadNb != null) { + System.out.println("error conflicting arguments --thread and -t"); + System.exit(1); + } + if (!it.hasNext()) { + System.err.println("arguments invalid please refer to --help"); + System.exit(1); + } + nbt = it.next(); + if (nbt.matches("[0-9]*")) { + threadNb = Integer.valueOf(Integer.parseInt(nbt)); + continue; + } + System.err.println("arguments invalid please refer to --help"); + System.exit(1); + continue; + case 1333013276: + if (!str1.equals("--file")) + break; + if (!it.hasNext()) { + System.err.println("arguments invalid please refer to --help"); + System.exit(1); + } + f = new File(it.next()); + continue; + case 1333069025: + if (!str1.equals("--help")) + break; + System.out.println("use --file to specify the modfile\nuse --check to check without updating\nuse --help to see this help\nuse -v to see verbose\nuse --threads to specify the number of threads\nuse -t to set the number of thread automaticaly"); + System.exit(0); + continue; + } + System.err.print("unknown args " + cmd + "\n" + + "see --help for help"); + System.exit(1); + } + } } - - - public static boolean isAComment(String line) - { + + public static boolean isAComment(String line) { return line.startsWith("//"); } - + + public static boolean isVersbose() { + return verbose; + } + + public static boolean isCheckingOnly() { + return checkingonly; + } } diff --git a/downloader/NewLineInterpreter.java b/downloader/NewLineInterpreter.java new file mode 100644 index 0000000..1439089 --- /dev/null +++ b/downloader/NewLineInterpreter.java @@ -0,0 +1,58 @@ +package downloader; + +import java.io.File; +import java.net.MalformedURLException; + +public class NewLineInterpreter extends Thread { + private String line; + + private IntegrityChecker updateManager; + + private Database db; + + public NewLineInterpreter(String line, IntegrityChecker updateManager, Database db) { + this.line = line; + this.updateManager = updateManager; + this.db = db; + } + + public void run() { + super.run(); + interpretLine(); + } + + private void interpretLine() { + if (this.line.startsWith("direct=")) { + String url = this.line.replaceFirst("direct=.*@", ""); + String filename = extractNameFromLink(this.line).toLowerCase(); + String slug = extractSlugFromLink(this.line).toLowerCase(); + boolean upToDate = this.updateManager.checkAndDelete(new File("mods/" + filename), slug); + if (!upToDate) { + if (Main.isVersbose()) + Log.i("main", "downloading " + filename); + if (!Main.isCheckingOnly()) + try { + HttpHelper.readFileFromUrlToFolder(url, "mods", filename); + } catch (MalformedURLException e) { + Log.e("main", "error bad mod url " + this.line); + } + } else if (Main.isVersbose()) { + Log.i("main", "alredy installed"); + } + } else if ((this.line.split("/")).length >= 5 && !this.db.fetchMod(this.line)) { + Log.e("main", "error could not get " + this.line); + } + } + + private String extractSlugFromLink(String line) { + char[] chars = new char[line.length() - line.indexOf(";") - "direct=".length() + 1]; + line.getChars("direct=".length(), line.indexOf(";"), chars, 0); + return new String(chars); + } + + private String extractNameFromLink(String line) { + char[] chars = new char[line.indexOf("@") - line.indexOf(";")]; + line.getChars(line.indexOf(";") + 1, line.indexOf("@"), chars, 0); + return new String(chars); + } +} diff --git a/downloader/ProjectInfo.java b/downloader/ProjectInfo.java index da8553f..3f2cd1f 100644 --- a/downloader/ProjectInfo.java +++ b/downloader/ProjectInfo.java @@ -1,24 +1,27 @@ package downloader; public class ProjectInfo { - private String slug, name, desc; - + private String slug; + + private String name; + + private String desc; + public ProjectInfo(String slug, String name, String desc) { - super(); this.slug = slug; this.name = name; this.desc = desc; } public String getDesc() { - return desc; + return this.desc; } + public String getName() { - return name; + return this.name; } + public String getSlug() { - return slug; + return this.slug; } - - } diff --git a/downloader/forgeSvc/ForgeSvcEntry.java b/downloader/forgeSvc/ForgeSvcEntry.java index 8a8d63b..c7d6a58 100644 --- a/downloader/forgeSvc/ForgeSvcEntry.java +++ b/downloader/forgeSvc/ForgeSvcEntry.java @@ -4,6 +4,6 @@ public class ForgeSvcEntry { private ForgeSvcFile[] gameVersionLatestFiles; public ForgeSvcFile[] getFiles() { - return gameVersionLatestFiles; + return this.gameVersionLatestFiles; } } diff --git a/downloader/forgeSvc/ForgeSvcFile.java b/downloader/forgeSvc/ForgeSvcFile.java index c5653dd..9d96cf4 100644 --- a/downloader/forgeSvc/ForgeSvcFile.java +++ b/downloader/forgeSvc/ForgeSvcFile.java @@ -1,8 +1,7 @@ package downloader.forgeSvc; -import java.net.MalformedURLException; - import downloader.HttpHelper; +import java.net.MalformedURLException; public class ForgeSvcFile { private String gameVersion; @@ -11,21 +10,22 @@ public class ForgeSvcFile { private String projectFileName; public String getGameVersion() { - return gameVersion; + return this.gameVersion; } public int getFileType() { - return fileType; + return this.fileType; } + public int getProjectFileId() { - return projectFileId; + return this.projectFileId; } public String getProjectFileName() { - return projectFileName; + return this.projectFileName; } - + public String getDownloadUrl(int modID) throws MalformedURLException { - return HttpHelper.readStringFromUrl("https://addons-ecs.forgesvc.net/api/v2/addon/"+modID+"/file/"+projectFileId+"/download-url"); + return HttpHelper.readStringFromUrl("https://addons-ecs.forgesvc.net/api/v2/addon/" + modID + "/file/" + this.projectFileId + "/download-url"); } } diff --git a/scripts/build.sh b/scripts/build.sh index 60fabf3..69ab4c1 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -1,5 +1,5 @@ #!/bin/sh javac \ -d objs\ - -cp libs/commons-compress-1.20.jar:libs/gson-2.8.7.jar\ + -cp libs/commons-compress-1.20.jar:libs/gson-2.8.7.jar:libs/gson-2.8.6.jar\ downloader/*.java downloader/forgeSvc/*.java