-Cleaning
This commit is contained in:
tonikelope 2016-10-26 16:38:56 +02:00
parent fc274e9a1f
commit 6b5ac57673
52 changed files with 5804 additions and 6236 deletions

View File

@ -71,24 +71,24 @@
-->
<target name="package-for-store" depends="jar">
<property name="store.jar.name" value="MegaBasterd"/>
<property name="store.dir" value="store"/>
<property name="store.jar" value="${store.dir}/${store.jar.name}.jar"/>
<echo message="Packaging ${application.title} into a single JAR at ${store.jar}"/>
<delete dir="${store.dir}"/>
<mkdir dir="${store.dir}"/>
<jar destfile="${store.dir}/temp_final.jar" filesetmanifest="skip">
<zipgroupfileset dir="dist" includes="*.jar"/>
<zipgroupfileset dir="dist/lib" includes="*.jar"/>
<manifest>
<attribute name="Main-Class" value="${main.class}"/>
<attribute name="SplashScreen-Image" value="megabasterd/dot_com.png"/>
</manifest>
</jar>
<zip destfile="${store.jar}">
<zipfileset src="${store.dir}/temp_final.jar"
excludes="META-INF/*.SF, META-INF/*.DSA, META-INF/*.RSA, megabasterd/screenshot*.png"/>
</zip>
<delete file="${store.dir}/temp_final.jar"/>
</target>
<property name="store.jar.name" value="MegaBasterd"/>
<property name="store.dir" value="store"/>
<property name="store.jar" value="${store.dir}/${store.jar.name}.jar"/>
<echo message="Packaging ${application.title} into a single JAR at ${store.jar}"/>
<delete dir="${store.dir}"/>
<mkdir dir="${store.dir}"/>
<jar destfile="${store.dir}/temp_final.jar" filesetmanifest="skip">
<zipgroupfileset dir="dist" includes="*.jar"/>
<zipgroupfileset dir="dist/lib" includes="*.jar"/>
<manifest>
<attribute name="Main-Class" value="${main.class}"/>
<attribute name="SplashScreen-Image" value="megabasterd/dot_com.png"/>
</manifest>
</jar>
<zip destfile="${store.jar}">
<zipfileset src="${store.dir}/temp_final.jar"
excludes="META-INF/*.SF, META-INF/*.DSA, META-INF/*.RSA, megabasterd/screenshot*.png"/>
</zip>
<delete file="${store.dir}/temp_final.jar"/>
</target>
</project>

View File

@ -18,7 +18,7 @@ is divided into following sections:
- applet
- cleanup
-->
-->
<project xmlns:j2seproject1="http://www.netbeans.org/ns/j2se-project/1" xmlns:j2seproject3="http://www.netbeans.org/ns/j2se-project/3" xmlns:jaxrpc="http://www.netbeans.org/ns/j2se-project/jax-rpc" basedir=".." default="default" name="MegaBasterd-impl">
<fail message="Please build using Ant 1.8.0 or higher.">
<condition>
@ -29,10 +29,10 @@ is divided into following sections:
</fail>
<target depends="test,jar,javadoc" description="Build and test whole project." name="default"/>
<!--
======================
INITIALIZATION SECTION
======================
-->
======================
INITIALIZATION SECTION
======================
-->
<target name="-pre-init">
<!-- Empty placeholder for easier customization. -->
<!-- You can override this target in the ../build.xml file. -->
@ -675,8 +675,8 @@ is divided into following sections:
</target>
<target depends="-init-macrodef-test-debug-junit,-init-macrodef-test-debug-testng" name="-init-macrodef-test-debug"/>
<!--
pre NB7.2 profiling section; consider it deprecated
-->
pre NB7.2 profiling section; consider it deprecated
-->
<target depends="-profile-pre-init, init, -profile-post-init, -profile-init-macrodef-profile, -profile-init-check" if="profiler.info.jvmargs.agent" name="profile-init"/>
<target if="profiler.info.jvmargs.agent" name="-profile-pre-init">
<!-- Empty placeholder for easier customization. -->
@ -723,8 +723,8 @@ is divided into following sections:
<fail unless="profiler.info.jvmargs.agent">Must set profiler agent JVM arguments in profiler.info.jvmargs.agent</fail>
</target>
<!--
end of pre NB7.2 profiling section
-->
end of pre NB7.2 profiling section
-->
<target depends="-init-debug-args" name="-init-macrodef-nbjpda">
<macrodef name="nbjpdastart" uri="http://www.netbeans.org/ns/j2se-project/1">
<attribute default="${main.class}" name="name"/>
@ -884,10 +884,10 @@ is divided into following sections:
</target>
<target depends="-pre-init,-init-private,-init-user,-init-project,-do-init,-post-init,-init-check,-init-macrodef-property,-init-macrodef-javac,-init-macrodef-test,-init-macrodef-test-debug,-init-macrodef-nbjpda,-init-macrodef-debug,-init-macrodef-java,-init-presetdef-jar,-init-ap-cmdline" name="init"/>
<!--
===================
COMPILATION SECTION
===================
-->
===================
COMPILATION SECTION
===================
-->
<target name="-deps-jar-init" unless="built-jar.properties">
<property location="${build.dir}/built-jar.properties" name="built-jar.properties"/>
<delete file="${built-jar.properties}" quiet="true"/>
@ -958,10 +958,10 @@ is divided into following sections:
</target>
<target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile-single,-do-compile-single,-post-compile-single" name="compile-single"/>
<!--
====================
JAR BUILDING SECTION
====================
-->
====================
JAR BUILDING SECTION
====================
-->
<target depends="init" name="-pre-pre-jar">
<dirname file="${dist.jar}" property="dist.jar.dir"/>
<mkdir dir="${dist.jar.dir}"/>
@ -1032,10 +1032,10 @@ is divided into following sections:
<target depends="init,compile,-pre-jar,-do-jar-without-libraries,-do-jar-with-libraries,-post-jar" name="-do-jar"/>
<target depends="init,compile,-pre-jar,-do-jar,-post-jar" description="Build JAR." name="jar"/>
<!--
=================
EXECUTION SECTION
=================
-->
=================
EXECUTION SECTION
=================
-->
<target depends="init,compile" description="Run a main class." name="run">
<j2seproject1:java>
<customize>
@ -1055,10 +1055,10 @@ is divided into following sections:
<j2seproject1:java classname="${run.class}" classpath="${run.test.classpath}"/>
</target>
<!--
=================
DEBUGGING SECTION
=================
-->
=================
DEBUGGING SECTION
=================
-->
<target depends="init" if="netbeans.home" name="-debug-start-debugger">
<j2seproject1:nbjpdastart name="${debug.class}"/>
</target>
@ -1096,13 +1096,13 @@ is divided into following sections:
</target>
<target depends="init,-pre-debug-fix,-do-debug-fix" if="netbeans.home" name="debug-fix"/>
<!--
=================
PROFILING SECTION
=================
-->
=================
PROFILING SECTION
=================
-->
<!--
pre NB7.2 profiler integration
-->
pre NB7.2 profiler integration
-->
<target depends="profile-init,compile" description="Profile a project in the IDE." if="profiler.info.jvmargs.agent" name="-profile-pre72">
<fail unless="netbeans.home">This target only works when run from inside the NetBeans IDE.</fail>
<nbprofiledirect>
@ -1159,8 +1159,8 @@ is divided into following sections:
</junit>
</target>
<!--
end of pre NB72 profiling section
-->
end of pre NB72 profiling section
-->
<target if="netbeans.home" name="-profile-check">
<condition property="profiler.configured">
<or>
@ -1195,10 +1195,10 @@ is divided into following sections:
<antcall target="run-applet"/>
</target>
<!--
===============
JAVADOC SECTION
===============
-->
===============
JAVADOC SECTION
===============
-->
<target depends="init" if="have.sources" name="-javadoc-build">
<mkdir dir="${dist.javadoc.dir}"/>
<condition else="" property="javadoc.endorsed.classpath.cmd.line.arg" value="-J${endorsed.classpath.cmd.line.arg}">
@ -1239,10 +1239,10 @@ is divided into following sections:
</target>
<target depends="init,-javadoc-build,-javadoc-browse" description="Build Javadoc." name="javadoc"/>
<!--
=========================
TEST COMPILATION SECTION
=========================
-->
=========================
TEST COMPILATION SECTION
=========================
-->
<target depends="init,compile" if="have.tests" name="-pre-pre-compile-test">
<mkdir dir="${build.test.classes.dir}"/>
</target>
@ -1282,10 +1282,10 @@ is divided into following sections:
</target>
<target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single,-do-compile-test-single,-post-compile-test-single" name="compile-test-single"/>
<!--
=======================
TEST EXECUTION SECTION
=======================
-->
=======================
TEST EXECUTION SECTION
=======================
-->
<target depends="init" if="have.tests" name="-pre-test-run">
<mkdir dir="${build.test.results.dir}"/>
</target>
@ -1319,10 +1319,10 @@ is divided into following sections:
</target>
<target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single-method,-post-test-run-single-method" description="Run single unit test." name="test-single-method"/>
<!--
=======================
TEST DEBUGGING SECTION
=======================
-->
=======================
TEST DEBUGGING SECTION
=======================
-->
<target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-debug-start-debuggee-test">
<fail unless="test.class">Must select one file in the IDE or set test.class</fail>
<j2seproject3:test-debug excludes="" includes="${javac.includes}" testClass="${test.class}" testincludes="${javac.includes}"/>
@ -1342,10 +1342,10 @@ is divided into following sections:
</target>
<target depends="init,-pre-debug-fix,-do-debug-fix-test" if="netbeans.home" name="debug-fix-test"/>
<!--
=========================
APPLET EXECUTION SECTION
=========================
-->
=========================
APPLET EXECUTION SECTION
=========================
-->
<target depends="init,compile-single" name="run-applet">
<fail unless="applet.url">Must select one file in the IDE or set applet.url</fail>
<j2seproject1:java classname="sun.applet.AppletViewer">
@ -1355,10 +1355,10 @@ is divided into following sections:
</j2seproject1:java>
</target>
<!--
=========================
APPLET DEBUGGING SECTION
=========================
-->
=========================
APPLET DEBUGGING SECTION
=========================
-->
<target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-applet">
<fail unless="applet.url">Must select one file in the IDE or set applet.url</fail>
<j2seproject3:debug classname="sun.applet.AppletViewer">
@ -1369,10 +1369,10 @@ is divided into following sections:
</target>
<target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-applet" if="netbeans.home" name="debug-applet"/>
<!--
===============
CLEANUP SECTION
===============
-->
===============
CLEANUP SECTION
===============
-->
<target name="-deps-clean-init" unless="built-clean.properties">
<property location="${build.dir}/built-clean.properties" name="built-clean.properties"/>
<delete file="${built-clean.properties}" quiet="true"/>

View File

@ -6,7 +6,6 @@ import javax.swing.JOptionPane;
import static megabasterd.MainPanel.FONT_DEFAULT;
import static megabasterd.MainPanel.THREAD_POOL;
import static megabasterd.MainPanel.VERSION;
import static megabasterd.MiscTools.copyTextToClipboard;
import static megabasterd.MiscTools.swingReflectionInvoke;
import static megabasterd.MiscTools.updateFont;
@ -15,31 +14,32 @@ import static megabasterd.MiscTools.updateFont;
* @author tonikelope
*/
public final class AboutDialog extends javax.swing.JDialog {
private static final String MEGA_URL = "https://mega.nz/#F!lYsRWaQB!uVhntmyKcVECRaOxAbcL4A";
private static final String TONIKELOPE_URL = "http://t0ni.xyz";
private static final String MEGACRYPTER_URL = "https://megacrypter.com";
private static final String SPAIN_URL = "https://en.wikipedia.org/wiki/Spain";
private static final String MEGABASTERD_GITHUB_URL = "https://github.com/tonikelope/megabasterd";
public AboutDialog(MainPanelView parent, boolean modal) {
super(parent, modal);
initComponents();
swingReflectionInvoke("setText", title_label , "MegaBasterd "+ VERSION);
MiscTools.swingInvokeIt(new Runnable(){
swingReflectionInvoke("setText", title_label, "MegaBasterd " + VERSION);
MiscTools.swingInvokeIt(new Runnable() {
@Override
public void run() { updateFont(title_label, FONT_DEFAULT, Font.BOLD);
updateFont(subtitle_label, FONT_DEFAULT, Font.BOLD);
updateFont(mcdown_url_button, FONT_DEFAULT, Font.PLAIN);
updateFont(check_version_button, FONT_DEFAULT, Font.PLAIN);}}, true);
public void run() {
updateFont(title_label, FONT_DEFAULT, Font.BOLD);
updateFont(subtitle_label, FONT_DEFAULT, Font.BOLD);
updateFont(mcdown_url_button, FONT_DEFAULT, Font.PLAIN);
updateFont(check_version_button, FONT_DEFAULT, Font.PLAIN);
}
}, true);
}
/**
@ -190,49 +190,50 @@ public final class AboutDialog extends javax.swing.JDialog {
private void mcdown_url_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mcdown_url_buttonActionPerformed
copyTextToClipboard(MEGA_URL);
MiscTools.copyTextToClipboard(MEGA_URL);
JOptionPane.showMessageDialog(this, "MEGA URL was copied to clipboard!");
}//GEN-LAST:event_mcdown_url_buttonActionPerformed
private void check_version_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_check_version_buttonActionPerformed
check_version_button.setEnabled(false);
check_version_button.setText("Checking, please wait...");
final Dialog tthis = this;
THREAD_POOL.execute(new Runnable(){
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
String new_version = MiscTools.checkNewVersion("lYsRWaQB", "uVhntmyKcVECRaOxAbcL4A");
if(new_version != null) {
JOptionPane.showMessageDialog(tthis, "MegaBasterd NEW VERSION ("+new_version+") is available!\n\n(HELP > ABOUT for more info)");
if (new_version != null) {
JOptionPane.showMessageDialog(tthis, "MegaBasterd NEW VERSION (" + new_version + ") is available!\n\n(HELP > ABOUT for more info)");
} else {
JOptionPane.showMessageDialog(tthis, "You have the latest version ;)");
}
swingReflectionInvoke("setText", check_version_button, "Check version");
swingReflectionInvoke("setEnabled", check_version_button, true);
}});
}
});
}//GEN-LAST:event_check_version_buttonActionPerformed
private void pica_roja_labelMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pica_roja_labelMouseReleased
MiscTools.openBrowserURL(TONIKELOPE_URL);
}//GEN-LAST:event_pica_roja_labelMouseReleased
private void author_webpage_labelMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_author_webpage_labelMouseReleased
MiscTools.openBrowserURL(TONIKELOPE_URL);
}//GEN-LAST:event_author_webpage_labelMouseReleased
@ -242,7 +243,7 @@ public final class AboutDialog extends javax.swing.JDialog {
}//GEN-LAST:event_mc_logo_labelMouseReleased
private void made_in_spain_labelMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_made_in_spain_labelMouseReleased
MiscTools.openBrowserURL(SPAIN_URL);
}//GEN-LAST:event_made_in_spain_labelMouseReleased
@ -250,7 +251,6 @@ public final class AboutDialog extends javax.swing.JDialog {
MiscTools.openBrowserURL(MEGABASTERD_GITHUB_URL);
}//GEN-LAST:event_title_labelMouseReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel author_webpage_label;
private javax.swing.JButton check_version_button;

View File

@ -9,49 +9,46 @@ import static java.lang.String.valueOf;
* @author tonikelope
*/
public final class Chunk {
private final long _id;
private final long _offset;
private final long _size;
private final ByteArrayOutputStream _data_os;
private final String _url;
public Chunk(long id, long file_size, String file_url) throws ChunkInvalidIdException
{
public Chunk(long id, long file_size, String file_url) throws ChunkInvalidIdException {
_id = id;
_offset = calculateOffset();
if(file_size > 0)
{
if(_offset>=file_size) {
if (file_size > 0) {
if (_offset >= file_size) {
throw new ChunkInvalidIdException(valueOf(id));
}
} else {
if(id>1) {
if (id > 1) {
throw new ChunkInvalidIdException(valueOf(id));
}
}
_size = calculateSize(file_size);
_url = file_url!=null?file_url+"/"+_offset+"-"+(_offset+_size-1):null;
_data_os = new ByteArrayOutputStream((int)_size);
_url = file_url != null ? file_url + "/" + _offset + "-" + (_offset + _size - 1) : null;
_data_os = new ByteArrayOutputStream((int) _size);
}
public long getOffset() {
return _offset;
}
public ByteArrayOutputStream getOutputStream() {
return _data_os;
}
public long getId() {
return _id;
}
@ -63,27 +60,25 @@ public final class Chunk {
public String getUrl() {
return _url;
}
public ByteArrayInputStream getInputStream() {
return new ByteArrayInputStream(_data_os.toByteArray());
}
private long calculateSize(long file_size)
{
long chunk_size = (_id>=1 && _id<=7)?_id*128*1024:1024*1024;
if(_offset + chunk_size > file_size) {
private long calculateSize(long file_size) {
long chunk_size = (_id >= 1 && _id <= 7) ? _id * 128 * 1024 : 1024 * 1024;
if (_offset + chunk_size > file_size) {
chunk_size = file_size - _offset;
}
return chunk_size;
}
private long calculateOffset()
{
private long calculateOffset() {
long[] offs = {0, 128, 384, 768, 1280, 1920, 2688};
return (_id<=7?offs[(int)_id-1]:(3584 + (_id-8)*1024))*1024;
return (_id <= 7 ? offs[(int) _id - 1] : (3584 + (_id - 8) * 1024)) * 1024;
}
}

View File

@ -14,13 +14,12 @@ import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
/**
*
* @author tonikelope
*/
public class ChunkDownloader implements Runnable, SecureNotifiable {
private final int _id;
private final Download _download;
private volatile boolean _exit;
@ -28,9 +27,7 @@ public class ChunkDownloader implements Runnable, SecureNotifiable {
private volatile boolean _error_wait;
private boolean _notified;
public ChunkDownloader(int id, Download download)
{
public ChunkDownloader(int id, Download download) {
_notified = false;
_exit = false;
_secure_notify_lock = new Object();
@ -38,7 +35,7 @@ public class ChunkDownloader implements Runnable, SecureNotifiable {
_download = download;
_error_wait = false;
}
public void setExit(boolean exit) {
_exit = exit;
}
@ -62,25 +59,22 @@ public class ChunkDownloader implements Runnable, SecureNotifiable {
public void setError_wait(boolean error_wait) {
_error_wait = error_wait;
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -88,80 +82,75 @@ public class ChunkDownloader implements Runnable, SecureNotifiable {
getLogger(ChunkDownloader.class.getName()).log(Level.SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
@Override
public void run()
{
String worker_url=null;
public void run() {
String worker_url = null;
Chunk chunk;
int reads, conta_error, http_status;
byte[] buffer = new byte[THROTTLE_SLICE_SIZE];
InputStream is;
boolean error;
System.out.println("Worker ["+_id+"]: let's do some work!");
try(CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient())
{
System.out.println("Worker [" + _id + "]: let's do some work!");
try (CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient()) {
conta_error = 0;
error = false;
while(!_exit && !_download.isStopped())
{
if(worker_url == null || error) {
worker_url=_download.getDownloadUrlForWorker();
while (!_exit && !_download.isStopped()) {
if (worker_url == null || error) {
worker_url = _download.getDownloadUrlForWorker();
}
chunk = new Chunk(_download.nextChunkId(), _download.getFile_size(), worker_url);
HttpGet httpget = new HttpGet(new URI(chunk.getUrl()));
httpget.addHeader("Connection", "close");
error = false;
try(CloseableHttpResponse httpresponse = httpclient.execute(httpget)){
try (CloseableHttpResponse httpresponse = httpclient.execute(httpget)) {
if (!_exit && !_download.isStopped()) {
if(!_exit && !_download.isStopped()) {
is = new ThrottledInputStream(httpresponse.getEntity().getContent(), _download.getMain_panel().getStream_supervisor());
http_status = httpresponse.getStatusLine().getStatusCode();
if ( http_status != HttpStatus.SC_OK )
{
if (http_status != HttpStatus.SC_OK) {
System.out.println("Failed : HTTP error code : " + http_status);
error = true;
} else {
while(!_exit && !_download.isStopped() && !_download.getChunkwriter().isExit() && chunk.getOutputStream().size() < chunk.getSize() && (reads=is.read(buffer))!=-1 )
{
while (!_exit && !_download.isStopped() && !_download.getChunkwriter().isExit() && chunk.getOutputStream().size() < chunk.getSize() && (reads = is.read(buffer)) != -1) {
chunk.getOutputStream().write(buffer, 0, reads);
_download.getPartialProgressQueue().add(reads);
_download.getProgress_meter().secureNotify();
if(_download.isPaused() && !_download.isStopped()) {
if (_download.isPaused() && !_download.isStopped()) {
_download.pause_worker();
@ -170,13 +159,12 @@ public class ChunkDownloader implements Runnable, SecureNotifiable {
}
is.close();
if(chunk.getOutputStream().size() < chunk.getSize()) {
if(chunk.getOutputStream().size() > 0)
{
_download.getPartialProgressQueue().add(-1*chunk.getOutputStream().size());
if (chunk.getOutputStream().size() < chunk.getSize()) {
if (chunk.getOutputStream().size() > 0) {
_download.getPartialProgressQueue().add(-1 * chunk.getOutputStream().size());
_download.getProgress_meter().secureNotify();
}
@ -185,78 +173,73 @@ public class ChunkDownloader implements Runnable, SecureNotifiable {
}
}
if(error && !_download.isStopped()) {
if (error && !_download.isStopped()) {
_download.rejectChunkId(chunk.getId());
conta_error++;
if(!_exit) {
if (!_exit) {
_error_wait = true;
_download.getView().updateSlotsStatus();
Thread.sleep(getWaitTimeExpBackOff(conta_error)*1000);
Thread.sleep(getWaitTimeExpBackOff(conta_error) * 1000);
_error_wait = false;
_download.getView().updateSlotsStatus();
}
} else if(!error) {
System.out.println("Worker ["+_id+"] has downloaded chunk ["+chunk.getId()+"]!");
} else if (!error) {
System.out.println("Worker [" + _id + "] has downloaded chunk [" + chunk.getId() + "]!");
_download.getChunkwriter().getChunk_queue().put(chunk.getId(), chunk);
_download.getChunkwriter().secureNotify();
conta_error = 0;
}
} else if(_exit) {
_download.rejectChunkId(chunk.getId());
} else if (_exit) {
_download.rejectChunkId(chunk.getId());
}
}
catch (IOException ex)
{
} catch (IOException ex) {
error = true;
_download.rejectChunkId(chunk.getId());
if(chunk.getOutputStream().size() > 0)
{
_download.getPartialProgressQueue().add(-1*chunk.getOutputStream().size());
if (chunk.getOutputStream().size() > 0) {
_download.getPartialProgressQueue().add(-1 * chunk.getOutputStream().size());
_download.getProgress_meter().secureNotify();
}
getLogger(ChunkDownloader.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
} catch (InterruptedException ex) {
getLogger(ChunkDownloader.class.getName()).log(Level.SEVERE, null, ex);
}
}
}catch(ChunkInvalidIdException e) {
}catch (IOException ex) {
} catch (ChunkInvalidIdException e) {
} catch (IOException ex) {
_download.emergencyStopDownloader(ex.getMessage());
getLogger(ChunkDownloader.class.getName()).log(Level.SEVERE, null, ex);
} catch (URISyntaxException ex) {
Logger.getLogger(ChunkDownloader.class.getName()).log(Level.SEVERE, null, ex);
}
_download.stopThisSlot(this);
_download.getChunkwriter().secureNotify();
System.out.println("Worker ["+_id+"]: bye bye");
System.out.println("Worker [" + _id + "]: bye bye");
}
}

View File

@ -14,7 +14,6 @@ import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
/**
*
* @author tonikelope
@ -24,138 +23,130 @@ public class ChunkDownloaderMono extends ChunkDownloader {
public ChunkDownloaderMono(Download download) {
super(1, download);
}
@Override
public void run()
{
String worker_url=null;
public void run() {
String worker_url = null;
Chunk chunk;
int reads, max_reads, conta_error, http_status=200;
int reads, max_reads, conta_error, http_status = 200;
byte[] buffer = new byte[THROTTLE_SLICE_SIZE];
boolean error;
HttpGet httpget = null;
CloseableHttpResponse httpresponse=null;
CloseableHttpResponse httpresponse = null;
System.out.println("Worker ["+getId()+"]: let's do some work!");
System.out.println("Worker [" + getId() + "]: let's do some work!");
try(CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient())
{
try (CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient()) {
conta_error = 0;
error = false;
InputStream is=null;
InputStream is = null;
while(!isExit() && !getDownload().isStopped())
{
if(worker_url == null || error) {
worker_url=getDownload().getDownloadUrlForWorker();
if(httpresponse != null) {
while (!isExit() && !getDownload().isStopped()) {
if (worker_url == null || error) {
worker_url = getDownload().getDownloadUrlForWorker();
if (httpresponse != null) {
httpresponse.close();
}
}
chunk = new Chunk(getDownload().nextChunkId(), getDownload().getFile_size(), null);
if(httpget == null || error) {
httpget = new HttpGet(new URI(worker_url+"/"+chunk.getOffset()));
if (httpget == null || error) {
httpget = new HttpGet(new URI(worker_url + "/" + chunk.getOffset()));
httpget.addHeader("Connection", "close");
httpresponse = httpclient.execute(httpget);
is = new ThrottledInputStream(httpresponse.getEntity().getContent(), getDownload().getMain_panel().getStream_supervisor());
http_status = httpresponse.getStatusLine().getStatusCode();
}
error = false;
if(http_status != HttpStatus.SC_OK){
if (http_status != HttpStatus.SC_OK) {
System.out.println("Failed : HTTP error code : " + http_status);
error = true;
error = true;
} else {
try{
try {
if(!isExit() && !getDownload().isStopped()) {
if (!isExit() && !getDownload().isStopped() && is != null) {
while(!getDownload().isStopped() && !getDownload().getChunkwriter().isExit() && chunk.getOutputStream().size() < chunk.getSize() && (reads=is.read(buffer, 0, (max_reads=(int)(chunk.getSize() - chunk.getOutputStream().size())) <= buffer.length?max_reads:buffer.length))!=-1 )
{
while (!getDownload().isStopped() && !getDownload().getChunkwriter().isExit() && chunk.getOutputStream().size() < chunk.getSize() && (reads = is.read(buffer, 0, (max_reads = (int) (chunk.getSize() - chunk.getOutputStream().size())) <= buffer.length ? max_reads : buffer.length)) != -1) {
chunk.getOutputStream().write(buffer, 0, reads);
getDownload().getPartialProgressQueue().add(reads);
getDownload().getProgress_meter().secureNotify();
if(getDownload().isPaused() && !getDownload().isStopped()) {
if (getDownload().isPaused() && !getDownload().isStopped()) {
getDownload().pause_worker_mono();
secureWait();
}
}
if(chunk.getOutputStream().size() < chunk.getSize()) {
if(chunk.getOutputStream().size() > 0)
{
getDownload().getPartialProgressQueue().add(-1*chunk.getOutputStream().size());
if (chunk.getOutputStream().size() < chunk.getSize()) {
if (chunk.getOutputStream().size() > 0) {
getDownload().getPartialProgressQueue().add(-1 * chunk.getOutputStream().size());
getDownload().getProgress_meter().secureNotify();
}
error = true;
}
if(error && !getDownload().isStopped()) {
if (error && !getDownload().isStopped()) {
getDownload().rejectChunkId(chunk.getId());
conta_error++;
if(!isExit()) {
if (!isExit()) {
setError_wait(true);
Thread.sleep(getWaitTimeExpBackOff(conta_error)*1000);
Thread.sleep(getWaitTimeExpBackOff(conta_error) * 1000);
setError_wait(false);
}
} else if(!error) {
} else if (!error) {
getDownload().getChunkwriter().getChunk_queue().put(chunk.getId(), chunk);
getDownload().getChunkwriter().secureNotify();
conta_error = 0;
}
} else if(isExit()) {
} else if (isExit()) {
getDownload().rejectChunkId(chunk.getId());
}
}
catch (IOException ex)
{
} catch (IOException ex) {
error = true;
getDownload().rejectChunkId(chunk.getId());
if(chunk.getOutputStream().size() > 0)
{
getDownload().getPartialProgressQueue().add(-1*chunk.getOutputStream().size());
if (chunk.getOutputStream().size() > 0) {
getDownload().getPartialProgressQueue().add(-1 * chunk.getOutputStream().size());
getDownload().getProgress_meter().secureNotify();
}
getLogger(ChunkDownloaderMono.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
@ -163,24 +154,24 @@ public class ChunkDownloaderMono extends ChunkDownloader {
}
}
}
}catch(ChunkInvalidIdException e) {
} catch (ChunkInvalidIdException e) {
} catch (IOException ex) {
getLogger(ChunkDownloaderMono.class.getName()).log(Level.SEVERE, null, ex);
getDownload().emergencyStopDownloader(ex.getMessage());
} catch (URISyntaxException ex) {
Logger.getLogger(ChunkDownloaderMono.class.getName()).log(Level.SEVERE, null, ex);
}
getDownload().stopThisSlot(this);
getDownload().getChunkwriter().secureNotify();
System.out.println("Worker ["+getId()+"]: bye bye");
System.out.println("Worker [" + getId() + "]: bye bye");
}
}

View File

@ -1,15 +1,13 @@
package megabasterd;
/**
*
* @author tonikelope
*/
public final class ChunkInvalidIdException extends Exception {
public ChunkInvalidIdException(String message)
{
public ChunkInvalidIdException(String message) {
super(message);
}
}

View File

@ -28,14 +28,12 @@ import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
/**
*
* @author tonikelope
*/
public class ChunkUploader implements Runnable, SecureNotifiable {
private final int _id;
private final Upload _upload;
private volatile boolean _exit;
@ -43,8 +41,7 @@ public class ChunkUploader implements Runnable, SecureNotifiable {
private volatile boolean _error_wait;
private boolean _notified;
public ChunkUploader(int id, Upload upload)
{
public ChunkUploader(int id, Upload upload) {
_notified = false;
_secure_notify_lock = new Object();
_id = id;
@ -52,7 +49,7 @@ public class ChunkUploader implements Runnable, SecureNotifiable {
_exit = false;
_error_wait = false;
}
public void setExit(boolean exit) {
_exit = exit;
}
@ -62,22 +59,20 @@ public class ChunkUploader implements Runnable, SecureNotifiable {
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -85,22 +80,22 @@ public class ChunkUploader implements Runnable, SecureNotifiable {
getLogger(ChunkUploader.class.getName()).log(Level.SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
public int getId() {
return _id;
}
@ -116,201 +111,191 @@ public class ChunkUploader implements Runnable, SecureNotifiable {
public void setError_wait(boolean _error_wait) {
this._error_wait = _error_wait;
}
@Override
public void run()
{
System.out.println("ChunkUploader "+_id+" hello!");
String worker_url=_upload.getUl_url();
public void run() {
System.out.println("ChunkUploader " + _id + " hello!");
String worker_url = _upload.getUl_url();
Chunk chunk;
int reads, to_read, conta_error, re, http_status, tot_bytes_up;
byte[] buffer = new byte[MainPanel.THROTTLE_SLICE_SIZE];
boolean error;
OutputStream out;
try(final CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient())
{
try (final CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient()) {
RandomAccessFile f = new RandomAccessFile(_upload.getFile_name(), "r");
conta_error = 0;
while(!_exit && !_upload.isStopped())
{
while (!_exit && !_upload.isStopped()) {
chunk = new Chunk(_upload.nextChunkId(), _upload.getFile_size(), worker_url);
f.seek(chunk.getOffset());
do
{
to_read = chunk.getSize() - chunk.getOutputStream().size() >= buffer.length?buffer.length:(int)(chunk.getSize() - chunk.getOutputStream().size());
re=f.read(buffer, 0, to_read);
do {
to_read = chunk.getSize() - chunk.getOutputStream().size() >= buffer.length ? buffer.length : (int) (chunk.getSize() - chunk.getOutputStream().size());
re = f.read(buffer, 0, to_read);
chunk.getOutputStream().write(buffer, 0, re);
}while(!_exit && !_upload.isStopped() && chunk.getOutputStream().size()<chunk.getSize());
final HttpPost httppost = new HttpPost(new URI(chunk.getUrl()));
final long postdata_length = chunk.getSize();
httppost.addHeader("Connection", "close");
tot_bytes_up=0;
error = false;
CloseableHttpResponse httpresponse = null;
try{
} while (!_exit && !_upload.isStopped() && chunk.getOutputStream().size() < chunk.getSize());
final HttpPost httppost = new HttpPost(new URI(chunk.getUrl()));
final long postdata_length = chunk.getSize();
httppost.addHeader("Connection", "close");
tot_bytes_up = 0;
error = false;
CloseableHttpResponse httpresponse = null;
try {
if (!_exit && !_upload.isStopped()) {
if(!_exit && !_upload.isStopped()) {
CipherInputStream cis = new CipherInputStream(chunk.getInputStream(), CryptTools.genCrypter("AES", "AES/CTR/NoPadding", _upload.getByte_file_key(), CryptTools.forwardMEGALinkKeyIV(_upload.getByte_file_iv(), chunk.getOffset())));
final PipedInputStream pipein = new PipedInputStream();
PipedOutputStream pipeout = new PipedOutputStream(pipein);
FutureTask<CloseableHttpResponse> futureTask = new FutureTask<>(new Callable() {
@Override
public CloseableHttpResponse call() throws IOException {
httppost.setEntity(new InputStreamEntity(pipein, postdata_length));
return httpclient.execute(httppost);
}
});
THREAD_POOL.execute(futureTask);
out = new ThrottledOutputStream(pipeout, _upload.getMain_panel().getStream_supervisor());
System.out.println(" Subiendo chunk "+chunk.getId()+" desde worker "+ _id +"...");
while( !_exit && !_upload.isStopped() && (reads=cis.read(buffer))!=-1 )
{
THREAD_POOL.execute(futureTask);
out = new ThrottledOutputStream(pipeout, _upload.getMain_panel().getStream_supervisor());
System.out.println(" Subiendo chunk " + chunk.getId() + " desde worker " + _id + "...");
while (!_exit && !_upload.isStopped() && (reads = cis.read(buffer)) != -1) {
out.write(buffer, 0, reads);
_upload.getPartialProgress().add(reads);
_upload.getProgress_meter().secureNotify();
tot_bytes_up+=reads;
if(_upload.isPaused() && !_upload.isStopped()) {
tot_bytes_up += reads;
if (_upload.isPaused() && !_upload.isStopped()) {
_upload.pause_worker();
secureWait();
}
}
out.close();
if(!_upload.isStopped()) {
try{
if(!_exit) {
if (!_upload.isStopped()) {
try {
if (!_exit) {
httpresponse = futureTask.get();
} else {
futureTask.cancel(true);
httpresponse = null;
}
if (httpresponse != null && (http_status = httpresponse.getStatusLine().getStatusCode()) != HttpStatus.SC_OK )
{
System.out.println("Failed : HTTP error code : " + http_status);
error = true;
} else {
if(tot_bytes_up < chunk.getSize())
{
if(tot_bytes_up > 0) {
_upload.getPartialProgress().add(-1*tot_bytes_up);
_upload.getProgress_meter().secureNotify();
}
if (httpresponse != null && (http_status = httpresponse.getStatusLine().getStatusCode()) != HttpStatus.SC_OK) {
System.out.println("Failed : HTTP error code : " + http_status);
error = true;
} else {
if(httpresponse != null && _upload.getCompletion_handle() == null) {
InputStream is=httpresponse.getEntity().getContent();
ByteArrayOutputStream byte_res = new ByteArrayOutputStream();
while( (reads=is.read(buffer)) != -1 ) {
if (tot_bytes_up < chunk.getSize()) {
if (tot_bytes_up > 0) {
byte_res.write(buffer, 0, reads);
_upload.getPartialProgress().add(-1 * tot_bytes_up);
_upload.getProgress_meter().secureNotify();
}
String response = new String(byte_res.toByteArray());
error = true;
if(response.length() > 0) {
} else {
if( MegaAPI.checkMEGAError(response) != 0 )
{
error = true;
if (httpresponse != null && _upload.getCompletion_handle() == null) {
} else {
InputStream is = httpresponse.getEntity().getContent();
System.out.println("Completion handle -> "+response);
ByteArrayOutputStream byte_res = new ByteArrayOutputStream();
_upload.setCompletion_handle(response);
while ((reads = is.read(buffer)) != -1) {
byte_res.write(buffer, 0, reads);
}
}
String response = new String(byte_res.toByteArray());
if (response.length() > 0) {
if (MegaAPI.checkMEGAError(response) != 0) {
error = true;
} else {
System.out.println("Completion handle -> " + response);
_upload.setCompletion_handle(response);
}
}
}
}
}
}
if(error && !_upload.isStopped()) {
_upload.rejectChunkId(chunk.getId());
conta_error++;
if (error && !_upload.isStopped()) {
if(!_exit) {
_error_wait = true;
_upload.getView().updateSlotsStatus();
_upload.rejectChunkId(chunk.getId());
Thread.sleep(getWaitTimeExpBackOff(conta_error)*1000);
_error_wait = false;
_upload.getView().updateSlotsStatus();
conta_error++;
if (!_exit) {
_error_wait = true;
_upload.getView().updateSlotsStatus();
Thread.sleep(getWaitTimeExpBackOff(conta_error) * 1000);
_error_wait = false;
_upload.getView().updateSlotsStatus();
}
} else if (!error) {
System.out.println(" Worker " + _id + " ha subido chunk " + chunk.getId());
_upload.getMac_generator().getChunk_queue().put(chunk.getId(), chunk);
_upload.getMac_generator().secureNotify();
conta_error = 0;
}
} else if(!error) {
System.out.println(" Worker "+_id+" ha subido chunk "+chunk.getId());
} catch (ExecutionException exception) {
} finally {
_upload.getMac_generator().getChunk_queue().put(chunk.getId(), chunk);
_upload.getMac_generator().secureNotify();
conta_error = 0;
}
}catch(ExecutionException exception){}
finally{
if(httpresponse != null) {
if (httpresponse != null) {
httpresponse.close();
}
@ -318,54 +303,51 @@ public class ChunkUploader implements Runnable, SecureNotifiable {
}
}
} else if(_exit) {
} else if (_exit) {
_upload.rejectChunkId(chunk.getId());
}
}
catch (IOException ex)
{
_upload.rejectChunkId(chunk.getId());
if(tot_bytes_up > 0) {
_upload.getPartialProgress().add(-1*tot_bytes_up);
} catch (IOException ex) {
_upload.rejectChunkId(chunk.getId());
if (tot_bytes_up > 0) {
_upload.getPartialProgress().add(-1 * tot_bytes_up);
_upload.getProgress_meter().secureNotify();
}
getLogger(ChunkUploader.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | InterruptedException ex) {
getLogger(ChunkUploader.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if( httpresponse != null ) {
if (httpresponse != null) {
httpresponse.close();
}
}
}
}catch(ChunkInvalidIdException e) {
} catch (ChunkInvalidIdException e) {
} catch (IOException ex) {
_upload.emergencyStopUploader(ex.getMessage());
getLogger(ChunkUploader.class.getName()).log(Level.SEVERE, null, ex);
} catch (URISyntaxException ex) {
Logger.getLogger(ChunkUploader.class.getName()).log(Level.SEVERE, null, ex);
}
_upload.stopThisSlot(this);
_upload.getMac_generator().secureNotify();
System.out.println("ChunkUploader "+_id+" bye bye...");
System.out.println("ChunkUploader " + _id + " bye bye...");
}
}

View File

@ -38,62 +38,58 @@ import org.apache.http.impl.client.CloseableHttpClient;
* @author tonikelope
*/
public class ChunkUploaderMono extends ChunkUploader {
public ChunkUploaderMono(Upload upload) {
super(1, upload);
}
@Override
public void run()
{
System.out.println("ChunkUploader "+getId()+" hello!");
String worker_url=getUpload().getUl_url();
public void run() {
System.out.println("ChunkUploader " + getId() + " hello!");
String worker_url = getUpload().getUl_url();
Chunk chunk;
int reads, to_read, conta_error, re, http_status, tot_bytes_up=-1;
int reads, to_read, conta_error, re, http_status, tot_bytes_up = -1;
byte[] buffer = new byte[MainPanel.THROTTLE_SLICE_SIZE];
boolean error = false;
try(CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient())
{
try (CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient()) {
RandomAccessFile f = new RandomAccessFile(getUpload().getFile_name(), "r");
conta_error = 0;
OutputStream out=null;
OutputStream out = null;
FutureTask<CloseableHttpResponse> futureTask = null;
while(!isExit() && !getUpload().isStopped())
{
CloseableHttpResponse httpresponse=null;
while (!isExit() && !getUpload().isStopped()) {
CloseableHttpResponse httpresponse = null;
chunk = new Chunk(getUpload().nextChunkId(), getUpload().getFile_size(), null);
f.seek(chunk.getOffset());
do
{
to_read = chunk.getSize() - chunk.getOutputStream().size() >= buffer.length?buffer.length:(int)(chunk.getSize() - chunk.getOutputStream().size());
re=f.read(buffer, 0, to_read);
do {
to_read = chunk.getSize() - chunk.getOutputStream().size() >= buffer.length ? buffer.length : (int) (chunk.getSize() - chunk.getOutputStream().size());
re = f.read(buffer, 0, to_read);
chunk.getOutputStream().write(buffer, 0, re);
}while(!isExit() && !getUpload().isStopped() && chunk.getOutputStream().size()<chunk.getSize());
if(tot_bytes_up == -1 || error) {
final HttpPost httppost = new HttpPost(new URI(worker_url+"/"+chunk.getOffset()));
final long postdata_length = getUpload().getFile_size()-chunk.getOffset();
} while (!isExit() && !getUpload().isStopped() && chunk.getOutputStream().size() < chunk.getSize());
if (tot_bytes_up == -1 || error) {
final HttpPost httppost = new HttpPost(new URI(worker_url + "/" + chunk.getOffset()));
final long postdata_length = getUpload().getFile_size() - chunk.getOffset();
httppost.addHeader("Connection", "close");
final PipedInputStream pipein = new PipedInputStream();
PipedOutputStream pipeout = new PipedOutputStream(pipein);
futureTask = new FutureTask<>(new Callable() {
@Override
public CloseableHttpResponse call() throws IOException {
@ -107,46 +103,44 @@ public class ChunkUploaderMono extends ChunkUploader {
THREAD_POOL.execute(futureTask);
out = new ThrottledOutputStream(pipeout, getUpload().getMain_panel().getStream_supervisor());
}
tot_bytes_up=0;
error = false;
try{
if(!isExit() && !getUpload().isStopped()) {
}
tot_bytes_up = 0;
error = false;
try {
if (!isExit() && !getUpload().isStopped()) {
CipherInputStream cis = new CipherInputStream(chunk.getInputStream(), CryptTools.genCrypter("AES", "AES/CTR/NoPadding", getUpload().getByte_file_key(), CryptTools.forwardMEGALinkKeyIV(getUpload().getByte_file_iv(), chunk.getOffset())));
System.out.println(" Subiendo chunk "+chunk.getId()+" desde worker "+ getId() +"...");
System.out.println(" Subiendo chunk " + chunk.getId() + " desde worker " + getId() + "...");
while( !isExit() && !getUpload().isStopped() && (reads=cis.read(buffer))!=-1 && out != null )
{
while (!isExit() && !getUpload().isStopped() && (reads = cis.read(buffer)) != -1 && out != null) {
out.write(buffer, 0, reads);
getUpload().getPartialProgress().add(reads);
getUpload().getProgress_meter().secureNotify();
tot_bytes_up+=reads;
if(getUpload().isPaused() && !getUpload().isStopped()) {
tot_bytes_up += reads;
if (getUpload().isPaused() && !getUpload().isStopped()) {
getUpload().pause_worker();
secureWait();
}
}
if(!getUpload().isStopped()) {
if(tot_bytes_up < chunk.getSize())
{
if(tot_bytes_up > 0) {
getUpload().getPartialProgress().add(-1*tot_bytes_up);
if (!getUpload().isStopped()) {
if (tot_bytes_up < chunk.getSize()) {
if (tot_bytes_up > 0) {
getUpload().getPartialProgress().add(-1 * tot_bytes_up);
getUpload().getProgress_meter().secureNotify();
}
@ -154,143 +148,139 @@ public class ChunkUploaderMono extends ChunkUploader {
error = true;
}
if(error && !getUpload().isStopped()) {
if (error && !getUpload().isStopped()) {
getUpload().rejectChunkId(chunk.getId());
conta_error++;
if(!isExit()) {
if (!isExit()) {
setError_wait(true);
Thread.sleep(getWaitTimeExpBackOff(conta_error)*1000);
Thread.sleep(getWaitTimeExpBackOff(conta_error) * 1000);
setError_wait(false);
}
} else if(!error) {
System.out.println(" Worker "+getId()+" ha subido chunk "+chunk.getId());
} else if (!error) {
System.out.println(" Worker " + getId() + " ha subido chunk " + chunk.getId());
getUpload().getMac_generator().getChunk_queue().put(chunk.getId(), chunk);
getUpload().getMac_generator().secureNotify();
conta_error = 0;
}
}
} else if(isExit()) {
} else if (isExit()) {
getUpload().rejectChunkId(chunk.getId());
}
}
catch (IOException ex)
{
error = true;
getUpload().rejectChunkId(chunk.getId());
if(tot_bytes_up > 0) {
getUpload().getPartialProgress().add(-1*tot_bytes_up);
} catch (IOException ex) {
error = true;
getUpload().rejectChunkId(chunk.getId());
if (tot_bytes_up > 0) {
getUpload().getPartialProgress().add(-1 * tot_bytes_up);
getUpload().getProgress_meter().secureNotify();
}
getLogger(ChunkUploader.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | InterruptedException ex) {
getLogger(ChunkUploader.class.getName()).log(Level.SEVERE, null, ex);
}
if(!error && chunk.getOffset() + tot_bytes_up == getUpload().getFile_size() && futureTask != null) {
try {
httpresponse = futureTask.get();
http_status = httpresponse.getStatusLine().getStatusCode();
if (http_status != HttpStatus.SC_OK )
{
throw new IOException("UPLOAD FAILED! (HTTP STATUS: "+ http_status+")");
if (!error && chunk.getOffset() + tot_bytes_up == getUpload().getFile_size() && futureTask != null) {
} else {
try {
InputStream is=httpresponse.getEntity().getContent();
httpresponse = futureTask.get();
http_status = httpresponse.getStatusLine().getStatusCode();
if (http_status != HttpStatus.SC_OK) {
throw new IOException("UPLOAD FAILED! (HTTP STATUS: " + http_status + ")");
} else {
InputStream is = httpresponse.getEntity().getContent();
ByteArrayOutputStream byte_res = new ByteArrayOutputStream();
while( (reads=is.read(buffer)) != -1 ) {
while ((reads = is.read(buffer)) != -1) {
byte_res.write(buffer, 0, reads);
}
String response = new String(byte_res.toByteArray());
if(response.length() > 0) {
if (response.length() > 0) {
if( MegaAPI.checkMEGAError(response) != 0 )
{
throw new IOException("UPLOAD FAILED! (MEGA ERROR: "+ MegaAPI.checkMEGAError(response)+")");
if (MegaAPI.checkMEGAError(response) != 0) {
throw new IOException("UPLOAD FAILED! (MEGA ERROR: " + MegaAPI.checkMEGAError(response) + ")");
} else {
System.out.println("Completion handle -> "+response);
System.out.println("Completion handle -> " + response);
getUpload().setCompletion_handle(response);
}
}
}
}
}
}catch(ExecutionException exception) {}
finally{
if(out != null) {
} catch (ExecutionException exception) {
} finally {
if (out != null) {
out.close();
}
if(httpresponse != null) {
if (httpresponse != null) {
httpresponse.close();
}
}
} else if(error) {
if(out != null) {
} else if (error) {
if (out != null) {
out.close();
}
if(futureTask != null) {
if (futureTask != null) {
futureTask.cancel(true);
}
}
}
}catch(ChunkInvalidIdException e) {
}
}
} catch (ChunkInvalidIdException e) {
} catch (IOException ex) {
getUpload().emergencyStopUploader(ex.getMessage());
getLogger(ChunkUploader.class.getName()).log(Level.SEVERE, null, ex);
} catch (URISyntaxException | InterruptedException ex) {
Logger.getLogger(ChunkUploaderMono.class.getName()).log(Level.SEVERE, null, ex);
}
}
getUpload().stopThisSlot(this);
getUpload().getMac_generator().secureNotify();
System.out.println("ChunkUploader "+getId()+" bye bye...");
System.out.println("ChunkUploader " + getId() + " bye bye...");
}
}

View File

@ -11,13 +11,12 @@ import static java.util.logging.Logger.getLogger;
import javax.crypto.CipherInputStream;
import javax.crypto.NoSuchPaddingException;
public final class ChunkWriter implements Runnable, SecureNotifiable {
private long _last_chunk_id_written;
private long _bytes_written;
private final long _file_size;
private final ConcurrentHashMap<Long,Chunk> _chunk_queue;
private final ConcurrentHashMap<Long, Chunk> _chunk_queue;
private final Download _download;
private final byte[] _byte_file_key;
private final byte[] _byte_iv;
@ -25,8 +24,8 @@ public final class ChunkWriter implements Runnable, SecureNotifiable {
private final ConcurrentLinkedQueue<Long> _rejectedChunkIds;
private final Object _secure_notify_lock;
private boolean _notified;
public ChunkWriter(Download downloader) throws Exception
{
public ChunkWriter(Download downloader) throws Exception {
_notified = false;
_exit = false;
_download = downloader;
@ -36,43 +35,37 @@ public final class ChunkWriter implements Runnable, SecureNotifiable {
_byte_iv = CryptTools.initMEGALinkKeyIV(_download.getFile_key());
_chunk_queue = new ConcurrentHashMap();
_rejectedChunkIds = new ConcurrentLinkedQueue<>();
if(_download.getProgress() == 0)
{
if (_download.getProgress() == 0) {
_download.setLast_chunk_id_dispatched(0);
_last_chunk_id_written = 0;
_bytes_written = 0;
}
else
{
} else {
_last_chunk_id_written = calculateLastWrittenChunk(_download.getProgress());
_download.setLast_chunk_id_dispatched(_last_chunk_id_written);
_bytes_written = _download.getProgress();
}
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -80,126 +73,112 @@ public final class ChunkWriter implements Runnable, SecureNotifiable {
getLogger(ChunkWriter.class.getName()).log(Level.SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
public byte[] getByte_file_key() {
return _byte_file_key;
}
public ConcurrentLinkedQueue getRejectedChunkIds() {
return _rejectedChunkIds;
}
public boolean isExit() {
return _exit;
}
public long getBytes_written() {
return _bytes_written;
}
public long getLast_chunk_id_written() {
return _last_chunk_id_written;
}
public ConcurrentHashMap getChunk_queue()
{
public ConcurrentHashMap getChunk_queue() {
return _chunk_queue;
}
@Override
public void run()
{
public void run() {
Chunk current_chunk;
CipherInputStream cis;
byte[] buffer = new byte[16*1024];
byte[] buffer = new byte[16 * 1024];
int reads;
try {
System.out.println("Filewriter: let's do some work!");
if(_file_size > 0)
{
while(!_exit && (!_download.isStopped() || !_download.getChunkworkers().isEmpty()) && _bytes_written < _file_size)
{
while(_chunk_queue.containsKey(_last_chunk_id_written+1))
{
current_chunk = _chunk_queue.get(_last_chunk_id_written+1);
cis = new CipherInputStream(current_chunk.getInputStream(), CryptTools.genDecrypter("AES", "AES/CTR/NoPadding", _byte_file_key, CryptTools.forwardMEGALinkKeyIV(_byte_iv, _bytes_written)));
try {
while((reads=cis.read(buffer))!=-1)
{
_download.getOutput_stream().write(buffer, 0, reads);
}
System.out.println("Filewriter: let's do some work!");
cis.close();
if (_file_size > 0) {
while (!_exit && (!_download.isStopped() || !_download.getChunkworkers().isEmpty()) && _bytes_written < _file_size) {
while (_chunk_queue.containsKey(_last_chunk_id_written + 1)) {
current_chunk = _chunk_queue.get(_last_chunk_id_written + 1);
_bytes_written+=current_chunk.getSize();
_chunk_queue.remove(current_chunk.getId());
_last_chunk_id_written = current_chunk.getId();
cis = new CipherInputStream(current_chunk.getInputStream(), CryptTools.genDecrypter("AES", "AES/CTR/NoPadding", _byte_file_key, CryptTools.forwardMEGALinkKeyIV(_byte_iv, _bytes_written)));
while ((reads = cis.read(buffer)) != -1) {
_download.getOutput_stream().write(buffer, 0, reads);
}
if(!_exit && (!_download.isStopped() || !_download.getChunkworkers().isEmpty()) && _bytes_written < _file_size)
{
System.out.println("Filewriter waiting for chunk ["+(_last_chunk_id_written+1)+"]...");
secureWait();
}
cis.close();
_bytes_written += current_chunk.getSize();
_chunk_queue.remove(current_chunk.getId());
_last_chunk_id_written = current_chunk.getId();
}
if (!_exit && (!_download.isStopped() || !_download.getChunkworkers().isEmpty()) && _bytes_written < _file_size) {
System.out.println("Filewriter waiting for chunk [" + (_last_chunk_id_written + 1) + "]...");
secureWait();
}
}
}
} catch (IOException | NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException ex) {
System.out.println(ex.getMessage());
_download.emergencyStopDownloader(ex.getMessage());
}
_exit = true;
_download.secureNotify();
System.out.println("Filewriter: bye bye"+_download.getFile().getName());
}
private long calculateLastWrittenChunk(long temp_file_size)
{
if(temp_file_size > 3584*1024)
{
return 7 + (long)Math.ceil((temp_file_size - 3584*1024)/(1024*1024));
} catch (IOException | NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException ex) {
System.out.println(ex.getMessage());
_download.emergencyStopDownloader(ex.getMessage());
}
else
{
int i=0, tot=0;
while(tot < temp_file_size)
{
_exit = true;
_download.secureNotify();
System.out.println("Filewriter: bye bye" + _download.getFile().getName());
}
private long calculateLastWrittenChunk(long temp_file_size) {
if (temp_file_size > 3584 * 1024) {
return 7 + (long) Math.ceil((temp_file_size - 3584 * 1024) / (1024 * 1024));
} else {
int i = 0, tot = 0;
while (tot < temp_file_size) {
i++;
tot+=i*128*1024;
tot += i * 128 * 1024;
}
return i;
}
}

View File

@ -7,10 +7,13 @@ import java.awt.datatransfer.Transferable;
* @author tonikelope
*/
public interface ClipboardChangeObservable {
void attachObserver(ClipboardChangeObserver observer);
void detachObserver(ClipboardChangeObserver observer);
Transferable getContents();
void notifyChangeToMyObservers();
}

View File

@ -5,7 +5,7 @@ package megabasterd;
* @author tonikelope
*/
public interface ClipboardChangeObserver {
void notifyClipboardChange();
}

View File

@ -4,28 +4,24 @@ import static java.awt.Toolkit.getDefaultToolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import static java.lang.System.out;
import static java.lang.Thread.sleep;
import java.util.concurrent.ConcurrentLinkedQueue;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Logger.getLogger;
public final class ClipboardSpy implements Runnable, ClipboardOwner, SecureNotifiable, ClipboardChangeObservable {
private static final int SLEEP = 50;
private final Clipboard _sysClip;
private boolean _notified;
private final ConcurrentLinkedQueue<ClipboardChangeObserver> _observers;
private Transferable _contents;
private final Object _secure_notify_lock;
private final ConcurrentLinkedQueue<ClipboardChangeObserver> _observers;
private Transferable _contents;
private final Object _secure_notify_lock;
public ClipboardSpy() {
_sysClip = getDefaultToolkit().getSystemClipboard();
@ -34,28 +30,27 @@ public final class ClipboardSpy implements Runnable, ClipboardOwner, SecureNotif
_secure_notify_lock = new Object();
_observers = new ConcurrentLinkedQueue<>();
}
@Override
public Transferable getContents() {
return _contents;
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -63,126 +58,122 @@ public final class ClipboardSpy implements Runnable, ClipboardOwner, SecureNotif
getLogger(ClipboardSpy.class.getName()).log(SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
@Override
public void run() {
_contents = getClipboardContents();
gainOwnership(_contents);
out.println("Spying clipboard...");
System.out.println("Spying clipboard...");
secureWait();
}
@Override
public void lostOwnership(Clipboard c, Transferable t) {
_contents = getClipboardContents();
notifyChangeToMyObservers();
gainOwnership(_contents);
}
private Transferable getClipboardContents() {
boolean error;
Transferable c = null;
do{
do {
error = false;
try{
try {
c = _sysClip.getContents(null);
} catch(Exception ex) {
} catch (Exception ex) {
error = true;
try {
sleep(SLEEP);
} catch (InterruptedException ex1) {
getLogger(ClipboardSpy.class.getName()).log(SEVERE, null, ex1);
}
}
}while(error);
} while (error);
return c;
}
private void gainOwnership(Transferable t) {
boolean error;
do{
do {
error = false;
try{
_sysClip.setContents(t,this);
} catch(Exception ex) {
try {
_sysClip.setContents(t, this);
} catch (Exception ex) {
error = true;
try {
sleep(SLEEP);
} catch (InterruptedException ex1) {
getLogger(ClipboardSpy.class.getName()).log(SEVERE, null, ex1);
}
}
}while(error);
} while (error);
}
@Override
public void attachObserver(ClipboardChangeObserver observer) {
if(!_observers.contains(observer)) {
if (!_observers.contains(observer)) {
_observers.add(observer);
}
}
@Override
public void detachObserver(ClipboardChangeObserver observer) {
_observers.remove(observer);
}
@Override
public void notifyChangeToMyObservers() {
for(ClipboardChangeObserver o:_observers) {
for (ClipboardChangeObserver o : _observers) {
o.notifyClipboardChange();
}
}
}
}

View File

@ -3,14 +3,13 @@ package megabasterd;
import java.util.HashMap;
public final class ContentType {
private final HashMap<String,String> _content_type;
private final HashMap<String, String> _content_type;
public ContentType() {
_content_type = new HashMap();
_content_type.put("mp2", "audio/x-mpeg");
_content_type.put("mp3", "audio/x-mpeg");
_content_type.put("mpga", "audio/x-mpeg");
@ -26,7 +25,7 @@ public final class ContentType {
_content_type.put("avi", "video/x-msvideo");
_content_type.put("ogg", "application/ogg");
_content_type.put("ogv", "video/ogg");
_content_type.put("asf", "video/x-ms-asf-plugin");
_content_type.put("asf", "video/x-ms-asf-plugin");
_content_type.put("asx", "video/x-ms-asf-plugin");
_content_type.put("ogv", "video/ogg");
_content_type.put("wmv", "video/x-ms-wmv");
@ -48,12 +47,12 @@ public final class ContentType {
_content_type.put("mov", "video/quicktime");
_content_type.put("qt", "video/quicktime");
}
public HashMap<String, String> getContent_type() {
return _content_type;
}
public String getMIME(String ext)
{
public String getMIME(String ext) {
return _content_type.get(ext);
}
}

View File

@ -22,8 +22,6 @@ public final class ContextMenuMouseListener extends MouseAdapter {
private JTextComponent _textComponent;
private String _savedString;
private _Actions _lastActionSelected;
public ContextMenuMouseListener() {
_savedString = "";
@ -32,9 +30,9 @@ public final class ContextMenuMouseListener extends MouseAdapter {
@Override
public void actionPerformed(ActionEvent ae) {
_textComponent.setText("");
_textComponent.replaceSelection(_savedString);
_lastActionSelected = _Actions.UNDO;
_textComponent.setText("");
_textComponent.replaceSelection(_savedString);
_lastActionSelected = _Actions.UNDO;
}
};
@ -121,5 +119,8 @@ public final class ContextMenuMouseListener extends MouseAdapter {
_popup.show(e.getComponent(), nx, e.getY() - _popup.getSize().height);
}
}
private enum _Actions { UNDO, CUT, COPY, PASTE, SELECT_ALL }
private enum _Actions {
UNDO, CUT, COPY, PASTE, SELECT_ALL
}
}

View File

@ -26,200 +26,195 @@ import static megabasterd.MiscTools.hex2bin;
import static megabasterd.MiscTools.i32a2bin;
import static megabasterd.MiscTools.long2bytearray;
public final class CryptTools {
public static final int[] AES_ZERO_IV_I32A = {0,0,0,0};
public static final int[] AES_ZERO_IV_I32A = {0, 0, 0, 0};
public static final byte[] AES_ZERO_IV = i32a2bin(AES_ZERO_IV_I32A);
public static final int PBKDF2_SALT_BYTE_LENGTH = 16;
public static final int PBKDF2_ITERATIONS = 0x10000;
public static Cipher genDecrypter(String algo, String mode, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException
{
SecretKeySpec skeySpec = new SecretKeySpec(key, algo);
public static Cipher genDecrypter(String algo, String mode, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
SecretKeySpec skeySpec = new SecretKeySpec(key, algo);
Cipher decryptor = Cipher.getInstance(mode);
if(iv != null) {
if (iv != null) {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
decryptor.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
} else {
decryptor.init(Cipher.DECRYPT_MODE, skeySpec);
}
return decryptor;
}
public static Cipher genCrypter(String algo, String mode, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException
{
SecretKeySpec skeySpec = new SecretKeySpec(key, algo);
public static Cipher genCrypter(String algo, String mode, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
SecretKeySpec skeySpec = new SecretKeySpec(key, algo);
Cipher cryptor = Cipher.getInstance(mode);
if(iv != null) {
if (iv != null) {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cryptor.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
} else {
cryptor.init(Cipher.ENCRYPT_MODE, skeySpec);
}
return cryptor;
}
public static byte[] aes_cbc_encrypt(byte[] data, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher cryptor = CryptTools.genCrypter("AES", "AES/CBC/NoPadding", key, iv);
return cryptor.doFinal(data);
}
public static byte[] aes_cbc_encrypt_pkcs7(byte[] data, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher cryptor = CryptTools.genCrypter("AES", "AES/CBC/PKCS5Padding", key, iv);
return cryptor.doFinal(data);
}
public static byte[] aes_cbc_decrypt(byte[] data, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher decryptor = CryptTools.genDecrypter("AES", "AES/CBC/NoPadding", key, iv);
return decryptor.doFinal(data);
}
public static byte[] aes_cbc_decrypt_pkcs7(byte[] data, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher decryptor = CryptTools.genDecrypter("AES", "AES/CBC/PKCS5Padding", key, iv);
return decryptor.doFinal(data);
}
public static byte[] aes_ecb_encrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher cryptor = CryptTools.genCrypter("AES", "AES/ECB/NoPadding", key, null);
return cryptor.doFinal(data);
}
public static byte[] aes_ecb_decrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher decryptor = CryptTools.genDecrypter("AES", "AES/ECB/NoPadding", key, null);
return decryptor.doFinal(data);
}
public static byte[] aes_ctr_encrypt(byte[] data, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher cryptor = CryptTools.genCrypter("AES", "AES/CTR/NoPadding", key, iv);
return cryptor.doFinal(data);
}
public static byte[] aes_ctr_decrypt(byte[] data, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher decryptor = CryptTools.genDecrypter("AES", "AES/CTR/NoPadding", key, iv);
return decryptor.doFinal(data);
}
public static int[] aes_cbc_encrypt_ia32(int[] data, int[] key, int[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher cryptor = CryptTools.genCrypter("AES", "AES/CBC/NoPadding", i32a2bin(key), i32a2bin(iv));
return bin2i32a(cryptor.doFinal(i32a2bin(data)));
}
public static int[] aes_cbc_decrypt_ia32(int[] data, int[] key, int[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher decryptor = CryptTools.genDecrypter("AES", "AES/CBC/NoPadding", i32a2bin(key), i32a2bin(iv));
return bin2i32a(decryptor.doFinal(i32a2bin(data)));
}
public static int[] aes_ecb_encrypt_ia32(int[] data, int[] key, int[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher cryptor = CryptTools.genCrypter("AES", "AES/ECB/NoPadding", i32a2bin(key), i32a2bin(iv));
return bin2i32a(cryptor.doFinal(i32a2bin(data)));
}
public static int[] aes_ecb_decrypt_ia32(int[] data, int[] key, int[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher decryptor = CryptTools.genDecrypter("AES", "AES/ECB/NoPadding", i32a2bin(key), i32a2bin(iv));
return bin2i32a(decryptor.doFinal(i32a2bin(data)));
}
public static int[] aes_ctr_encrypt_ia32(int[] data, int[] key, int[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher cryptor = CryptTools.genCrypter("AES", "AES/CTR/NoPadding", i32a2bin(key), i32a2bin(iv));
return bin2i32a(cryptor.doFinal(i32a2bin(data)));
}
public static int[] aes_ctr_decrypt_ia32(int[] data, int[] key, int[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher decryptor = CryptTools.genDecrypter("AES", "AES/CTR/NoPadding", i32a2bin(key), i32a2bin(iv));
return bin2i32a(decryptor.doFinal(i32a2bin(data)));
}
public static byte[] rsaDecrypt(BigInteger enc_data, BigInteger p, BigInteger q, BigInteger d) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
RSAPrivateKeySpec privateSpec = new RSAPrivateKeySpec(p.multiply(q), d);
KeyFactory factory = KeyFactory.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
RSAPrivateKey privKey = (RSAPrivateKey) factory.generatePrivate(privateSpec);
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] enc_data_byte = enc_data.toByteArray();
if(enc_data_byte[0] == 0) {
enc_data_byte=Arrays.copyOfRange(enc_data_byte, 1, enc_data_byte.length);
if (enc_data_byte[0] == 0) {
enc_data_byte = Arrays.copyOfRange(enc_data_byte, 1, enc_data_byte.length);
}
byte[] plainText = cipher.doFinal(enc_data_byte);
if(plainText[0] == 0) {
plainText=Arrays.copyOfRange(plainText, 1, plainText.length);
if (plainText[0] == 0) {
plainText = Arrays.copyOfRange(plainText, 1, plainText.length);
}
return plainText;
}
public static byte[] initMEGALinkKey(String key_string) throws Exception
{
public static byte[] initMEGALinkKey(String key_string) throws Exception {
int[] int_key = bin2i32a(UrlBASE642Bin(key_string));
int[] k=new int[4];
int[] k = new int[4];
k[0] = int_key[0] ^ int_key[4];
k[1] = int_key[1] ^ int_key[5];
k[2] = int_key[2] ^ int_key[6];
k[3] = int_key[3] ^ int_key[7];
return i32a2bin(k);
}
public static byte[] initMEGALinkKeyIV(String key_string) throws Exception
{
int[] int_key =bin2i32a(UrlBASE642Bin(key_string));
}
public static byte[] initMEGALinkKeyIV(String key_string) throws Exception {
int[] int_key = bin2i32a(UrlBASE642Bin(key_string));
int[] iv = new int[4];
iv[0] = int_key[4];
@ -229,33 +224,30 @@ public final class CryptTools {
return i32a2bin(iv);
}
public static byte[] forwardMEGALinkKeyIV(byte[] iv, long forward_bytes)
{
public static byte[] forwardMEGALinkKeyIV(byte[] iv, long forward_bytes) {
byte[] new_iv = new byte[iv.length];
System.arraycopy(iv, 0, new_iv, 0, iv.length/2);
byte[] ctr = long2bytearray(forward_bytes/iv.length);
System.arraycopy(ctr, 0, new_iv, iv.length/2, ctr.length);
System.arraycopy(iv, 0, new_iv, 0, iv.length / 2);
byte[] ctr = long2bytearray(forward_bytes / iv.length);
System.arraycopy(ctr, 0, new_iv, iv.length / 2, ctr.length);
return new_iv;
}
public static String decryptMegaDownloaderLink(String link) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, Exception, IllegalBlockSizeException, BadPaddingException
{
String[] keys = {"6B316F36416C2D316B7A3F217A30357958585858585858585858585858585858","ED1F4C200B35139806B260563B3D3876F011B4750F3A1A4A5EFD0BBE67554B44"};
String iv="79F10A01844A0B27FF5B2D4E0ED3163E";
}
public static String decryptMegaDownloaderLink(String link) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, Exception, IllegalBlockSizeException, BadPaddingException {
String[] keys = {"6B316F36416C2D316B7A3F217A30357958585858585858585858585858585858", "ED1F4C200B35139806B260563B3D3876F011B4750F3A1A4A5EFD0BBE67554B44"};
String iv = "79F10A01844A0B27FF5B2D4E0ED3163E";
String enc_type, folder, dec_link;
if((enc_type=findFirstRegex("mega://f?(enc[0-9]*)\\?", link, 1)) != null)
{
if ((enc_type = findFirstRegex("mega://f?(enc[0-9]*)\\?", link, 1)) != null) {
Cipher decrypter;
String the_key=null;
String the_key = null;
switch (enc_type.toLowerCase()) {
case "enc":
the_key = keys[0];
@ -264,82 +256,81 @@ public final class CryptTools {
the_key = keys[1];
break;
}
folder=findFirstRegex("mega://(f)?enc[0-9]*\\?", link, 1);
folder = findFirstRegex("mega://(f)?enc[0-9]*\\?", link, 1);
decrypter = CryptTools.genDecrypter("AES", "AES/CBC/NoPadding", hex2bin(the_key), hex2bin(iv));
byte[] decrypted_data = decrypter.doFinal(UrlBASE642Bin(findFirstRegex("mega://f?enc[0-9]*\\?([\\da-zA-Z_,-]*)", link, 1)));
dec_link=new String(decrypted_data).trim();
return "https://mega.nz/#"+(folder!=null?"f":"")+dec_link;
dec_link = new String(decrypted_data).trim();
return "https://mega.nz/#" + (folder != null ? "f" : "") + dec_link;
} else {
return link;
}
}
public static String MEGAUserHash(byte[] str, int[] aeskey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, Exception {
int[] s32 = bin2i32a(str);
int[] h32 = {0,0,0,0};
int[] iv = {0,0,0,0};
for(int i=0; i<s32.length; i++) {
h32[i%4]^=s32[i];
}
for(int i=0; i<0x4000; i++) {
int[] h32 = {0, 0, 0, 0};
int[] iv = {0, 0, 0, 0};
for (int i = 0; i < s32.length; i++) {
h32[i % 4] ^= s32[i];
}
for (int i = 0; i < 0x4000; i++) {
h32 = CryptTools.aes_cbc_encrypt_ia32(h32, aeskey, iv);
}
int[] res = {h32[0], h32[2]};
return Bin2UrlBASE64(i32a2bin(res));
}
public static int[] MEGAPrepareMasterKey(int[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
int[] pkey = {0x93C467E3, 0x7DB0_C7A4, 0xD1BE_3F81, 0x0152_CB56};
int[] iv = {0,0,0,0};
for(int r=0; r<0x10000; r++) {
for(int j=0; j<key.length; j+=4) {
int[] k = {0,0,0,0};
for(int i=0; i<4; i++) {
if(i+j < key.length) {
k[i] = key[i+j];
int[] iv = {0, 0, 0, 0};
for (int r = 0; r < 0x10000; r++) {
for (int j = 0; j < key.length; j += 4) {
int[] k = {0, 0, 0, 0};
for (int i = 0; i < 4; i++) {
if (i + j < key.length) {
k[i] = key[i + j];
}
}
pkey = CryptTools.aes_cbc_encrypt_ia32(pkey, k, iv);
}
}
return pkey;
}
public static byte[] PBKDF2HMACSHA256(String password, byte[] salt, int iterations) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec ks = new PBEKeySpec(password.toCharArray(), salt, iterations, 256);
return f.generateSecret(ks).getEncoded();
}
private CryptTools() {
}
}

View File

@ -15,30 +15,30 @@ import static java.util.logging.Logger.getLogger;
* @author tonikelope
*/
public final class DBTools {
public static void setupSqliteTables() throws SQLException {
try (Connection conn = SqliteSingleton.getInstance().getConn(); Statement stat = conn.createStatement()) {
stat.executeUpdate("CREATE TABLE IF NOT EXISTS downloads(url TEXT, path TEXT, filename TEXT, filekey TEXT, filesize UNSIGNED BIG INT, filepass VARCHAR(64), filenoexpire VARCHAR(64), PRIMARY KEY ('url'), UNIQUE(path, filename));");
stat.executeUpdate("CREATE TABLE IF NOT EXISTS uploads(filename TEXT, email TEXT, url TEXT, ul_key TEXT, parent_node TEXT, root_node TEXT, share_key TEXT, folder_link TEXT, PRIMARY KEY ('filename'), UNIQUE(filename, email));");
stat.executeUpdate("CREATE TABLE IF NOT EXISTS settings(key VARCHAR(255), value TEXT, PRIMARY KEY('key'));");
stat.executeUpdate("CREATE TABLE IF NOT EXISTS mega_accounts(email TEXT, password TEXT, password_aes TEXT, user_hash TEXT, PRIMARY KEY('email'));");
}
}
public static void vaccum() throws SQLException {
try (Connection conn = SqliteSingleton.getInstance().getConn(); Statement stat = conn.createStatement()) {
stat.execute("VACUUM");
}
}
public static void insertDownload(String url, String path, String filename, String filekey, Long size, String filepass, String filenoexpire) throws SQLException {
try (Connection conn = SqliteSingleton.getInstance().getConn(); PreparedStatement ps = conn.prepareStatement("INSERT INTO downloads (url, path, filename, filekey, filesize, filepass, filenoexpire) VALUES (?,?,?,?,?,?,?)")) {
ps.setString(1, url);
ps.setString(2, path);
ps.setString(3, filename);
@ -50,22 +50,22 @@ public final class DBTools {
ps.executeUpdate();
}
}
public static void deleteDownload(String url) throws SQLException {
try (Connection conn = SqliteSingleton.getInstance().getConn(); PreparedStatement ps = conn.prepareStatement("DELETE FROM downloads WHERE url=?")) {
ps.setString(1, url);
ps.executeUpdate();
}
}
public static void insertUpload(String filename, String email, String parent_node, String ul_key, String root_node, String share_key, String folder_link) throws SQLException {
try (Connection conn = SqliteSingleton.getInstance().getConn(); PreparedStatement ps = conn.prepareStatement("INSERT INTO uploads (filename, email, parent_node, ul_key, root_node, share_key, folder_link) VALUES (?,?,?,?,?,?,?)")) {
ps.setString(1, filename);
ps.setString(2, email);
ps.setString(3, parent_node);
@ -76,10 +76,10 @@ public final class DBTools {
ps.executeUpdate();
}
}
}
public static void updateUploadUrl(String filename, String email, String ul_url) throws SQLException {
try (Connection conn = SqliteSingleton.getInstance().getConn(); PreparedStatement ps = conn.prepareStatement("UPDATE uploads SET url=? WHERE filename=? AND email=?")) {
ps.setString(1, ul_url);
@ -88,13 +88,13 @@ public final class DBTools {
ps.executeUpdate();
}
}
}
public static void deleteUpload(String filename, String email) throws SQLException {
try (Connection conn = SqliteSingleton.getInstance().getConn(); PreparedStatement ps = conn.prepareStatement("DELETE FROM uploads WHERE filename=? AND email=?")) {
ps.setString(1, filename);
ps.setString(2, email);
@ -102,29 +102,29 @@ public final class DBTools {
ps.executeUpdate();
}
}
public static String selectSettingValueFromDB(String key) {
String value=null;
String value = null;
try (Connection conn = SqliteSingleton.getInstance().getConn(); PreparedStatement ps = conn.prepareStatement("SELECT value from settings WHERE key=?")) {
ps.setString(1, key);
ResultSet res = ps.executeQuery();
if(res.next()) {
if (res.next()) {
value = res.getString(1);
}
} catch (SQLException ex) {
getLogger(DBTools.class.getName()).log(Level.SEVERE, null, ex);
}
return value;
}
public static void insertSettingValueInDB(String key, String value) throws SQLException {
public static void insertSettingValueInDB(String key, String value) throws SQLException {
try (Connection conn = SqliteSingleton.getInstance().getConn(); PreparedStatement ps = conn.prepareStatement("INSERT OR REPLACE INTO settings (key,value) VALUES (?, ?)")) {
ps.setString(1, key);
@ -134,21 +134,21 @@ public final class DBTools {
ps.executeUpdate();
}
}
public static ArrayList<HashMap<String,Object>> selectDownloads() throws SQLException {
ArrayList<HashMap<String,Object>> downloads = new ArrayList<>();
public static ArrayList<HashMap<String, Object>> selectDownloads() throws SQLException {
ArrayList<HashMap<String, Object>> downloads = new ArrayList<>();
ResultSet res;
try (Connection conn = SqliteSingleton.getInstance().getConn(); Statement stat = conn.createStatement()) {
res = stat.executeQuery("SELECT * FROM downloads");
while(res.next()) {
HashMap<String,Object> download = new HashMap<>();
while (res.next()) {
HashMap<String, Object> download = new HashMap<>();
download.put("url", res.getString("url"));
download.put("path", res.getString("path"));
download.put("filename", res.getString("filename"));
@ -156,28 +156,28 @@ public final class DBTools {
download.put("filesize", res.getLong("filesize"));
download.put("filepass", res.getString("filepass"));
download.put("filenoexpire", res.getString("filenoexpire"));
downloads.add(download);
}
}
return downloads;
}
public static ArrayList<HashMap<String,Object>> selectUploads() throws SQLException {
ArrayList<HashMap<String,Object>> uploads = new ArrayList<>();
public static ArrayList<HashMap<String, Object>> selectUploads() throws SQLException {
ArrayList<HashMap<String, Object>> uploads = new ArrayList<>();
ResultSet res;
try (Connection conn = SqliteSingleton.getInstance().getConn(); Statement stat = conn.createStatement()) {
res = stat.executeQuery("SELECT * FROM uploads");
while(res.next()) {
HashMap<String,Object> upload = new HashMap<>();
while (res.next()) {
HashMap<String, Object> upload = new HashMap<>();
upload.put("filename", res.getString("filename"));
upload.put("email", res.getString("email"));
upload.put("url", res.getString("url"));
@ -189,42 +189,41 @@ public final class DBTools {
uploads.add(upload);
}
}
return uploads;
}
public static HashMap<String,Object> selectMegaAccounts() throws SQLException {
public static HashMap<String, Object> selectMegaAccounts() throws SQLException {
HashMap<String, Object> accounts = new HashMap<>();
ResultSet res;
try (Connection conn = SqliteSingleton.getInstance().getConn(); Statement stat = conn.createStatement()) {
res = stat.executeQuery("SELECT * FROM mega_accounts");
while(res.next()) {
HashMap<String,Object> account_data = new HashMap<>();
while (res.next()) {
HashMap<String, Object> account_data = new HashMap<>();
account_data.put("password", res.getString("password"));
account_data.put("password_aes", res.getString("password_aes"));
account_data.put("user_hash", res.getString("user_hash"));
accounts.put(res.getString("email"), account_data);
}
}
return accounts;
}
public static void insertMegaAccount(String email, String password, String password_aes, String user_hash) throws SQLException {
try (Connection conn = SqliteSingleton.getInstance().getConn(); PreparedStatement ps = conn.prepareStatement("INSERT OR REPLACE INTO mega_accounts (email,password,password_aes,user_hash) VALUES (?, ?, ?, ?)")) {
ps.setString(1, email);
ps.setString(2, password);
ps.setString(3, password_aes);
@ -232,22 +231,22 @@ public final class DBTools {
ps.setString(4, user_hash);
ps.executeUpdate();
}
}
}
public static void deleteMegaAccount(String email) throws SQLException {
try (Connection conn = SqliteSingleton.getInstance().getConn(); PreparedStatement ps = conn.prepareStatement("DELETE from mega_accounts WHERE email=?")) {
try (Connection conn = SqliteSingleton.getInstance().getConn(); PreparedStatement ps = conn.prepareStatement("DELETE from mega_accounts WHERE email=?")) {
ps.setString(1, email);
ps.executeUpdate();
}
}
private DBTools() {
}
}

File diff suppressed because it is too large Load Diff

View File

@ -7,94 +7,93 @@ import static java.util.logging.Logger.getLogger;
import static megabasterd.DBTools.deleteDownload;
import static megabasterd.MainPanel.THREAD_POOL;
public final class DownloadManager extends TransferenceManager {
public DownloadManager(MainPanel main_panel) {
super(main_panel, main_panel.getMax_dl(), main_panel.getView().getStatus_down_label(), main_panel.getView().getjPanel_scroll_down(), main_panel.getView().getClose_all_finished_down_button(), main_panel.getView().getPause_all_down_button(), main_panel.getView().getClean_all_down_menu());
}
@Override
public void remove(Transference download) {
getScroll_panel().remove(((Download)download).getView());
getScroll_panel().remove(((Download) download).getView());
getTransference_waitstart_queue().remove(download);
getTransference_running_list().remove(download);
getTransference_finished_queue().remove(download);
if(((Download)download).isProvision_ok()) {
if (((Download) download).isProvision_ok()) {
try {
deleteDownload(((Download)download).getUrl());
deleteDownload(((Download) download).getUrl());
} catch (SQLException ex) {
getLogger(DownloadManager.class.getName()).log(SEVERE, null, ex);
}
}
secureNotify();
}
@Override
public void provision(final Transference download)
{
getScroll_panel().add(((Download)download).getView());
public void provision(final Transference download) {
getScroll_panel().add(((Download) download).getView());
try {
_provision((Download)download, false);
_provision((Download) download, false);
secureNotify();
} catch (MegaAPIException | MegaCrypterAPIException ex) {
System.out.println("Provision failed! Retrying in separated thread...");
THREAD_POOL.execute(new Runnable(){
THREAD_POOL.execute(new Runnable() {
@Override
public void run(){
public void run() {
try {
_provision((Download)download, true);
_provision((Download) download, true);
} catch (MegaAPIException | MegaCrypterAPIException ex1) {
getLogger(DownloadManager.class.getName()).log(SEVERE, null, ex1);
}
secureNotify();
}});
}
});
}
}
private void _provision(Download download, boolean retry) throws MegaAPIException, MegaCrypterAPIException {
download.provisionIt(retry);
if(download.isProvision_ok()) {
if (download.isProvision_ok()) {
getTransference_waitstart_queue().add(download);
if(getTransference_provision_queue().isEmpty()) {
if (getTransference_provision_queue().isEmpty()) {
sortTransferenceStartQueue();
for(Transference down:getTransference_waitstart_queue()) {
for (Transference down : getTransference_waitstart_queue()) {
getScroll_panel().remove((Component)down.getView());
getScroll_panel().add((Component)down.getView());
getScroll_panel().remove((Component) down.getView());
getScroll_panel().add((Component) down.getView());
}
for(Transference down:getTransference_finished_queue()) {
for (Transference down : getTransference_finished_queue()) {
getScroll_panel().remove((Component)down.getView());
getScroll_panel().add((Component)down.getView());
getScroll_panel().remove((Component) down.getView());
getScroll_panel().add((Component) down.getView());
}
}
@ -103,5 +102,5 @@ public final class DownloadManager extends TransferenceManager {
getTransference_finished_queue().add(download);
}
}
}

View File

@ -11,12 +11,10 @@ import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import static megabasterd.MainPanel.FONT_DEFAULT;
import static megabasterd.MainPanel.THREAD_POOL;
import static megabasterd.MiscTools.copyTextToClipboard;
import static megabasterd.MiscTools.swingReflectionInvoke;
import static megabasterd.MiscTools.swingReflectionInvokeAndWait;
import static megabasterd.MiscTools.updateFont;
public final class DownloadView extends javax.swing.JPanel implements TransferenceView {
private final Download _download;
@ -82,45 +80,45 @@ public final class DownloadView extends javax.swing.JPanel implements Transferen
}
public DownloadView(Download download) {
initComponents();
_download = download;
MiscTools.swingInvokeIt(new Runnable(){
MiscTools.swingInvokeIt(new Runnable() {
@Override
public void run() {
updateFont(status_label, FONT_DEFAULT, Font.BOLD);
updateFont(remtime_label, FONT_DEFAULT, Font.PLAIN);
updateFont(speed_label, FONT_DEFAULT, Font.BOLD);
updateFont(progress_pbar, FONT_DEFAULT, Font.PLAIN);
updateFont(slots_label, FONT_DEFAULT, Font.BOLD);
updateFont(slots_spinner, FONT_DEFAULT, Font.PLAIN);
updateFont(pause_button, FONT_DEFAULT, Font.BOLD);
updateFont(stop_button, FONT_DEFAULT, Font.BOLD);
updateFont(keep_temp_checkbox, FONT_DEFAULT, Font.PLAIN);
updateFont(file_name_label, FONT_DEFAULT, Font.PLAIN);
updateFont(file_size_label, FONT_DEFAULT, Font.BOLD);
updateFont(close_button, FONT_DEFAULT, Font.PLAIN);
updateFont(copy_link_button, FONT_DEFAULT, Font.PLAIN);
updateFont(restart_button, FONT_DEFAULT, Font.PLAIN);
updateFont(slot_status_label, FONT_DEFAULT, Font.BOLD);}}, true);
updateFont(remtime_label, FONT_DEFAULT, Font.PLAIN);
updateFont(speed_label, FONT_DEFAULT, Font.BOLD);
updateFont(progress_pbar, FONT_DEFAULT, Font.PLAIN);
updateFont(slots_label, FONT_DEFAULT, Font.BOLD);
updateFont(slots_spinner, FONT_DEFAULT, Font.PLAIN);
updateFont(pause_button, FONT_DEFAULT, Font.BOLD);
updateFont(stop_button, FONT_DEFAULT, Font.BOLD);
updateFont(keep_temp_checkbox, FONT_DEFAULT, Font.PLAIN);
updateFont(file_name_label, FONT_DEFAULT, Font.PLAIN);
updateFont(file_size_label, FONT_DEFAULT, Font.BOLD);
updateFont(close_button, FONT_DEFAULT, Font.PLAIN);
updateFont(copy_link_button, FONT_DEFAULT, Font.PLAIN);
updateFont(restart_button, FONT_DEFAULT, Font.PLAIN);
updateFont(slot_status_label, FONT_DEFAULT, Font.BOLD);
}
}, true);
swingReflectionInvokeAndWait("setModel", slots_spinner, new SpinnerNumberModel(_download.getMain_panel().getDefault_slots_down(), Download.MIN_WORKERS, Download.MAX_WORKERS, 1));
swingReflectionInvoke("setEditable", ((JSpinner.DefaultEditor)slots_spinner.getEditor()).getTextField(), false);
swingReflectionInvoke("setForeground", speed_label, new Color(0,128,255));
swingReflectionInvoke("setVisible", new Object[]{slots_spinner, slots_label, pause_button, stop_button, speed_label, remtime_label,progress_pbar,keep_temp_checkbox,file_name_label,close_button,copy_link_button,restart_button,file_size_label}, false);
swingReflectionInvoke("setEditable", ((JSpinner.DefaultEditor) slots_spinner.getEditor()).getTextField(), false);
swingReflectionInvoke("setForeground", speed_label, new Color(0, 128, 255));
swingReflectionInvoke("setVisible", new Object[]{slots_spinner, slots_label, pause_button, stop_button, speed_label, remtime_label, progress_pbar, keep_temp_checkbox, file_name_label, close_button, copy_link_button, restart_button, file_size_label}, false);
}
public void hideAllExceptStatus()
{
swingReflectionInvoke("setVisible", new Object[]{speed_label, remtime_label, slots_spinner,slots_label,slot_status_label,slot_status_label,pause_button,stop_button,progress_pbar,keep_temp_checkbox}, false);
public void hideAllExceptStatus() {
swingReflectionInvoke("setVisible", new Object[]{speed_label, remtime_label, slots_spinner, slots_label, slot_status_label, slot_status_label, pause_button, stop_button, progress_pbar, keep_temp_checkbox}, false);
}
/**
@ -325,41 +323,40 @@ public final class DownloadView extends javax.swing.JPanel implements Transferen
private void slots_spinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_slots_spinnerStateChanged
THREAD_POOL.execute(new Runnable(){
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
_download.checkSlotsAndWorkers();
}
});
}//GEN-LAST:event_slots_spinnerStateChanged
private void close_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_close_buttonActionPerformed
_download.close();
}//GEN-LAST:event_close_buttonActionPerformed
private void copy_link_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copy_link_buttonActionPerformed
copyTextToClipboard(_download.getUrl());
MiscTools.copyTextToClipboard(_download.getUrl());
JOptionPane.showMessageDialog(_download.getMain_panel().getView(), "Link was copied to clipboard!");
}//GEN-LAST:event_copy_link_buttonActionPerformed
private void restart_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restart_buttonActionPerformed
_download.restart();
}//GEN-LAST:event_restart_buttonActionPerformed
private void stop_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stop_buttonActionPerformed
_download.stop();
}//GEN-LAST:event_stop_buttonActionPerformed
private void pause_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pause_buttonActionPerformed
_download.pause();
}//GEN-LAST:event_pause_buttonActionPerformed
@ -367,123 +364,119 @@ public final class DownloadView extends javax.swing.JPanel implements Transferen
public void pause() {
printStatusNormal("Pausing download ...");
swingReflectionInvoke("setEnabled", new Object[]{pause_button,speed_label,slots_label,slots_spinner}, false);
swingReflectionInvoke("setEnabled", new Object[]{pause_button, speed_label, slots_label, slots_spinner}, false);
swingReflectionInvoke("setVisible", new Object[]{stop_button, keep_temp_checkbox}, true);
}
@Override
public void resume() {
printStatusNormal("Downloading file from mega ...");
swingReflectionInvoke("setEnabled", new Object[]{pause_button,speed_label,slots_label,slots_spinner}, true);
swingReflectionInvoke("setEnabled", new Object[]{pause_button, speed_label, slots_label, slots_spinner}, true);
swingReflectionInvoke("setVisible", new Object[]{stop_button, keep_temp_checkbox}, false);
swingReflectionInvoke("setText", pause_button, "PAUSE DOWNLOAD");
swingReflectionInvoke("setVisible", _download.getMain_panel().getView().getPause_all_down_button(), true);
}
@Override
public void stop() {
printStatusNormal("Stopping download safely, please wait...");
swingReflectionInvoke("setEnabled", new Object[]{pause_button,keep_temp_checkbox,stop_button,speed_label,slots_label,slots_spinner}, false);
}
@Override
public void stop() {
printStatusNormal("Stopping download safely, please wait...");
swingReflectionInvoke("setEnabled", new Object[]{pause_button, keep_temp_checkbox, stop_button, speed_label, slots_label, slots_spinner}, false);
}
@Override
public void updateSpeed(String speed, Boolean visible) {
if(speed != null) {
if (speed != null) {
swingReflectionInvoke("setText", speed_label, speed);
}
if(visible != null) {
if (visible != null) {
swingReflectionInvoke("setVisible", speed_label, visible);
}
}
@Override
public void updateRemainingTime(String rem_time, Boolean visible) {
if(speed_label != null) {
if (speed_label != null) {
swingReflectionInvoke("setText", remtime_label, rem_time);
}
if(visible != null) {
if (visible != null) {
swingReflectionInvoke("setVisible", remtime_label, visible);
}
}
@Override
public void updateProgressBar(long progress, double bar_rate) {
swingReflectionInvoke("setValue", progress_pbar, (int)Math.ceil(bar_rate*progress));
swingReflectionInvoke("setValue", progress_pbar, (int) Math.ceil(bar_rate * progress));
}
@Override
public void printStatusError(String message)
{
public void printStatusError(String message) {
swingReflectionInvoke("setForeground", status_label, Color.red);
swingReflectionInvoke("setText", status_label, message);
}
@Override
public void printStatusOK(String message)
{
swingReflectionInvoke("setForeground", status_label, new Color(0,128,0));
public void printStatusOK(String message) {
swingReflectionInvoke("setForeground", status_label, new Color(0, 128, 0));
swingReflectionInvoke("setText", status_label, message);
}
@Override
public void printStatusNormal(String message)
{
public void printStatusNormal(String message) {
swingReflectionInvoke("setForeground", status_label, Color.BLACK);
swingReflectionInvoke("setText", status_label, message);
}
@Override
public synchronized void updateSlotsStatus() {
int conta_exit = 0;
for(ChunkDownloader c:_download.getChunkworkers()) {
if(c.isExit()) {
for (ChunkDownloader c : _download.getChunkworkers()) {
if (c.isExit()) {
conta_exit++;
}
}
int conta_error = 0;
for(ChunkDownloader c:_download.getChunkworkers()) {
if(c.isError_wait()) {
for (ChunkDownloader c : _download.getChunkworkers()) {
if (c.isError_wait()) {
conta_error++;
}
}
if(conta_error > 0) {
if (conta_error > 0) {
swingReflectionInvoke("setForeground", slot_status_label, Color.red);
} else {
swingReflectionInvoke("setForeground", slot_status_label, Color.black);
}
swingReflectionInvoke("setText", slot_status_label, (conta_exit>0?"Removing: "+conta_exit:"") + (conta_error>0?((conta_exit>0?" / ":"")+"Error: " + conta_error):""));
swingReflectionInvoke("setText", slot_status_label, (conta_exit > 0 ? "Removing: " + conta_exit : "") + (conta_error > 0 ? ((conta_exit > 0 ? " / " : "") + "Error: " + conta_error) : ""));
}
// Variables declaration - do not modify//GEN-BEGIN:variables
@ -504,6 +497,4 @@ public final class DownloadView extends javax.swing.JPanel implements Transferen
private javax.swing.JButton stop_button;
// End of variables declaration//GEN-END:variables
}

View File

@ -15,6 +15,8 @@ import javax.swing.JFileChooser;
import javax.swing.JTextField;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import static megabasterd.MainPanel.FONT_DEFAULT;
import static megabasterd.MainPanel.THREAD_POOL;
import static megabasterd.MiscTools.BASE642Bin;
@ -63,57 +65,61 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
public JTextField getDir_name_textfield() {
return dir_name_textfield;
}
public boolean isRemember_master_pass() {
return _remember_master_pass;
}
/**
* Creates new form FileGrabber
*
* @param parent
* @param modal
*/
public FileGrabberDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
_last_selected_account = null;
_total_space = 0L;
_base_path = null;
_upload = false;
_remember_master_pass = true;
_files = new ArrayList<>();
MiscTools.swingInvokeIt(new Runnable(){
MiscTools.swingInvokeIt(new Runnable() {
@Override
public void run() {updateFont(dance_button, FONT_DEFAULT, Font.PLAIN);
updateFont(add_files_button, FONT_DEFAULT, Font.PLAIN);
updateFont(add_folder_button, FONT_DEFAULT, Font.PLAIN);
updateFont(account_combobox, FONT_DEFAULT, Font.PLAIN);
updateFont(dir_name_label, FONT_DEFAULT, Font.PLAIN);
updateFont(account_label, FONT_DEFAULT, Font.PLAIN);
updateFont(used_space_label, FONT_DEFAULT, Font.BOLD);
updateFont(total_file_size_label, FONT_DEFAULT, Font.BOLD);
updateFont(file_tree, FONT_DEFAULT, Font.PLAIN);
updateFont(warning_label, FONT_DEFAULT, Font.PLAIN);
updateFont(dir_name_textfield, FONT_DEFAULT, Font.PLAIN);
updateFont(skip_button, FONT_DEFAULT, Font.PLAIN);
updateFont(skip_rest_button, FONT_DEFAULT, Font.PLAIN);}}, true);
swingReflectionInvokeAndWait("addMouseListener", dir_name_textfield, new ContextMenuMouseListener());
_main_panel = ((MainPanelView)parent).getMain_panel();
if( _main_panel.getMega_accounts().size() > 0) {
for (Object o:_main_panel.getMega_accounts().keySet()) {
swingReflectionInvoke("addItem", account_combobox, (String)o);
public void run() {
updateFont(dance_button, FONT_DEFAULT, Font.PLAIN);
updateFont(add_files_button, FONT_DEFAULT, Font.PLAIN);
updateFont(add_folder_button, FONT_DEFAULT, Font.PLAIN);
updateFont(account_combobox, FONT_DEFAULT, Font.PLAIN);
updateFont(dir_name_label, FONT_DEFAULT, Font.PLAIN);
updateFont(account_label, FONT_DEFAULT, Font.PLAIN);
updateFont(used_space_label, FONT_DEFAULT, Font.BOLD);
updateFont(total_file_size_label, FONT_DEFAULT, Font.BOLD);
updateFont(file_tree, FONT_DEFAULT, Font.PLAIN);
updateFont(warning_label, FONT_DEFAULT, Font.PLAIN);
updateFont(dir_name_textfield, FONT_DEFAULT, Font.PLAIN);
updateFont(skip_button, FONT_DEFAULT, Font.PLAIN);
updateFont(skip_rest_button, FONT_DEFAULT, Font.PLAIN);
}
}, true);
swingReflectionInvokeAndWait("addMouseListener", dir_name_textfield, new ContextMenuMouseListener());
_main_panel = ((MainPanelView) parent).getMain_panel();
if (_main_panel.getMega_accounts().size() > 0) {
for (Object o : _main_panel.getMega_accounts().keySet()) {
swingReflectionInvoke("addItem", account_combobox, o);
}
} else {
swingReflectionInvoke("setText", used_space_label, "No MEGA accounts available!!");
}
@ -345,9 +351,9 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
}// </editor-fold>//GEN-END:initComponents
private void add_files_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_files_buttonActionPerformed
add_files_button.setText("Adding files, please wait...");
add_files_button.setEnabled(false);
add_files_button.setEnabled(false);
add_folder_button.setEnabled(false);
warning_label.setEnabled(false);
skip_button.setEnabled(false);
@ -355,18 +361,17 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
dance_button.setEnabled(false);
dir_name_textfield.setEnabled(false);
dir_name_label.setEnabled(false);
JFileChooser filechooser = new javax.swing.JFileChooser();
filechooser.setDialogTitle("Add files");
filechooser.setAcceptAllFileFilterUsed(false);
filechooser.setMultiSelectionEnabled(true);
if( filechooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ) {
if (filechooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
total_file_size_label.setText("[0 B]");
File[] files_selected = filechooser.getSelectedFiles();
@ -375,17 +380,17 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
System.out.println(_base_path);
dir_name_textfield.setText(files_selected[0].getParentFile().getName()+"_"+genID(10));
dir_name_textfield.setText(files_selected[0].getParentFile().getName() + "_" + genID(10));
dir_name_textfield.setEnabled(true);
dir_name_label.setEnabled(true);
DefaultMutableTreeNode root = new DefaultMutableTreeNode(filechooser.getSelectedFile().getParent());
for(File file:files_selected) {
for (File file : files_selected) {
DefaultMutableTreeNode current_file = new DefaultMutableTreeNode( file.getName() + (file.isFile()?" ["+ formatBytes(file.length())+"]":"") );
DefaultMutableTreeNode current_file = new DefaultMutableTreeNode(file.getName() + (file.isFile() ? " [" + formatBytes(file.length()) + "]" : ""));
root.add(current_file);
}
@ -395,15 +400,15 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
file_tree.setModel(tree_model);
_genFileList();
add_files_button.setEnabled(true);
add_folder_button.setEnabled(true);
add_files_button.setText("Add files");
boolean root_childs = ((DefaultMutableTreeNode)tree_model.getRoot()).getChildCount()>0;
boolean root_childs = ((TreeNode) tree_model.getRoot()).getChildCount() > 0;
file_tree.setRootVisible(root_childs);
file_tree.setEnabled(root_childs);
warning_label.setEnabled(root_childs);
@ -411,11 +416,11 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
total_file_size_label.setEnabled(root_childs);
skip_button.setEnabled(root_childs);
skip_rest_button.setEnabled(root_childs);
} else {
add_files_button.setText("Add files");
add_files_button.setEnabled(true);
add_files_button.setEnabled(true);
add_folder_button.setEnabled(true);
warning_label.setEnabled(true);
skip_button.setEnabled(true);
@ -427,10 +432,10 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
}//GEN-LAST:event_add_files_buttonActionPerformed
private void add_folder_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_folder_buttonActionPerformed
add_folder_button.setText("Adding files, please wait...");
add_files_button.setEnabled(false);
add_files_button.setEnabled(false);
add_folder_button.setEnabled(false);
warning_label.setEnabled(false);
skip_button.setEnabled(false);
@ -438,49 +443,49 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
dance_button.setEnabled(false);
dir_name_textfield.setEnabled(false);
dir_name_label.setEnabled(false);
JFileChooser filechooser = new javax.swing.JFileChooser();
filechooser.setDialogTitle("Add directory");
filechooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
filechooser.setAcceptAllFileFilterUsed(false);
if( filechooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ) {
if (filechooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
total_file_size_label.setText("[0 B]");
_base_path = filechooser.getSelectedFile().getAbsolutePath();
System.out.println(_base_path);
dir_name_textfield.setText(filechooser.getSelectedFile().getName()+"_"+genID(10));
dir_name_textfield.setText(filechooser.getSelectedFile().getName() + "_" + genID(10));
dir_name_textfield.setEnabled(true);
dir_name_label.setEnabled(true);
DefaultMutableTreeNode root = new DefaultMutableTreeNode(filechooser.getSelectedFile().getAbsolutePath());
_genFileTree(filechooser.getSelectedFile().getAbsolutePath(), root);
DefaultTreeModel tree_model = new DefaultTreeModel(sortTree(root));
file_tree.setModel(tree_model);
_genFileList();
add_files_button.setEnabled(true);
add_folder_button.setEnabled(true);
add_folder_button.setText("Add folder");
boolean root_childs = ((DefaultMutableTreeNode)tree_model.getRoot()).getChildCount()>0;
boolean root_childs = ((TreeNode) tree_model.getRoot()).getChildCount() > 0;
file_tree.setRootVisible(root_childs);
file_tree.setRootVisible(root_childs);
file_tree.setEnabled(root_childs);
warning_label.setEnabled(root_childs);
@ -488,10 +493,10 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
total_file_size_label.setEnabled(root_childs);
skip_button.setEnabled(root_childs);
skip_rest_button.setEnabled(root_childs);
} else {
add_folder_button.setText("Add folder");
add_files_button.setEnabled(true);
add_files_button.setEnabled(true);
add_folder_button.setEnabled(true);
warning_label.setEnabled(true);
skip_button.setEnabled(true);
@ -499,35 +504,34 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
dance_button.setEnabled(true);
dir_name_textfield.setEnabled(true);
dir_name_label.setEnabled(true);
}
}//GEN-LAST:event_add_folder_buttonActionPerformed
private void dance_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dance_buttonActionPerformed
_upload = true;
this.setVisible(false);
}//GEN-LAST:event_dance_buttonActionPerformed
private void account_comboboxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_account_comboboxItemStateChanged
String selected_item = (String)account_combobox.getSelectedItem();
if(selected_item != null && !selected_item.equals(_last_selected_account)) {
String selected_item = (String) account_combobox.getSelectedItem();
if (selected_item != null && !selected_item.equals(_last_selected_account)) {
_last_selected_account = selected_item;
final String email = selected_item;
final Dialog tthis = this;
used_space_label.setForeground(Color.black);
used_space_label.setText("Checking account quota, please wait...");
account_combobox.setEnabled(false);
account_label.setEnabled(false);
dance_button.setEnabled(false);
@ -539,142 +543,140 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
skip_rest_button.setEnabled(false);
warning_label.setEnabled(false);
file_tree.setEnabled(false);
THREAD_POOL.execute(new Runnable(){
@Override
public void run() {
HashMap<String,Object> account_info = (HashMap)_main_panel.getMega_accounts().get(email);
Long[] quota = null;
MegaAPI ma = _main_panel.getMega_active_accounts().get((String)account_combobox.getSelectedItem());
if(ma == null) {
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
ma = new MegaAPI();
String password_aes, user_hash;
try {
if(_main_panel.getMega_master_pass_hash() != null) {
if(_main_panel.getMega_master_pass() == null) {
GetMegaMasterPasswordDialog dialog = new GetMegaMasterPasswordDialog((Frame)getParent(), true, _main_panel.getMega_master_pass_hash(), _main_panel.getMega_master_pass_salt());
swingReflectionInvokeAndWait("setLocationRelativeTo", dialog, tthis);
swingReflectionInvokeAndWait("setVisible", dialog, true);
if(dialog.isPass_ok()) {
_main_panel.setMega_master_pass(dialog.getPass());
dialog.deletePass();
_remember_master_pass = dialog.getRemember_checkbox().isSelected();
dialog.dispose();
password_aes = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String)account_info.get("password_aes")), _main_panel.getMega_master_pass(), CryptTools.AES_ZERO_IV));
user_hash = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String)account_info.get("user_hash")), _main_panel.getMega_master_pass(), CryptTools.AES_ZERO_IV));
} else {
dialog.dispose();
throw new Exception();
HashMap<String, Object> account_info = (HashMap) _main_panel.getMega_accounts().get(email);
Long[] quota = null;
MegaAPI ma = _main_panel.getMega_active_accounts().get(account_combobox.getSelectedItem());
if (ma == null) {
ma = new MegaAPI();
String password_aes, user_hash;
try {
if (_main_panel.getMega_master_pass_hash() != null) {
if (_main_panel.getMega_master_pass() == null) {
GetMegaMasterPasswordDialog dialog = new GetMegaMasterPasswordDialog((Frame) getParent(), true, _main_panel.getMega_master_pass_hash(), _main_panel.getMega_master_pass_salt());
swingReflectionInvokeAndWait("setLocationRelativeTo", dialog, tthis);
swingReflectionInvokeAndWait("setVisible", dialog, true);
if (dialog.isPass_ok()) {
_main_panel.setMega_master_pass(dialog.getPass());
dialog.deletePass();
_remember_master_pass = dialog.getRemember_checkbox().isSelected();
dialog.dispose();
password_aes = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String) account_info.get("password_aes")), _main_panel.getMega_master_pass(), CryptTools.AES_ZERO_IV));
user_hash = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String) account_info.get("user_hash")), _main_panel.getMega_master_pass(), CryptTools.AES_ZERO_IV));
} else {
dialog.dispose();
throw new Exception();
}
} else {
password_aes = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String) account_info.get("password_aes")), _main_panel.getMega_master_pass(), CryptTools.AES_ZERO_IV));
user_hash = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String) account_info.get("user_hash")), _main_panel.getMega_master_pass(), CryptTools.AES_ZERO_IV));
}
} else {
password_aes = (String) account_info.get("password_aes");
user_hash = (String) account_info.get("user_hash");
}
ma.fastLogin(email, bin2i32a(BASE642Bin(password_aes)), user_hash);
_main_panel.getMega_active_accounts().put(email, ma);
quota = ma.getQuota();
} catch (Exception ex) {
getLogger(FileGrabberDialog.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
password_aes = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String)account_info.get("password_aes")), _main_panel.getMega_master_pass(), CryptTools.AES_ZERO_IV));
user_hash = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String)account_info.get("user_hash")), _main_panel.getMega_master_pass(), CryptTools.AES_ZERO_IV));
quota = ma.getQuota();
}
if (quota != null) {
if (quota[0] <= Math.round((double) quota[1] / 2)) {
swingReflectionInvoke("setForeground", used_space_label, new Color(0, 128, 0));
} else if (quota[0] < quota[1]) {
swingReflectionInvoke("setForeground", used_space_label, new Color(230, 115, 0));
} else {
swingReflectionInvoke("setForeground", used_space_label, Color.red);
}
boolean root_childs = ((TreeNode) ((TreeModel) swingReflectionInvokeAndWaitForReturn("getModel", file_tree)).getRoot()).getChildCount() > 0;
swingReflectionInvoke("setText", used_space_label, formatBytes(quota[0]) + " / " + formatBytes(quota[1]));
swingReflectionInvoke("setEnabled", new Object[]{add_files_button, add_folder_button, account_combobox, account_label}, true);
swingReflectionInvoke("setEnabled", new Object[]{dir_name_textfield, dir_name_label, warning_label, dance_button, file_tree, total_file_size_label, skip_button, skip_rest_button}, root_childs);
} else {
_last_selected_account = null;
swingReflectionInvoke("setEnabled", account_combobox, true);
swingReflectionInvoke("setEnabled", account_label, true);
swingReflectionInvoke("setSelectedIndex", account_combobox, -1);
swingReflectionInvoke("setForeground", used_space_label, Color.red);
swingReflectionInvoke("setText", used_space_label, "ERROR checking account quota!");
}
} else {
password_aes = (String)account_info.get("password_aes");
user_hash = (String)account_info.get("user_hash");
}
ma.fastLogin(email,bin2i32a(BASE642Bin(password_aes)), user_hash);
});
_main_panel.getMega_active_accounts().put(email, ma);
quota = ma.getQuota();
} catch (Exception ex) {
getLogger(FileGrabberDialog.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
quota = ma.getQuota();
}
if(quota != null) {
if(quota[0] <= Math.round((double)quota[1]/2)) {
swingReflectionInvoke("setForeground", used_space_label, new Color(0,128,0));
} else if(quota[0] < quota[1]) {
swingReflectionInvoke("setForeground", used_space_label, new Color(230,115,0));
} else {
swingReflectionInvoke("setForeground", used_space_label, Color.red);
}
boolean root_childs = ((DefaultMutableTreeNode)((DefaultTreeModel)swingReflectionInvokeAndWaitForReturn("getModel", file_tree)).getRoot()).getChildCount()>0;
swingReflectionInvoke("setText", used_space_label, formatBytes(quota[0])+" / "+formatBytes(quota[1]));
swingReflectionInvoke("setEnabled", new Object[]{add_files_button,add_folder_button, account_combobox, account_label}, true);
swingReflectionInvoke("setEnabled", new Object[]{dir_name_textfield, dir_name_label, warning_label, dance_button, file_tree, total_file_size_label, skip_button, skip_rest_button}, root_childs);
} else {
_last_selected_account = null;
swingReflectionInvoke("setEnabled", account_combobox, true);
swingReflectionInvoke("setEnabled", account_label, true);
swingReflectionInvoke("setSelectedIndex", account_combobox, -1);
swingReflectionInvoke("setForeground", used_space_label, Color.red);
swingReflectionInvoke("setText", used_space_label, "ERROR checking account quota!");
}
} });
}
}//GEN-LAST:event_account_comboboxItemStateChanged
private void skip_rest_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_skip_rest_buttonActionPerformed
if( deleteAllExceptSelectedTreeItems(file_tree)) {
if (deleteAllExceptSelectedTreeItems(file_tree)) {
_genFileList();
boolean root_childs = ((DefaultMutableTreeNode)file_tree.getModel().getRoot()).getChildCount()>0;
boolean root_childs = ((TreeNode) file_tree.getModel().getRoot()).getChildCount() > 0;
warning_label.setEnabled(root_childs);
dance_button.setEnabled(root_childs);
total_file_size_label.setEnabled(root_childs);
@ -682,22 +684,22 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
skip_rest_button.setEnabled(root_childs);
dir_name_textfield.setEnabled(root_childs);
dir_name_label.setEnabled(root_childs);
if(!root_childs) {
if (!root_childs) {
dir_name_textfield.setText("");
}
}
}//GEN-LAST:event_skip_rest_buttonActionPerformed
private void skip_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_skip_buttonActionPerformed
if(deleteSelectedTreeItems(file_tree)) {
if (deleteSelectedTreeItems(file_tree)) {
_genFileList();
boolean root_childs = ((DefaultMutableTreeNode)file_tree.getModel().getRoot()).getChildCount()>0;
boolean root_childs = ((TreeNode) file_tree.getModel().getRoot()).getChildCount() > 0;
warning_label.setEnabled(root_childs);
dance_button.setEnabled(root_childs);
@ -706,87 +708,86 @@ public final class FileGrabberDialog extends javax.swing.JDialog {
skip_rest_button.setEnabled(root_childs);
dir_name_textfield.setEnabled(root_childs);
dir_name_label.setEnabled(root_childs);
if(!root_childs) {
if (!root_childs) {
dir_name_textfield.setText("");
}
}
}//GEN-LAST:event_skip_buttonActionPerformed
private void _genFileTree(String directoryName, DefaultMutableTreeNode root) {
File directory = new File(directoryName);
File[] fList = directory.listFiles();
if(fList != null) {
for (File file : fList) {
if (fList != null) {
if (file.isFile()) {
for (File file : fList) {
DefaultMutableTreeNode current_file = new DefaultMutableTreeNode( file.getName() + " ["+formatBytes(file.length())+"]" );
if (file.isFile()) {
root.add(current_file);
DefaultMutableTreeNode current_file = new DefaultMutableTreeNode(file.getName() + " [" + formatBytes(file.length()) + "]");
} else if (file.isDirectory() && file.listFiles().length > 0) {
root.add(current_file);
DefaultMutableTreeNode current_dir = new DefaultMutableTreeNode( file.getName() );
} else if (file.isDirectory() && file.listFiles().length > 0) {
root.add(current_dir);
DefaultMutableTreeNode current_dir = new DefaultMutableTreeNode(file.getName());
_genFileTree(file.getAbsolutePath(), current_dir);
}
root.add(current_dir);
_genFileTree(file.getAbsolutePath(), current_dir);
}
}
}
}
private void _genFileList() {
_files.clear();
_total_space = 0L;
DefaultTreeModel tree_model = (DefaultTreeModel)file_tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree_model.getRoot();
private void _genFileList() {
_files.clear();
_total_space = 0L;
DefaultTreeModel tree_model = (DefaultTreeModel) file_tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree_model.getRoot();
Enumeration files_tree = root.depthFirstEnumeration();
while(files_tree.hasMoreElements()) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)files_tree.nextElement();
if(node.isLeaf() && node!=root) {
while (files_tree.hasMoreElements()) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) files_tree.nextElement();
if (node.isLeaf() && node != root) {
String path = "";
Object[] object_path = node.getUserObjectPath();
for(Object p:object_path) {
path+="/"+p;
for (Object p : object_path) {
path += "/" + p;
}
path = path.replaceAll("^//", "/").trim().replaceAll(" \\[[0-9,]+ [A-Z]+\\]$", "");
File file = new File(path);
if(file.isFile()) {
_total_space+=file.length();
if (file.isFile()) {
_total_space += file.length();
_files.add(file);
}
}
}
total_file_size_label.setText("["+formatBytes(_total_space)+"]");
total_file_size_label.setText("[" + formatBytes(_total_space) + "]");
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> account_combobox;
private javax.swing.JLabel account_label;

View File

@ -11,6 +11,8 @@ import static java.util.logging.Level.SEVERE;
import static java.util.logging.Logger.getLogger;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import static megabasterd.MainPanel.FONT_DEFAULT;
import static megabasterd.MainPanel.THREAD_POOL;
import static megabasterd.MiscTools.deleteAllExceptSelectedTreeItems;
@ -30,13 +32,13 @@ import static megabasterd.MiscTools.updateFont;
public final class FolderLinkDialog extends javax.swing.JDialog {
private String _link;
private boolean _download;
private final List<HashMap> _download_links;
private long _total_space;
private boolean _mega_error;
public List<HashMap> getDownload_links() {
@ -50,17 +52,17 @@ public final class FolderLinkDialog extends javax.swing.JDialog {
public boolean isMega_error() {
return _mega_error;
}
/**
* Creates new form FolderLink
*
* @param parent
* @param link
*/
public FolderLinkDialog(java.awt.Frame parent, boolean modal, String link) {
super(parent, modal);
initComponents();
_mega_error = false;
@ -68,30 +70,31 @@ public final class FolderLinkDialog extends javax.swing.JDialog {
_download = false;
_download_links = new ArrayList<>();
_link = link;
MiscTools.swingInvokeIt(new Runnable(){
MiscTools.swingInvokeIt(new Runnable() {
@Override
public void run() {updateFont(file_tree, FONT_DEFAULT, PLAIN);
updateFont(link_detected_label, FONT_DEFAULT, PLAIN);
updateFont(warning_label, FONT_DEFAULT, PLAIN);
updateFont(skip_button, FONT_DEFAULT, PLAIN);
updateFont(dance_button, FONT_DEFAULT, PLAIN);
updateFont(restore_button, FONT_DEFAULT, PLAIN);
updateFont(skip_rest_button, FONT_DEFAULT, PLAIN);
updateFont(total_space_label, FONT_DEFAULT, BOLD);
updateFont(folder_link_label, FONT_DEFAULT, PLAIN);}}, true);
public void run() {
updateFont(file_tree, FONT_DEFAULT, PLAIN);
updateFont(link_detected_label, FONT_DEFAULT, PLAIN);
updateFont(warning_label, FONT_DEFAULT, PLAIN);
updateFont(skip_button, FONT_DEFAULT, PLAIN);
updateFont(dance_button, FONT_DEFAULT, PLAIN);
updateFont(restore_button, FONT_DEFAULT, PLAIN);
updateFont(skip_rest_button, FONT_DEFAULT, PLAIN);
updateFont(total_space_label, FONT_DEFAULT, BOLD);
updateFont(folder_link_label, FONT_DEFAULT, PLAIN);
}
}, true);
swingReflectionInvoke("setText", folder_link_label, link);
swingReflectionInvoke("setVisible", restore_button, false);
_loadMegaDirTree();
if(!_mega_error) {
if (!_mega_error) {
_genDownloadLiks();
}
}
@ -242,103 +245,102 @@ public final class FolderLinkDialog extends javax.swing.JDialog {
}// </editor-fold>//GEN-END:initComponents
private void skip_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_skip_buttonActionPerformed
if(deleteSelectedTreeItems(file_tree)) {
if (deleteSelectedTreeItems(file_tree)) {
_genDownloadLiks();
restore_button.setVisible(true);
boolean root_childs = ((DefaultMutableTreeNode)file_tree.getModel().getRoot()).getChildCount()>0;
boolean root_childs = ((TreeNode) file_tree.getModel().getRoot()).getChildCount() > 0;
dance_button.setEnabled(root_childs);
skip_button.setEnabled(root_childs);
skip_rest_button.setEnabled(root_childs);
}
}//GEN-LAST:event_skip_buttonActionPerformed
private void dance_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dance_buttonActionPerformed
_download = true;
this.setVisible(false);
}//GEN-LAST:event_dance_buttonActionPerformed
private void skip_rest_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_skip_rest_buttonActionPerformed
if(deleteAllExceptSelectedTreeItems(file_tree)) {
if (deleteAllExceptSelectedTreeItems(file_tree)) {
_genDownloadLiks();
restore_button.setVisible(true);
boolean root_childs = ((DefaultMutableTreeNode)file_tree.getModel().getRoot()).getChildCount()>0;
boolean root_childs = ((TreeNode) file_tree.getModel().getRoot()).getChildCount() > 0;
dance_button.setEnabled(root_childs);
skip_button.setEnabled(root_childs);
skip_rest_button.setEnabled(root_childs);
}
}//GEN-LAST:event_skip_rest_buttonActionPerformed
private void restore_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restore_buttonActionPerformed
restore_button.setText("Restoring data, please wait...");
file_tree.setEnabled(false);
restore_button.setEnabled(false);
dance_button.setEnabled(false);
THREAD_POOL.execute(new Runnable(){
@Override
public void run() {
_loadMegaDirTree();
_genDownloadLiks();
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
swingReflectionInvoke("setVisible", restore_button, false);
swingReflectionInvoke("setText", restore_button, "Restore folder data");
boolean root_childs = ((DefaultMutableTreeNode)((DefaultTreeModel)swingReflectionInvokeAndWaitForReturn("getModel", file_tree)).getRoot()).getChildCount()>0;
_loadMegaDirTree();
_genDownloadLiks();
swingReflectionInvoke("setVisible", restore_button, false);
swingReflectionInvoke("setText", restore_button, "Restore folder data");
boolean root_childs = ((TreeNode) ((TreeModel) swingReflectionInvokeAndWaitForReturn("getModel", file_tree)).getRoot()).getChildCount() > 0;
swingReflectionInvoke("setEnabled", new Object[]{restore_button, dance_button, skip_button, skip_rest_button, file_tree}, root_childs);
}
});
swingReflectionInvoke("setEnabled", new Object[]{restore_button,dance_button, skip_button, skip_rest_button, file_tree}, root_childs);
}});
}//GEN-LAST:event_restore_buttonActionPerformed
private void _loadMegaDirTree() {
try {
HashMap<String,Object> folder_nodes;
HashMap<String, Object> folder_nodes;
MegaAPI ma = new MegaAPI();
String folder_id = findFirstRegex("#F!([^!]+)", _link, 1);
String folder_key = findFirstRegex("#F![^!]+!(.+)", _link, 1);
folder_nodes = ma.getFolderNodes(folder_id, folder_key);
MegaMutableTreeNode root=null;
for(Object o:folder_nodes.values()) {
MegaMutableTreeNode root = null;
HashMap<String,Object> current_hashmap_node = (HashMap<String,Object>)o;
for (Object o : folder_nodes.values()) {
HashMap<String, Object> current_hashmap_node = (HashMap<String, Object>) o;
MegaMutableTreeNode current_node;
if(current_hashmap_node.get("jtree_node") == null) {
if (current_hashmap_node.get("jtree_node") == null) {
current_node = new MegaMutableTreeNode(current_hashmap_node);
@ -346,22 +348,22 @@ public final class FolderLinkDialog extends javax.swing.JDialog {
} else {
current_node = (MegaMutableTreeNode)current_hashmap_node.get("jtree_node");
current_node = (MegaMutableTreeNode) current_hashmap_node.get("jtree_node");
}
String parent_id=(String)current_hashmap_node.get("parent");
String parent_id = (String) current_hashmap_node.get("parent");
root=null;
root = null;
do{
do {
if(folder_nodes.get(parent_id) != null) {
if (folder_nodes.get(parent_id) != null) {
HashMap<String,Object> parent_hashmap_node = (HashMap)folder_nodes.get(parent_id);
HashMap<String, Object> parent_hashmap_node = (HashMap) folder_nodes.get(parent_id);
MegaMutableTreeNode parent_node;
if(parent_hashmap_node.get("jtree_node") == null) {
if (parent_hashmap_node.get("jtree_node") == null) {
parent_node = new MegaMutableTreeNode(parent_hashmap_node);
@ -369,12 +371,12 @@ public final class FolderLinkDialog extends javax.swing.JDialog {
} else {
parent_node = (MegaMutableTreeNode)parent_hashmap_node.get("jtree_node");
parent_node = (MegaMutableTreeNode) parent_hashmap_node.get("jtree_node");
}
parent_node.add(current_node);
parent_id = (String)parent_hashmap_node.get("parent");
parent_id = (String) parent_hashmap_node.get("parent");
current_node = parent_node;
@ -383,57 +385,56 @@ public final class FolderLinkDialog extends javax.swing.JDialog {
root = current_node;
}
}while(current_node != root);
} while (current_node != root);
}
swingReflectionInvokeAndWait("setModel", file_tree, new DefaultTreeModel(sortTree(root)));
swingReflectionInvoke("setRootVisible", file_tree, root!=null?root.getChildCount() > 0:false);
swingReflectionInvoke("setRootVisible", file_tree, root != null ? root.getChildCount() > 0 : false);
swingReflectionInvoke("setEnabled", file_tree, true);
} catch (Exception ex) {
getLogger(FolderLinkDialog.class.getName()).log(SEVERE, null, ex);
_mega_error = true;
}
}
private void _genDownloadLiks(){
String folder_id = findFirstRegex("#F!([^!]+)", _link, 1);
_download_links.clear();
MegaMutableTreeNode root = (MegaMutableTreeNode)((DefaultTreeModel)swingReflectionInvokeAndWaitForReturn("getModel", file_tree)).getRoot();
Enumeration files_tree = root.depthFirstEnumeration();
_total_space = 0L;
while(files_tree.hasMoreElements()) {
MegaMutableTreeNode node = (MegaMutableTreeNode)files_tree.nextElement();
if(node.isLeaf() && node!=root && ((HashMap<String,Object>)node.getUserObject()).get("size") != null) {
String path = "";
Object[] object_path = node.getUserObjectPath();
for(Object p:object_path) {
path+="/"+((Map<String,Object>)p).get("name");
}
path = path.replaceAll("^/+", "").trim();
String url = "https://mega.nz/#N!" + ((Map<String, Object>) node.getUserObject()).get("h") + "!" + ((Map<String, Object>) node.getUserObject()).get("key") + "###n=" + folder_id ;
HashMap<String,Object> download_link = new HashMap<>();
private void _genDownloadLiks() {
String folder_id = findFirstRegex("#F!([^!]+)", _link, 1);
_download_links.clear();
MegaMutableTreeNode root = (MegaMutableTreeNode) ((TreeModel) swingReflectionInvokeAndWaitForReturn("getModel", file_tree)).getRoot();
Enumeration files_tree = root.depthFirstEnumeration();
_total_space = 0L;
while (files_tree.hasMoreElements()) {
MegaMutableTreeNode node = (MegaMutableTreeNode) files_tree.nextElement();
if (node.isLeaf() && node != root && ((HashMap<String, Object>) node.getUserObject()).get("size") != null) {
String path = "";
Object[] object_path = node.getUserObjectPath();
for (Object p : object_path) {
path += "/" + ((Map<String, Object>) p).get("name");
}
path = path.replaceAll("^/+", "").trim();
String url = "https://mega.nz/#N!" + ((Map<String, Object>) node.getUserObject()).get("h") + "!" + ((Map<String, Object>) node.getUserObject()).get("key") + "###n=" + folder_id;
HashMap<String, Object> download_link = new HashMap<>();
download_link.put("url", url);
@ -441,17 +442,17 @@ public final class FolderLinkDialog extends javax.swing.JDialog {
download_link.put("filekey", ((Map<String, Object>) node.getUserObject()).get("key"));
download_link.put("filesize", ((Map<String,Object>)node.getUserObject()).get("size"));
_total_space+=(long)download_link.get("filesize");
download_link.put("filesize", ((Map<String, Object>) node.getUserObject()).get("size"));
_total_space += (long) download_link.get("filesize");
_download_links.add(download_link);
}
}
swingReflectionInvoke("setText", total_space_label, "["+formatBytes(_total_space)+"]");
swingReflectionInvoke("setEnabled", new Object[]{dance_button, warning_label, skip_button,skip_rest_button, total_space_label}, root.getChildCount() > 0);
swingReflectionInvoke("setText", total_space_label, "[" + formatBytes(_total_space) + "]");
swingReflectionInvoke("setEnabled", new Object[]{dance_button, warning_label, skip_button, skip_rest_button, total_space_label}, root.getChildCount() > 0);
}
// Variables declaration - do not modify//GEN-BEGIN:variables

View File

@ -16,7 +16,6 @@ import static megabasterd.MiscTools.HashBin;
import static megabasterd.MiscTools.swingReflectionInvoke;
import static megabasterd.MiscTools.updateFont;
/**
*
* @author tonikelope
@ -24,11 +23,11 @@ import static megabasterd.MiscTools.updateFont;
public class GetMegaMasterPasswordDialog extends javax.swing.JDialog {
private boolean _pass_ok;
private String _current_pass_hash;
private final String _salt;
private byte[] _pass;
public JPasswordField getNew_pass_textfield() {
@ -46,12 +45,12 @@ public class GetMegaMasterPasswordDialog extends javax.swing.JDialog {
public byte[] getPass() {
return _pass;
}
public void deletePass() {
if(_pass != null) {
Arrays.fill(_pass, (byte)0);
if (_pass != null) {
Arrays.fill(_pass, (byte) 0);
}
_pass = null;
@ -63,23 +62,25 @@ public class GetMegaMasterPasswordDialog extends javax.swing.JDialog {
public GetMegaMasterPasswordDialog(java.awt.Frame parent, boolean modal, String current_pass_hash, String salt) {
super(parent, modal);
initComponents();
MiscTools.swingInvokeIt(new Runnable(){
MiscTools.swingInvokeIt(new Runnable() {
@Override
public void run() { updateFont(ok_button, FONT_DEFAULT, Font.PLAIN);
updateFont(cancel_button, FONT_DEFAULT, Font.PLAIN);
updateFont(please_label, FONT_DEFAULT, Font.PLAIN);
updateFont(status_label, FONT_DEFAULT, Font.PLAIN);
updateFont(remember_checkbox, FONT_DEFAULT, Font.PLAIN);}}, true);
public void run() {
updateFont(ok_button, FONT_DEFAULT, Font.PLAIN);
updateFont(cancel_button, FONT_DEFAULT, Font.PLAIN);
updateFont(please_label, FONT_DEFAULT, Font.PLAIN);
updateFont(status_label, FONT_DEFAULT, Font.PLAIN);
updateFont(remember_checkbox, FONT_DEFAULT, Font.PLAIN);
}
}, true);
_current_pass_hash = current_pass_hash;
_pass_ok = false;
_pass = null;
_salt = salt;
}
@ -198,56 +199,57 @@ public class GetMegaMasterPasswordDialog extends javax.swing.JDialog {
}//GEN-LAST:event_cancel_buttonActionPerformed
private void ok_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ok_buttonActionPerformed
status_label.setText("Verifying your password, please wait...");
final Dialog tthis = this;
THREAD_POOL.execute(new Runnable(){
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {try {
byte[] pass = CryptTools.PBKDF2HMACSHA256(new String(current_pass_textfield.getPassword()), MiscTools.BASE642Bin(_salt), CryptTools.PBKDF2_ITERATIONS);
public void run() {
try {
byte[] pass = CryptTools.PBKDF2HMACSHA256(new String(current_pass_textfield.getPassword()), MiscTools.BASE642Bin(_salt), CryptTools.PBKDF2_ITERATIONS);
String pass_hash = Bin2BASE64(HashBin("SHA-1", pass));
String pass_hash = Bin2BASE64(HashBin("SHA-1", pass));
if(!pass_hash.equals(_current_pass_hash)) {
if (!pass_hash.equals(_current_pass_hash)) {
JOptionPane.showMessageDialog(tthis, "BAD PASSWORD!", "Error", JOptionPane.ERROR_MESSAGE);
swingReflectionInvoke("setText", status_label, "");
swingReflectionInvoke("setText", current_pass_textfield, "");
swingReflectionInvoke("grabFocus", current_pass_textfield);
JOptionPane.showMessageDialog(tthis, "BAD PASSWORD!", "Error", JOptionPane.ERROR_MESSAGE);
} else {
_pass = pass;
_current_pass_hash = pass_hash;
_pass_ok = true;
swingReflectionInvoke("setVisible", tthis, false);
swingReflectionInvoke("setText", status_label, "");
swingReflectionInvoke("setText", current_pass_textfield, "");
swingReflectionInvoke("grabFocus", current_pass_textfield);
} else {
_pass = pass;
_current_pass_hash = pass_hash;
_pass_ok = true;
swingReflectionInvoke("setVisible", tthis, false);
}
} catch (Exception ex) {
Logger.getLogger(GetMegaMasterPasswordDialog.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (Exception ex) {
Logger.getLogger(GetMegaMasterPasswordDialog.class.getName()).log(Level.SEVERE, null, ex);
}}});
}
});
}//GEN-LAST:event_ok_buttonActionPerformed
private void current_pass_textfieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_current_pass_textfieldKeyPressed
if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
ok_buttonActionPerformed(null);
}
}//GEN-LAST:event_current_pass_textfieldKeyPressed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancel_button;
private javax.swing.JPasswordField current_pass_textfield;

View File

@ -7,39 +7,35 @@ import javax.swing.JLabel;
import static megabasterd.MiscTools.formatBytes;
import static megabasterd.MiscTools.swingReflectionInvoke;
public final class GlobalSpeedMeter implements Runnable, SecureNotifiable
{
public final class GlobalSpeedMeter implements Runnable, SecureNotifiable {
private final JLabel _speed_label;
private final ConcurrentLinkedQueue<SpeedMeter> _speedmeters;
private final Object _secure_notify_lock;
private boolean _notified;
GlobalSpeedMeter(JLabel sp_label)
{
GlobalSpeedMeter(JLabel sp_label) {
_notified = false;
_secure_notify_lock = new Object();
_speed_label = sp_label;
_speedmeters = new ConcurrentLinkedQueue<>();
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -47,68 +43,62 @@ public final class GlobalSpeedMeter implements Runnable, SecureNotifiable
getLogger(GlobalSpeedMeter.class.getName()).log(Level.SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
public void attachSpeedMeter(SpeedMeter speed) {
_speedmeters.add(speed);
}
public void detachSpeedMeter(SpeedMeter speed) {
_speedmeters.remove(speed);
}
private long calcSpeed() {
long sp = 0;
for(SpeedMeter speed:_speedmeters)
{
sp+=speed.getLastSpeed();
for (SpeedMeter speed : _speedmeters) {
sp += speed.getLastSpeed();
}
return sp;
}
@Override
public void run()
{
public void run() {
long sp;
swingReflectionInvoke("setText", _speed_label, "------");
swingReflectionInvoke("setVisible", _speed_label, true);
while(true)
{
while (true) {
secureWait();
sp = calcSpeed();
if(sp > 0) {
if (sp > 0) {
swingReflectionInvoke("setText", _speed_label, formatBytes(sp)+"/s");
swingReflectionInvoke("setText", _speed_label, formatBytes(sp) + "/s");
}
else
{
} else {
swingReflectionInvoke("setText", _speed_label, "------");
}
}
}
}

View File

@ -32,28 +32,27 @@ import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
public final class KissVideoStreamServer implements HttpHandler, SecureNotifiable {
public static final int WORKER_STATUS_FILE_INFO=0x01;
public static final int WORKER_STATUS_CONNECT=0x02;
public static final int WORKER_STATUS_STREAM=0x03;
public static final int WORKER_STATUS_RETRY=0x04;
public static final int WORKER_STATUS_EXIT=0x05;
public static final int WORKER_STATUS_FILE_INFO = 0x01;
public static final int WORKER_STATUS_CONNECT = 0x02;
public static final int WORKER_STATUS_STREAM = 0x03;
public static final int WORKER_STATUS_RETRY = 0x04;
public static final int WORKER_STATUS_EXIT = 0x05;
private final MainPanel _main_panel;
private final ConcurrentHashMap<String, String[]> _link_cache;
private final ConcurrentHashMap<Thread, Integer> _working_threads;
private final ContentType _ctype;
private boolean _notified;
private final Object _secure_notify_lock;
public KissVideoStreamServer(MainPanel panel) {
_main_panel = panel;
_link_cache = new ConcurrentHashMap();
_working_threads = new ConcurrentHashMap();
_ctype = new ContentType();
_notified=false;
_notified = false;
_secure_notify_lock = new Object();
}
@ -72,24 +71,22 @@ public final class KissVideoStreamServer implements HttpHandler, SecureNotifiabl
public ContentType getCtype() {
return _ctype;
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -97,203 +94,131 @@ public final class KissVideoStreamServer implements HttpHandler, SecureNotifiabl
getLogger(Download.class.getName()).log(SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
public void start(int port, String context) throws IOException
{
swingReflectionInvoke("setForeground", _main_panel.getView().getKiss_server_status(), new Color(0,128,0));
swingReflectionInvoke("setText", _main_panel.getView().getKiss_server_status(), "Kissvideostreamer on localhost:"+STREAMER_PORT+" (Waiting for request...)");
public void start(int port, String context) throws IOException {
swingReflectionInvoke("setForeground", _main_panel.getView().getKiss_server_status(), new Color(0, 128, 0));
swingReflectionInvoke("setText", _main_panel.getView().getKiss_server_status(), "Kissvideostreamer on localhost:" + STREAMER_PORT + " (Waiting for request...)");
HttpServer httpserver = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), port), 0);
httpserver.createContext(context, this);
httpserver.setExecutor(THREAD_POOL);
httpserver.start();
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
while(true) {
while (true) {
secureWait();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(KissVideoStreamServer.class.getName()).log(Level.SEVERE, null, ex);
}
if(_working_threads.isEmpty()) {
swingReflectionInvoke("setText", _main_panel.getView().getKiss_server_status(), "Kissvideostreamer on localhost:"+STREAMER_PORT+" (Waiting for request...)");
if (_working_threads.isEmpty()) {
swingReflectionInvoke("setText", _main_panel.getView().getKiss_server_status(), "Kissvideostreamer on localhost:" + STREAMER_PORT + " (Waiting for request...)");
swingReflectionInvoke("setExtendedState", _main_panel.getView(), NORMAL);
swingReflectionInvoke("setVisible", _main_panel.getView(), true);
}
}
}
});
}
private void updateStatus(Integer new_status) {
if(new_status != WORKER_STATUS_EXIT) {
if (new_status != WORKER_STATUS_EXIT) {
getWorking_threads().put(Thread.currentThread(), new_status);
} else {
getWorking_threads().remove(Thread.currentThread());
}
int conta_info=0, conta_connect=0, conta_stream=0, conta_retry=0;
for(Integer thread_status:getWorking_threads().values()) {
switch(thread_status) {
int conta_info = 0, conta_connect = 0, conta_stream = 0, conta_retry = 0;
for (Integer thread_status : getWorking_threads().values()) {
switch (thread_status) {
case WORKER_STATUS_FILE_INFO:
conta_info++;
break;
case WORKER_STATUS_CONNECT:
conta_connect++;
break;
case WORKER_STATUS_STREAM:
case WORKER_STATUS_STREAM:
conta_stream++;
break;
case WORKER_STATUS_RETRY:
case WORKER_STATUS_RETRY:
conta_retry++;
break;
}
}
String status="Kissvideostreamer on localhost:"+STREAMER_PORT+" Info: "+conta_info+" / Conn: "+conta_connect+" / Stream: "+conta_stream+" / Retry: "+conta_retry;
String status = "Kissvideostreamer on localhost:" + STREAMER_PORT + " Info: " + conta_info + " / Conn: " + conta_connect + " / Stream: " + conta_stream + " / Retry: " + conta_retry;
swingReflectionInvoke("setText", _main_panel.getView().getKiss_server_status(), status);
}
private String[] getMegaFileMetadata(String link, MainPanelView panel) throws IOException, InterruptedException
{
String[] file_info=null;
int retry=0;
private String[] getMegaFileMetadata(String link, MainPanelView panel) throws IOException, InterruptedException {
String[] file_info = null;
int retry = 0;
boolean error;
do
{
do {
updateStatus(WORKER_STATUS_FILE_INFO);
error=false;
try
{
if( findFirstRegex("://mega(\\.co)?\\.nz/", link, 0) != null)
{
error = false;
try {
if (findFirstRegex("://mega(\\.co)?\\.nz/", link, 0) != null) {
MegaAPI ma = new MegaAPI();
file_info = ma.getMegaFileMetadata(link);
}
else
{
file_info = MegaCrypterAPI.getMegaFileMetadata(link, panel);
}
} else {
file_info = MegaCrypterAPI.getMegaFileMetadata(link, panel);
}
}
catch(MegaAPIException | MegaCrypterAPIException e)
{
error=true;
} catch (MegaAPIException | MegaCrypterAPIException e) {
error = true;
switch(Integer.parseInt(e.getMessage()))
{
switch (Integer.parseInt(e.getMessage())) {
case -2:
throw new IOException("Mega link is not valid!");
case -14:
throw new IOException("Mega link is not valid!");
case 22:
throw new IOException("MegaCrypter link is not valid!");
case 23:
throw new IOException("MegaCrypter link is blocked!");
case 24:
throw new IOException("MegaCrypter link has expired!");
default:
updateStatus(WORKER_STATUS_RETRY);
for(long i=getWaitTimeExpBackOff(retry++); i>0; i--)
{
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
}
} catch(Exception ex) {
}
}while(error);
return file_info;
}
private String getMegaFileDownloadUrl(String link, String pass_hash, String noexpire_token) throws IOException, InterruptedException
{
String dl_url=null;
int retry=0;
boolean error;
do
{
updateStatus(WORKER_STATUS_FILE_INFO);
error=false;
try
{
if( findFirstRegex("://mega(\\.co)?\\.nz/", link, 0) != null)
{
MegaAPI ma = new MegaAPI();
dl_url = ma.getMegaFileDownloadUrl(link);
}
else
{
dl_url = MegaCrypterAPI.getMegaFileDownloadUrl(link,pass_hash,noexpire_token);
}
}
catch(MegaAPIException | MegaCrypterAPIException e)
{
error=true;
switch(Integer.parseInt(e.getMessage()))
{
case 22:
throw new IOException("MegaCrypter link is not valid!");
@ -302,276 +227,313 @@ public final class KissVideoStreamServer implements HttpHandler, SecureNotifiabl
case 24:
throw new IOException("MegaCrypter link has expired!");
default:
updateStatus(WORKER_STATUS_RETRY);
for(long i=getWaitTimeExpBackOff(retry++); i>0; i--)
{
for (long i = getWaitTimeExpBackOff(retry++); i > 0; i--) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
} catch (InterruptedException ex) {
}
}
}
} catch (Exception ex) {
}
} while (error);
return file_info;
}
private String getMegaFileDownloadUrl(String link, String pass_hash, String noexpire_token) throws IOException, InterruptedException {
String dl_url = null;
int retry = 0;
boolean error;
do {
updateStatus(WORKER_STATUS_FILE_INFO);
error = false;
try {
if (findFirstRegex("://mega(\\.co)?\\.nz/", link, 0) != null) {
MegaAPI ma = new MegaAPI();
dl_url = ma.getMegaFileDownloadUrl(link);
} else {
dl_url = MegaCrypterAPI.getMegaFileDownloadUrl(link, pass_hash, noexpire_token);
}
} catch (MegaAPIException | MegaCrypterAPIException e) {
error = true;
switch (Integer.parseInt(e.getMessage())) {
case 22:
throw new IOException("MegaCrypter link is not valid!");
case 23:
throw new IOException("MegaCrypter link is blocked!");
case 24:
throw new IOException("MegaCrypter link has expired!");
default:
updateStatus(WORKER_STATUS_RETRY);
for (long i = getWaitTimeExpBackOff(retry++); i > 0; i--) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
}while(error);
} while (error);
return dl_url;
}
private long[] parseRangeHeader(String header)
{
private long[] parseRangeHeader(String header) {
Pattern pattern = Pattern.compile("bytes\\=([0-9]+)\\-([0-9]+)?");
Matcher matcher = pattern.matcher(header);
long[] ranges=new long[2];
if(matcher.find())
{
long[] ranges = new long[2];
if (matcher.find()) {
ranges[0] = Long.valueOf(matcher.group(1));
if(matcher.group(2)!=null) {
if (matcher.group(2) != null) {
ranges[1] = Long.valueOf(matcher.group(2));
} else
{
ranges[1]=-1;
} else {
ranges[1] = -1;
}
}
return ranges;
}
private String cookRangeUrl(String url, long[] ranges, int sync_bytes)
{
return url+"/"+String.valueOf(ranges[0]-sync_bytes)+(ranges[1]>=0?"-"+String.valueOf(ranges[1]):"");
}
@Override
public void handle(HttpExchange xchg) throws IOException {
long clength;
OutputStream os;
CipherInputStream cis = null;
String httpmethod = xchg.getRequestMethod();
HttpGet httpget;
try(CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient()){
Headers reqheaders=xchg.getRequestHeaders();
private String cookRangeUrl(String url, long[] ranges, int sync_bytes) {
return url + "/" + String.valueOf(ranges[0] - sync_bytes) + (ranges[1] >= 0 ? "-" + String.valueOf(ranges[1]) : "");
}
@Override
public void handle(HttpExchange xchg) throws IOException {
long clength;
OutputStream os;
CipherInputStream cis = null;
String httpmethod = xchg.getRequestMethod();
HttpGet httpget;
try (CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient()) {
Headers reqheaders = xchg.getRequestHeaders();
Headers resheaders = xchg.getResponseHeaders();
String url_path = xchg.getRequestURI().getPath();
String link = url_path.substring(url_path.indexOf("/video/")+7);
if(link.indexOf("mega/") == 0)
{
String link = url_path.substring(url_path.indexOf("/video/") + 7);
if (link.indexOf("mega/") == 0) {
link = link.replaceAll("mega/", "https://mega.co.nz/#");
}
else
{
} else {
String mc_host = findFirstRegex("^[^/]+/", link, 0);
link = "http://" + mc_host + link;
}
String[] cache_info, file_info;
cache_info = getLink_cache().get(link);
if(cache_info!=null) {
if (cache_info != null) {
file_info = new String[6];
System.arraycopy( cache_info, 0, file_info, 0, cache_info.length );
System.arraycopy(cache_info, 0, file_info, 0, cache_info.length);
} else {
file_info = getMegaFileMetadata(link, _main_panel.getView());
cache_info = new String[6];
System.arraycopy( file_info, 0, cache_info, 0, file_info.length );
System.arraycopy(file_info, 0, cache_info, 0, file_info.length);
cache_info[5]=null;
cache_info[5] = null;
}
String file_name = file_info[0];
long file_size = Long.parseLong(file_info[1]);
String file_name = file_info[0];
String file_key = file_info[2];
String pass_hash, noexpire_token;
long file_size = Long.parseLong(file_info[1]);
if(file_info.length >= 5)
{
pass_hash = file_info[3];
String file_key = file_info[2];
noexpire_token = file_info[4];
String pass_hash, noexpire_token;
} else {
pass_hash = null;
if (file_info.length >= 5) {
pass_hash = file_info[3];
noexpire_token = null;
}
String file_ext = file_name.substring(file_name.lastIndexOf('.')+1).toLowerCase();
noexpire_token = file_info[4];
} else {
pass_hash = null;
noexpire_token = null;
}
String file_ext = file_name.substring(file_name.lastIndexOf('.') + 1).toLowerCase();
if (httpmethod.equals("HEAD")) {
if(httpmethod.equals("HEAD")) {
resheaders.add("Accept-Ranges", "bytes");
resheaders.add("transferMode.dlna.org", "Streaming");
resheaders.add("contentFeatures.dlna.org", "DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000");
resheaders.add("Content-Type", getCtype().getMIME(file_ext));
resheaders.add("Content-Length", String.valueOf(file_size));
resheaders.add("Connection", "close");
xchg.sendResponseHeaders(HttpStatus.SC_OK, 0);
} else if(httpmethod.equals("GET")) {
resheaders.add("Accept-Ranges", "bytes");
resheaders.add("transferMode.dlna.org", "Streaming");
} else if (httpmethod.equals("GET")) {
resheaders.add("contentFeatures.dlna.org", "DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000");
resheaders.add("Accept-Ranges", "bytes");
resheaders.add("Content-Type", getCtype().getMIME(file_ext));
resheaders.add("transferMode.dlna.org", "Streaming");
resheaders.add("Connection", "close");
byte[] buffer = new byte[16*1024];
int reads;
String temp_url;
resheaders.add("contentFeatures.dlna.org", "DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000");
if(cache_info[5]!=null) {
resheaders.add("Content-Type", getCtype().getMIME(file_ext));
temp_url = cache_info[5];
resheaders.add("Connection", "close");
if(!checkMegaDownloadUrl(temp_url)) {
byte[] buffer = new byte[16 * 1024];
temp_url = getMegaFileDownloadUrl(link,pass_hash,noexpire_token);
int reads;
cache_info[5] = temp_url;
String temp_url;
getLink_cache().put(link, file_info);
}
if (cache_info[5] != null) {
} else {
temp_url = getMegaFileDownloadUrl(link,pass_hash,noexpire_token);
temp_url = cache_info[5];
if (!checkMegaDownloadUrl(temp_url)) {
temp_url = getMegaFileDownloadUrl(link, pass_hash, noexpire_token);
cache_info[5] = temp_url;
getLink_cache().put(link, cache_info);
getLink_cache().put(link, file_info);
}
long[] ranges=new long[2];
int sync_bytes=0;
} else {
temp_url = getMegaFileDownloadUrl(link, pass_hash, noexpire_token);
String header_range=null;
cache_info[5] = temp_url;
InputStream is;
getLink_cache().put(link, cache_info);
}
URL url;
long[] ranges = new long[2];
if(reqheaders.containsKey("Range"))
{
header_range = "Range";
int sync_bytes = 0;
} else if(reqheaders.containsKey("range")) {
String header_range = null;
header_range = "range";
}
if(header_range != null)
{
List<String> ranges_raw = reqheaders.get(header_range);
InputStream is;
String range_header=ranges_raw.get(0);
URL url;
ranges = parseRangeHeader(range_header);
if (reqheaders.containsKey("Range")) {
header_range = "Range";
sync_bytes = (int)ranges[0] % 16;
} else if (reqheaders.containsKey("range")) {
if(ranges[1]>=0 && ranges[1]>=ranges[0]) {
header_range = "range";
}
clength = ranges[1]-ranges[0]+1;
if (header_range != null) {
List<String> ranges_raw = reqheaders.get(header_range);
} else {
String range_header = ranges_raw.get(0);
clength = file_size - ranges[0];
}
ranges = parseRangeHeader(range_header);
resheaders.add("Content-Range", "bytes "+ranges[0]+"-"+(ranges[1]>=0?ranges[1]:(file_size-1))+"/"+file_size);
sync_bytes = (int) ranges[0] % 16;
xchg.sendResponseHeaders(HttpStatus.SC_PARTIAL_CONTENT, clength);
if (ranges[1] >= 0 && ranges[1] >= ranges[0]) {
url = new URL(cookRangeUrl(temp_url, ranges, sync_bytes));
clength = ranges[1] - ranges[0] + 1;
} else {
xchg.sendResponseHeaders(HttpStatus.SC_OK, file_size);
url = new URL(temp_url);
clength = file_size - ranges[0];
}
updateStatus(WORKER_STATUS_CONNECT);
httpget = new HttpGet(url.toURI());
httpget.addHeader("Connection", "close");
try(CloseableHttpResponse httpresponse = httpclient.execute(httpget)) {
is = httpresponse.getEntity().getContent();
resheaders.add("Content-Range", "bytes " + ranges[0] + "-" + (ranges[1] >= 0 ? ranges[1] : (file_size - 1)) + "/" + file_size);
byte[] iv = CryptTools.initMEGALinkKeyIV(file_key);
xchg.sendResponseHeaders(HttpStatus.SC_PARTIAL_CONTENT, clength);
cis = new CipherInputStream(is, CryptTools.genDecrypter("AES", "AES/CTR/NoPadding", CryptTools.initMEGALinkKey(file_key), (header_range!=null && (ranges[0]-sync_bytes)>0)?CryptTools.forwardMEGALinkKeyIV(iv, ranges[0]-sync_bytes):iv));
url = new URL(cookRangeUrl(temp_url, ranges, sync_bytes));
os = xchg.getResponseBody();
} else {
cis.skip(sync_bytes);
xchg.sendResponseHeaders(HttpStatus.SC_OK, file_size);
updateStatus(WORKER_STATUS_STREAM);
url = new URL(temp_url);
}
while((reads=cis.read(buffer))!=-1) {
updateStatus(WORKER_STATUS_CONNECT);
os.write(buffer, 0, reads);
}
httpget = new HttpGet(url.toURI());
httpget.addHeader("Connection", "close");
try (CloseableHttpResponse httpresponse = httpclient.execute(httpget)) {
is = httpresponse.getEntity().getContent();
byte[] iv = CryptTools.initMEGALinkKeyIV(file_key);
cis = new CipherInputStream(is, CryptTools.genDecrypter("AES", "AES/CTR/NoPadding", CryptTools.initMEGALinkKey(file_key), (header_range != null && (ranges[0] - sync_bytes) > 0) ? CryptTools.forwardMEGALinkKeyIV(iv, ranges[0] - sync_bytes) : iv));
os = xchg.getResponseBody();
cis.skip(sync_bytes);
updateStatus(WORKER_STATUS_STREAM);
while ((reads = cis.read(buffer)) != -1) {
os.write(buffer, 0, reads);
}
}
}
}
catch(Exception ex){ }
finally
{
} catch (Exception ex) {
} finally {
xchg.close();
updateStatus(WORKER_STATUS_EXIT);
secureNotify();
}
}
}
}

View File

@ -11,7 +11,6 @@ import static megabasterd.MiscTools.swingReflectionInvoke;
import static megabasterd.MiscTools.truncateText;
import static megabasterd.MiscTools.updateFont;
public final class LinkGrabberDialog extends javax.swing.JDialog implements ClipboardChangeObserver {
private boolean _download;
@ -29,36 +28,35 @@ public final class LinkGrabberDialog extends javax.swing.JDialog implements Clip
public JTextArea getLinks_textarea() {
return links_textarea;
}
public LinkGrabberDialog(java.awt.Frame parent, boolean modal, String download_path, ClipboardSpy clipboardspy) {
super(parent, modal);
_download = false;
initComponents();
MiscTools.swingInvokeIt(new Runnable(){
MiscTools.swingInvokeIt(new Runnable() {
@Override
public void run() {updateFont(links_label, FONT_DEFAULT, Font.PLAIN);
updateFont(dance_button, FONT_DEFAULT, Font.PLAIN);
updateFont(down_dir_to_label, FONT_DEFAULT, Font.PLAIN);
updateFont(change_dir_button, FONT_DEFAULT, Font.PLAIN);
updateFont(download_dir_label, FONT_DEFAULT, Font.PLAIN);}}, true);
public void run() {
updateFont(links_label, FONT_DEFAULT, Font.PLAIN);
updateFont(dance_button, FONT_DEFAULT, Font.PLAIN);
updateFont(down_dir_to_label, FONT_DEFAULT, Font.PLAIN);
updateFont(change_dir_button, FONT_DEFAULT, Font.PLAIN);
updateFont(download_dir_label, FONT_DEFAULT, Font.PLAIN);
}
}, true);
_download_path = download_path;
_clipboardpy = clipboardspy;
swingReflectionInvoke("setText", download_dir_label, truncateText(download_path,80));
swingReflectionInvoke("setText", download_dir_label, truncateText(download_path, 80));
notifyClipboardChange();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
@ -162,14 +160,14 @@ public final class LinkGrabberDialog extends javax.swing.JDialog implements Clip
}// </editor-fold>//GEN-END:initComponents
private void dance_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dance_buttonActionPerformed
_download=true;
_download = true;
this.setVisible(false);
}//GEN-LAST:event_dance_buttonActionPerformed
private void change_dir_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_change_dir_buttonActionPerformed
javax.swing.JFileChooser filechooser = new javax.swing.JFileChooser();
filechooser.setCurrentDirectory(new java.io.File(_download_path));
@ -177,17 +175,16 @@ public final class LinkGrabberDialog extends javax.swing.JDialog implements Clip
filechooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
filechooser.setAcceptAllFileFilterUsed(false);
if( filechooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ) {
if (filechooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = filechooser.getSelectedFile();
_download_path = file.getAbsolutePath();
download_dir_label.setText(truncateText(_download_path,80));
download_dir_label.setText(truncateText(_download_path, 80));
}
}//GEN-LAST:event_change_dir_buttonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton change_dir_button;
private javax.swing.JButton dance_button;
@ -200,7 +197,7 @@ public final class LinkGrabberDialog extends javax.swing.JDialog implements Clip
@Override
public void notifyClipboardChange() {
swingReflectionInvoke("setText", links_textarea,extractMegaLinksFromString(extractStringFromClipboardContents(_clipboardpy.getContents())));
swingReflectionInvoke("setText", links_textarea, extractMegaLinksFromString(extractStringFromClipboardContents(_clipboardpy.getContents())));
}
}

View File

@ -52,28 +52,27 @@ import static megabasterd.MiscTools.swingReflectionInvokeAndWaitForReturn;
import static megabasterd.Transference.LIMIT_TRANSFERENCE_SPEED_DEFAULT;
import static megabasterd.Transference.MAX_TRANSFERENCE_SPEED_DEFAULT;
/**
/**
*
* @author tonikelope
*/
public final class MainPanel {
public static final String VERSION="1.41";
public static final int THROTTLE_SLICE_SIZE=16*1024;
public static final String VERSION = "1.42";
public static final int THROTTLE_SLICE_SIZE = 16 * 1024;
public static final int STREAMER_PORT = 1337;
public static final int WATCHDOG_PORT = 1338;
public static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0";
public static final String ICON_FILE = "mbasterd_mini.png";
public static final ExecutorService THREAD_POOL = newCachedThreadPool();
public static final Font FONT_DEFAULT = createAndRegisterFont("Gochi.ttf");
public static void main(String args[]) {
setNimbusLookAndFeel();
final MainPanel main_panel = new MainPanel();
invokeLater(new Runnable() {
@Override
public void run() {
@ -82,7 +81,7 @@ public final class MainPanel {
});
}
private volatile MainPanelView _view=null; //lazy init
private volatile MainPanelView _view = null; //lazy init
private final GlobalSpeedMeter _global_dl_speed, _global_up_speed;
private final DownloadManager _download_manager;
private final UploadManager _upload_manager;
@ -98,81 +97,82 @@ public final class MainPanel {
private byte[] _mega_master_pass;
private String _mega_master_pass_hash;
private String _mega_master_pass_salt;
public MainPanel() {
if(checkAppIsRunning()) {
if (checkAppIsRunning()) {
System.exit(0);
}
try {
trayIcon();
} catch (AWTException ex) {
getLogger(MainPanelView.class.getName()).log(SEVERE, null, ex);
}
try {
setupSqliteTables();
} catch (SQLException ex) {
getLogger(MainPanel.class.getName()).log(SEVERE, null, ex);
}
loadUserSettings();
_mega_master_pass = null;
_mega_active_accounts = new HashMap<>();
THREAD_POOL.execute((_global_dl_speed = new GlobalSpeedMeter(getView().getGlobal_speed_down_label())));
THREAD_POOL.execute((_global_up_speed = new GlobalSpeedMeter(getView().getGlobal_speed_up_label())));
THREAD_POOL.execute((_download_manager = new DownloadManager(this)));
THREAD_POOL.execute((_upload_manager = new UploadManager(this)));
THREAD_POOL.execute((_stream_supervisor = new StreamThrottlerSupervisor(_limit_download_speed?_max_dl_speed*1024:0, _limit_upload_speed?_max_up_speed*1024:0, THROTTLE_SLICE_SIZE)));
THREAD_POOL.execute((_stream_supervisor = new StreamThrottlerSupervisor(_limit_download_speed ? _max_dl_speed * 1024 : 0, _limit_upload_speed ? _max_up_speed * 1024 : 0, THROTTLE_SLICE_SIZE)));
THREAD_POOL.execute((_clipboardspy = new ClipboardSpy()));
swingReflectionInvoke("setForeground", getView().getGlobal_speed_down_label(), _limit_download_speed?new Color(255,0,0):new Color(0,128,255));
swingReflectionInvoke("setForeground", getView().getGlobal_speed_up_label(), _limit_upload_speed?new Color(255,0,0):new Color(0,128,255));
swingReflectionInvoke("setForeground", getView().getGlobal_speed_down_label(), _limit_download_speed ? new Color(255, 0, 0) : new Color(0, 128, 255));
swingReflectionInvoke("setForeground", getView().getGlobal_speed_up_label(), _limit_upload_speed ? new Color(255, 0, 0) : new Color(0, 128, 255));
resumeDownloads();
resumeUploads();
_streamserver = new KissVideoStreamServer(this);
try {
_streamserver.start(STREAMER_PORT, "/video");
} catch (IOException ex) {
getLogger(MainPanel.class.getName()).log(SEVERE, null, ex);
}
THREAD_POOL.execute(new Runnable(){
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
String new_version = MiscTools.checkNewVersion("lYsRWaQB", "uVhntmyKcVECRaOxAbcL4A");
if(new_version != null) {
JOptionPane.showMessageDialog(getView(), "MegaBasterd NEW VERSION ("+new_version+") is available!\n\n(HELP > ABOUT for more info)");
if (new_version != null) {
JOptionPane.showMessageDialog(getView(), "MegaBasterd NEW VERSION (" + new_version + ") is available!\n\n(HELP > ABOUT for more info)");
}
}});
}
});
}
public TrayIcon getTrayicon() {
return _trayicon;
}
public String getMega_master_pass_hash() {
return _mega_master_pass_hash;
}
@ -185,46 +185,45 @@ public final class MainPanel {
return _mega_master_pass_salt;
}
public byte[] getMega_master_pass() {
return _mega_master_pass;
}
public void setMega_master_pass(byte[] pass) {
if(_mega_master_pass != null) {
Arrays.fill(_mega_master_pass, (byte)0);
if (_mega_master_pass != null) {
Arrays.fill(_mega_master_pass, (byte) 0);
_mega_master_pass = null;
}
if(pass != null) {
if (pass != null) {
_mega_master_pass = new byte[pass.length];
System.arraycopy(pass, 0, _mega_master_pass, 0, pass.length);
}
}
public MainPanelView getView() {
MainPanelView result = _view;
if (result == null) {
synchronized(this) {
synchronized (this) {
result = _view;
if (result == null) {
_view = result = new MainPanelView(this);
}
}
}
return result;
}
@ -279,7 +278,7 @@ public final class MainPanel {
public HashMap<String, MegaAPI> getMega_active_accounts() {
return _mega_active_accounts;
}
public TrayIcon getIcon() {
return _trayicon;
}
@ -312,36 +311,34 @@ public final class MainPanel {
return _limit_upload_speed;
}
public void loadUserSettings()
{
public void loadUserSettings() {
String def_slots = selectSettingValueFromDB("default_slots_down");
if(def_slots != null) {
if (def_slots != null) {
_default_slots_down = parseInt(def_slots);
} else {
_default_slots_down = Download.WORKERS_DEFAULT;
}
def_slots = selectSettingValueFromDB("default_slots_up");
if(def_slots != null) {
if (def_slots != null) {
_default_slots_up = parseInt(def_slots);
} else {
_default_slots_up = Upload.WORKERS_DEFAULT;
}
String use_slots = selectSettingValueFromDB("use_slots_down");
if(use_slots != null) {
if (use_slots != null) {
_use_slots_down = use_slots.equals("yes");
} else {
_use_slots_down = Download.USE_SLOTS_DEFAULT;
}
use_slots = selectSettingValueFromDB("use_slots_up");
if(use_slots != null) {
if (use_slots != null) {
_use_slots_up = use_slots.equals("yes");
} else {
_use_slots_up = Upload.USE_SLOTS_DEFAULT;
@ -349,242 +346,241 @@ public final class MainPanel {
String max_downloads = selectSettingValueFromDB("max_downloads");
if(max_downloads != null) {
if (max_downloads != null) {
_max_dl = parseInt(max_downloads);
} else {
_max_dl=Download.SIM_TRANSFERENCES_DEFAULT;
_max_dl = Download.SIM_TRANSFERENCES_DEFAULT;
}
String max_uploads = selectSettingValueFromDB("max_uploads");
if(max_uploads != null) {
if (max_uploads != null) {
_max_ul = parseInt(max_uploads);
} else {
_max_ul=Upload.SIM_TRANSFERENCES_DEFAULT;
_max_ul = Upload.SIM_TRANSFERENCES_DEFAULT;
}
_default_download_path = selectSettingValueFromDB("default_down_dir");
if(_default_download_path == null) {
if (_default_download_path == null) {
_default_download_path = ".";
}
String limit_dl_speed = selectSettingValueFromDB("limit_download_speed");
if(limit_dl_speed != null) {
if (limit_dl_speed != null) {
_limit_download_speed = limit_dl_speed.equals("yes");
} else {
_limit_download_speed = LIMIT_TRANSFERENCE_SPEED_DEFAULT;
}
String limit_ul_speed = selectSettingValueFromDB("limit_upload_speed");
if(limit_ul_speed != null) {
if (limit_ul_speed != null) {
_limit_upload_speed = limit_ul_speed.equals("yes");
} else {
_limit_upload_speed = LIMIT_TRANSFERENCE_SPEED_DEFAULT;
}
String max_download_speed = selectSettingValueFromDB("max_download_speed");
if(max_download_speed != null) {
if (max_download_speed != null) {
_max_dl_speed = parseInt(max_download_speed);
} else {
_max_dl_speed=MAX_TRANSFERENCE_SPEED_DEFAULT;
_max_dl_speed = MAX_TRANSFERENCE_SPEED_DEFAULT;
}
String max_upload_speed = selectSettingValueFromDB("max_upload_speed");
if(max_upload_speed != null) {
if (max_upload_speed != null) {
_max_up_speed = parseInt(max_upload_speed);
} else {
_max_up_speed=MAX_TRANSFERENCE_SPEED_DEFAULT;
_max_up_speed = MAX_TRANSFERENCE_SPEED_DEFAULT;
}
try {
_mega_accounts = selectMegaAccounts();
} catch (SQLException ex) {
getLogger(MainPanel.class.getName()).log(SEVERE, null, ex);
}
_mega_master_pass_hash = DBTools.selectSettingValueFromDB("mega_master_pass_hash");
_mega_master_pass_salt = DBTools.selectSettingValueFromDB("mega_master_pass_salt");
if(_mega_master_pass_salt == null) {
if (_mega_master_pass_salt == null) {
try {
_mega_master_pass_salt = MiscTools.Bin2BASE64(MiscTools.genRandomByteArray(CryptTools.PBKDF2_SALT_BYTE_LENGTH));
DBTools.insertSettingValueInDB("mega_master_pass_salt", _mega_master_pass_salt);
} catch (Exception ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void _byebye() {
boolean exit = true;
if(!_streamserver.getWorking_threads().isEmpty()) {
if (!_streamserver.getWorking_threads().isEmpty()) {
Object[] options = {"No",
"Yes"};
"Yes"};
int n = showOptionDialog(getView(),
"It seems MegaBasterd is streaming video. Do you want to exit?",
"Warning!", YES_NO_CANCEL_OPTION, QUESTION_MESSAGE,
null,
options,
options[0]);
if(n==0) {
exit=false;
"It seems MegaBasterd is streaming video. Do you want to exit?",
"Warning!", YES_NO_CANCEL_OPTION, QUESTION_MESSAGE,
null,
options,
options[0]);
if (n == 0) {
exit = false;
}
} else if(!getDownload_manager().getTransference_provision_queue().isEmpty() || !getUpload_manager().getTransference_provision_queue().isEmpty()) {
} else if (!getDownload_manager().getTransference_provision_queue().isEmpty() || !getUpload_manager().getTransference_provision_queue().isEmpty()) {
Object[] options = {"No",
"Yes"};
"Yes"};
int n = showOptionDialog(getView(),
"It seems MegaBasterd is provisioning down/uploads.\nIf you exit now, unprovisioned down/uploads will be lost.\nDo you want to continue?",
"Warning!", YES_NO_CANCEL_OPTION, QUESTION_MESSAGE,
null,
options,
options[0]);
if(n==0) {
exit=false;
"It seems MegaBasterd is provisioning down/uploads.\nIf you exit now, unprovisioned down/uploads will be lost.\nDo you want to continue?",
"Warning!", YES_NO_CANCEL_OPTION, QUESTION_MESSAGE,
null,
options,
options[0]);
if (n == 0) {
exit = false;
}
}
if(exit) {
if (exit) {
try {
DBTools.vaccum();
} catch (SQLException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
exit(0);
}
}
private boolean checkAppIsRunning()
{
private boolean checkAppIsRunning() {
boolean app_is_running = false;
try {
final ServerSocket serverSocket = new ServerSocket(WATCHDOG_PORT, 0, InetAddress.getLoopbackAddress());
THREAD_POOL.execute(new Runnable(){
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
final ServerSocket socket = serverSocket;
while(true) {
while (true) {
try {
socket.accept();
swingReflectionInvoke("setExtendedState", getView(), NORMAL);
swingReflectionInvoke("setVisible", getView(), true);
} catch (IOException ex) {
getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}});
}
});
} catch (IOException ex) {
app_is_running = true;
try {
Socket clientSocket = new Socket(InetAddress.getLoopbackAddress(), WATCHDOG_PORT);
clientSocket.close();
} catch (IOException ex1) {
getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex1);
}
}
return app_is_running;
}
private void resumeDownloads() {
swingReflectionInvoke("setText", getView().getStatus_down_label(), "Resuming previous downloads, please wait...");
final MainPanel tthis =this;
THREAD_POOL.execute(new Runnable(){
final MainPanel tthis = this;
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
int conta_downloads = 0;
try {
ArrayList<HashMap<String,Object>> res = selectDownloads();
int conta_downloads = 0;
try {
ArrayList<HashMap<String, Object>> res = selectDownloads();
for (HashMap<String, Object> o : res) {
Download download = new Download(tthis, (String) o.get("url"), (String) o.get("path"), (String) o.get("filename"), (String) o.get("filekey"), (Long) o.get("filesize"), (String) o.get("filepass"), (String) o.get("filenoexpire"), _use_slots_down, _default_slots_down, false);
getDownload_manager().getTransference_provision_queue().add(download);
conta_downloads++;
}
} catch (SQLException ex) {
for(HashMap<String,Object> o:res) {
Download download = new Download(tthis, (String)o.get("url"), (String)o.get("path"), (String)o.get("filename"), (String)o.get("filekey"), (Long)o.get("filesize"), (String)o.get("filepass"), (String)o.get("filenoexpire"), _use_slots_down, _default_slots_down, false);
getDownload_manager().getTransference_provision_queue().add(download);
conta_downloads++;
}
} catch (SQLException ex) {
getLogger(MainPanelView.class.getName()).log(SEVERE, null, ex);
}
if(conta_downloads>0) {
getDownload_manager().secureNotify();
}
getView().getjTabbedPane1().setSelectedIndex(0);
if (conta_downloads > 0) {
getDownload_manager().secureNotify();
getView().getjTabbedPane1().setSelectedIndex(0);
}
swingReflectionInvoke("setText", getView().getStatus_down_label(), "");
}
});
swingReflectionInvoke("setText", getView().getStatus_down_label(), "");
}});
}
public boolean trayIcon() throws AWTException {
if (!java.awt.SystemTray.isSupported()) {
return false;
}
@ -596,14 +592,14 @@ public final class MainPanel {
messageItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@Override
public void actionPerformed(ActionEvent e) {
swingReflectionInvoke("setExtendedState", getView(), NORMAL);
swingReflectionInvoke("setExtendedState", getView(), NORMAL);
swingReflectionInvoke("setVisible", getView(), true);
swingReflectionInvoke("setVisible", getView(), true);
}
}
});
menu.add(messageItem);
@ -612,36 +608,33 @@ public final class MainPanel {
closeItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@Override
public void actionPerformed(ActionEvent e) {
_byebye();
_byebye();
}
}
});
menu.add(closeItem);
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
@Override
public void actionPerformed(ActionEvent e) {
if(!(boolean)swingReflectionInvokeAndWaitForReturn("isVisible", getView()))
{
swingReflectionInvoke("setExtendedState", getView(), NORMAL);
if (!(boolean) swingReflectionInvokeAndWaitForReturn("isVisible", getView())) {
swingReflectionInvoke("setExtendedState", getView(), NORMAL);
swingReflectionInvoke("setVisible", getView(), true);
}
else
{
swingReflectionInvoke("dispatchEvent", getView(), new WindowEvent(getView(), WINDOW_CLOSING));
swingReflectionInvoke("setVisible", getView(), true);
} else {
swingReflectionInvoke("dispatchEvent", getView(), new WindowEvent(getView(), WINDOW_CLOSING));
}
}
}
};
_trayicon = new TrayIcon(getDefaultToolkit().getImage(getClass().getResource(ICON_FILE)), "MegaBasterd", menu);
_trayicon.setToolTip("MegaBasterd " + VERSION);
@ -653,143 +646,139 @@ public final class MainPanel {
getSystemTray().add(_trayicon);
return true;
}
private void resumeUploads() {
swingReflectionInvoke("setText", getView().getStatus_up_label(), "Resuming previous uploads, please wait...");
final MainPanel tthis =this;
THREAD_POOL.execute(new Runnable(){
@Override
public void run() {
try {
int conta_uploads = 0;
boolean remember_pass = true;
ArrayList<HashMap<String,Object>> res = selectUploads();
for(HashMap<String,Object> o:res) {
try{
String email = (String)o.get("email");
MegaAPI ma;
if(_mega_accounts.get(email) != null) {
final HashMap<String,Object> account_info = (HashMap)_mega_accounts.get(email);
ma = _mega_active_accounts.get(email);
if(ma == null) {
ma = new MegaAPI();
String password_aes, user_hash;
if(getMega_master_pass_hash() != null) {
if(getMega_master_pass() == null) {
getView().getjTabbedPane1().setSelectedIndex(1);
GetMegaMasterPasswordDialog dialog = new GetMegaMasterPasswordDialog(getView(), true, getMega_master_pass_hash(), getMega_master_pass_salt());
swingReflectionInvokeAndWait("setLocationRelativeTo", dialog, getView());
swingReflectionInvokeAndWait("setVisible", dialog, true);
if(dialog.isPass_ok()) {
setMega_master_pass(dialog.getPass());
dialog.deletePass();
remember_pass = dialog.getRemember_checkbox().isSelected();
dialog.dispose();
password_aes =Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String)account_info.get("password_aes")), getMega_master_pass(), CryptTools.AES_ZERO_IV));
user_hash =Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String)account_info.get("user_hash")), getMega_master_pass(), CryptTools.AES_ZERO_IV));
} else {
dialog.dispose();
throw new Exception();
}
} else {
password_aes =Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String)account_info.get("password_aes")), getMega_master_pass(), CryptTools.AES_ZERO_IV));
user_hash =Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String)account_info.get("user_hash")), getMega_master_pass(), CryptTools.AES_ZERO_IV));
}
} else {
password_aes = (String)account_info.get("password_aes");
user_hash = (String)account_info.get("user_hash");
}
ma.fastLogin(email,bin2i32a(BASE642Bin(password_aes)), user_hash);
_mega_active_accounts.put(email, ma);
}
Upload upload = new Upload(tthis, ma, (String)o.get("filename"), (String)o.get("parent_node"), (String)o.get("ul_key")!=null?bin2i32a(BASE642Bin((String)o.get("ul_key"))):null, (String)o.get("url"), (String)o.get("root_node"), BASE642Bin((String)o.get("share_key")), (String)o.get("folder_link"), _use_slots_up, _default_slots_up, false);
getUpload_manager().getTransference_provision_queue().add(upload);
conta_uploads++;
} else {
deleteUpload((String)o.get("filename"), email);
}
} catch (Exception ex) {
getLogger(MainPanelView.class.getName()).log(SEVERE, null, ex);
}
}
if(conta_uploads>0) {
getUpload_manager().secureNotify();
getView().getjTabbedPane1().setSelectedIndex(1);
}
if(!remember_pass) {
setMega_master_pass(null);
}
swingReflectionInvoke("setText", getView().getStatus_up_label(), "");
} catch (Exception ex) {
getLogger(MainPanel.class.getName()).log(SEVERE, null, ex);
}
}});
}
private void resumeUploads() {
swingReflectionInvoke("setText", getView().getStatus_up_label(), "Resuming previous uploads, please wait...");
final MainPanel tthis = this;
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
try {
int conta_uploads = 0;
boolean remember_pass = true;
ArrayList<HashMap<String, Object>> res = selectUploads();
for (HashMap<String, Object> o : res) {
try {
String email = (String) o.get("email");
MegaAPI ma;
if (_mega_accounts.get(email) != null) {
final HashMap<String, Object> account_info = (HashMap) _mega_accounts.get(email);
ma = _mega_active_accounts.get(email);
if (ma == null) {
ma = new MegaAPI();
String password_aes, user_hash;
if (getMega_master_pass_hash() != null) {
if (getMega_master_pass() == null) {
getView().getjTabbedPane1().setSelectedIndex(1);
GetMegaMasterPasswordDialog dialog = new GetMegaMasterPasswordDialog(getView(), true, getMega_master_pass_hash(), getMega_master_pass_salt());
swingReflectionInvokeAndWait("setLocationRelativeTo", dialog, getView());
swingReflectionInvokeAndWait("setVisible", dialog, true);
if (dialog.isPass_ok()) {
setMega_master_pass(dialog.getPass());
dialog.deletePass();
remember_pass = dialog.getRemember_checkbox().isSelected();
dialog.dispose();
password_aes = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String) account_info.get("password_aes")), getMega_master_pass(), CryptTools.AES_ZERO_IV));
user_hash = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String) account_info.get("user_hash")), getMega_master_pass(), CryptTools.AES_ZERO_IV));
} else {
dialog.dispose();
throw new Exception();
}
} else {
password_aes = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String) account_info.get("password_aes")), getMega_master_pass(), CryptTools.AES_ZERO_IV));
user_hash = Bin2BASE64(CryptTools.aes_cbc_decrypt_pkcs7(BASE642Bin((String) account_info.get("user_hash")), getMega_master_pass(), CryptTools.AES_ZERO_IV));
}
} else {
password_aes = (String) account_info.get("password_aes");
user_hash = (String) account_info.get("user_hash");
}
ma.fastLogin(email, bin2i32a(BASE642Bin(password_aes)), user_hash);
_mega_active_accounts.put(email, ma);
}
Upload upload = new Upload(tthis, ma, (String) o.get("filename"), (String) o.get("parent_node"), (String) o.get("ul_key") != null ? bin2i32a(BASE642Bin((String) o.get("ul_key"))) : null, (String) o.get("url"), (String) o.get("root_node"), BASE642Bin((String) o.get("share_key")), (String) o.get("folder_link"), _use_slots_up, _default_slots_up, false);
getUpload_manager().getTransference_provision_queue().add(upload);
conta_uploads++;
} else {
deleteUpload((String) o.get("filename"), email);
}
} catch (Exception ex) {
getLogger(MainPanelView.class.getName()).log(SEVERE, null, ex);
}
}
if (conta_uploads > 0) {
getUpload_manager().secureNotify();
getView().getjTabbedPane1().setSelectedIndex(1);
}
if (!remember_pass) {
setMega_master_pass(null);
}
swingReflectionInvoke("setText", getView().getStatus_up_label(), "");
} catch (Exception ex) {
getLogger(MainPanel.class.getName()).log(SEVERE, null, ex);
}
}
});
}
}

View File

@ -1,6 +1,5 @@
package megabasterd;
import java.awt.Color;
import static java.awt.Font.BOLD;
import static java.awt.Font.PLAIN;
@ -37,12 +36,10 @@ import static megabasterd.MiscTools.swingReflectionInvoke;
import static megabasterd.MiscTools.swingReflectionInvokeAndWait;
import static megabasterd.MiscTools.updateFont;
public final class MainPanelView extends javax.swing.JFrame {
private final MainPanel _main_panel;
public JLabel getKiss_server_status() {
return kiss_server_status;
}
@ -110,47 +107,46 @@ public final class MainPanelView extends javax.swing.JFrame {
public JTabbedPane getjTabbedPane1() {
return jTabbedPane1;
}
public MainPanelView(MainPanel main_panel) {
_main_panel = main_panel;
initComponents();
setTitle("MegaBasterd " + VERSION);
setIconImage(new ImageIcon(getClass().getResource(ICON_FILE)).getImage());
MiscTools.swingInvokeIt(new Runnable(){
MiscTools.swingInvokeIt(new Runnable() {
@Override
public void run() {updateFont(file_menu, FONT_DEFAULT, PLAIN);
updateFont(edit_menu, FONT_DEFAULT, PLAIN);
updateFont(help_menu, FONT_DEFAULT, PLAIN);
updateFont(new_download_menu, FONT_DEFAULT, PLAIN);
updateFont(exit_menu, FONT_DEFAULT, PLAIN);
updateFont(settings_menu, FONT_DEFAULT, PLAIN);
updateFont(hide_tray_menu, FONT_DEFAULT, PLAIN);
updateFont(about_menu, FONT_DEFAULT, PLAIN);
updateFont(new_stream_menu, FONT_DEFAULT, PLAIN);
updateFont(new_upload_menu, FONT_DEFAULT, PLAIN);
updateFont(clean_all_up_menu, FONT_DEFAULT, PLAIN);
updateFont(clean_all_down_menu, FONT_DEFAULT, PLAIN);
updateFont(global_speed_down_label, FONT_DEFAULT, BOLD);
updateFont(global_speed_up_label, FONT_DEFAULT, BOLD);
updateFont(kiss_server_status, FONT_DEFAULT, BOLD);
updateFont(status_down_label, FONT_DEFAULT, BOLD);
updateFont(status_up_label, FONT_DEFAULT, BOLD);
updateFont(close_all_finished_down_button, FONT_DEFAULT, BOLD);
updateFont(close_all_finished_up_button, FONT_DEFAULT, BOLD);
updateFont(pause_all_down_button, FONT_DEFAULT, BOLD);
updateFont(pause_all_up_button, FONT_DEFAULT, BOLD);
updateFont(jTabbedPane1, FONT_DEFAULT, PLAIN);}}, true);
public void run() {
updateFont(file_menu, FONT_DEFAULT, PLAIN);
updateFont(edit_menu, FONT_DEFAULT, PLAIN);
updateFont(help_menu, FONT_DEFAULT, PLAIN);
updateFont(new_download_menu, FONT_DEFAULT, PLAIN);
updateFont(exit_menu, FONT_DEFAULT, PLAIN);
updateFont(settings_menu, FONT_DEFAULT, PLAIN);
updateFont(hide_tray_menu, FONT_DEFAULT, PLAIN);
updateFont(about_menu, FONT_DEFAULT, PLAIN);
updateFont(new_stream_menu, FONT_DEFAULT, PLAIN);
updateFont(new_upload_menu, FONT_DEFAULT, PLAIN);
updateFont(clean_all_up_menu, FONT_DEFAULT, PLAIN);
updateFont(clean_all_down_menu, FONT_DEFAULT, PLAIN);
updateFont(global_speed_down_label, FONT_DEFAULT, BOLD);
updateFont(global_speed_up_label, FONT_DEFAULT, BOLD);
updateFont(kiss_server_status, FONT_DEFAULT, BOLD);
updateFont(status_down_label, FONT_DEFAULT, BOLD);
updateFont(status_up_label, FONT_DEFAULT, BOLD);
updateFont(close_all_finished_down_button, FONT_DEFAULT, BOLD);
updateFont(close_all_finished_up_button, FONT_DEFAULT, BOLD);
updateFont(pause_all_down_button, FONT_DEFAULT, BOLD);
updateFont(pause_all_up_button, FONT_DEFAULT, BOLD);
updateFont(jTabbedPane1, FONT_DEFAULT, PLAIN);
}
}, true);
swingReflectionInvoke("setVisible", global_speed_down_label, false);
swingReflectionInvoke("setVisible", global_speed_up_label, false);
swingReflectionInvoke("setVisible", close_all_finished_down_button, false);
@ -472,34 +468,34 @@ public final class MainPanelView extends javax.swing.JFrame {
}// </editor-fold>//GEN-END:initComponents
private void new_download_menuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_new_download_menuActionPerformed
new_download_menu.setEnabled(false);
final LinkGrabberDialog dialog = new LinkGrabberDialog(this, true, _main_panel.getDefault_download_path(), _main_panel.getClipboardspy());
_main_panel.getClipboardspy().attachObserver(dialog);
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
_main_panel.getClipboardspy().detachObserver(dialog);
final String dl_path = dialog.getDownload_path();
jTabbedPane1.setSelectedIndex(0);
if(dialog.isDownload()) {
Runnable run = new Runnable(){
@Override
public void run() {
if (dialog.isDownload()) {
Runnable run = new Runnable() {
@Override
public void run() {
Set<String> urls = new HashSet(findAllRegex("(?:https?|mega)://[^/]*/(#.*?)?!.+![^\r\n]+", dialog.getLinks_textarea().getText(), 0));
Set<String> megadownloader = new HashSet(findAllRegex("mega://enc.*?[^\r\n]+", dialog.getLinks_textarea().getText(), 0));
for (String link : megadownloader ) {
for (String link : megadownloader) {
try {
@ -510,39 +506,38 @@ public final class MainPanelView extends javax.swing.JFrame {
}
}
if(!urls.isEmpty()) {
if (!urls.isEmpty()) {
getMain_panel().getDownload_manager().addPre_count(urls.size());
getMain_panel().getDownload_manager().secureNotify();
for (String url : urls ) {
if(getMain_panel().getDownload_manager().getPre_count() > 0)
{
for (String url : urls) {
if (getMain_panel().getDownload_manager().getPre_count() > 0) {
url = url.replaceAll("^mega://", "https://mega.nz");
Download download;
if(findFirstRegex("#F!", url, 0) != null) {
if (findFirstRegex("#F!", url, 0) != null) {
FolderLinkDialog fdialog = new FolderLinkDialog(_main_panel.getView(), true, url);
if(!fdialog.isMega_error()) {
if (!fdialog.isMega_error()) {
swingReflectionInvokeAndWait("setLocationRelativeTo", fdialog, _main_panel.getView());
swingReflectionInvokeAndWait("setVisible", fdialog, true);
if(fdialog.isDownload()) {
if (fdialog.isDownload()) {
List<HashMap> folder_links = fdialog.getDownload_links();
fdialog.dispose();
for(HashMap folder_link:folder_links) {
for (HashMap folder_link : folder_links) {
download = new Download(getMain_panel(), (String)folder_link.get("url"), dl_path, (String)folder_link.get("filename"), (String)folder_link.get("filekey"), (long)folder_link.get("filesize"), null, null, getMain_panel().isUse_slots_down(), getMain_panel().getDefault_slots_down(), true);
download = new Download(getMain_panel(), (String) folder_link.get("url"), dl_path, (String) folder_link.get("filename"), (String) folder_link.get("filekey"), (long) folder_link.get("filesize"), null, null, getMain_panel().isUse_slots_down(), getMain_panel().getDefault_slots_down(), true);
getMain_panel().getDownload_manager().getTransference_provision_queue().add(download);
}
@ -565,37 +560,38 @@ public final class MainPanelView extends javax.swing.JFrame {
}
}
}
}
}
};
getMain_panel().getDownload_manager().getTransference_preprocess_queue().add(run);
getMain_panel().getDownload_manager().secureNotify();
new_download_menu.setEnabled(true);
}};
getMain_panel().getDownload_manager().getTransference_preprocess_queue().add(run);
getMain_panel().getDownload_manager().secureNotify();
new_download_menu.setEnabled(true);
} else {
new_download_menu.setEnabled(true);
}
dialog.dispose();
}//GEN-LAST:event_new_download_menuActionPerformed
private void settings_menuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_settings_menuActionPerformed
SettingsDialog dialog = new SettingsDialog(this, true);
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
if(dialog.isSettings_ok()) {
for(String email:dialog.getDeleted_accounts()) {
SettingsDialog dialog = new SettingsDialog(this, true);
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
if (dialog.isSettings_ok()) {
for (String email : dialog.getDeleted_accounts()) {
try {
deleteMegaAccount(email);
} catch (SQLException ex) {
@ -606,34 +602,34 @@ public final class MainPanelView extends javax.swing.JFrame {
_main_panel.getMega_active_accounts().remove(email);
}
_main_panel.loadUserSettings();
if(_main_panel.isLimit_download_speed()) {
_main_panel.getStream_supervisor().setMaxBytesPerSecInput(_main_panel.getMax_dl_speed()*1024);
global_speed_down_label.setForeground(new Color(255,0,0));
_main_panel.loadUserSettings();
if (_main_panel.isLimit_download_speed()) {
_main_panel.getStream_supervisor().setMaxBytesPerSecInput(_main_panel.getMax_dl_speed() * 1024);
global_speed_down_label.setForeground(new Color(255, 0, 0));
} else {
_main_panel.getStream_supervisor().setMaxBytesPerSecInput(0);
global_speed_down_label.setForeground(new Color(0,128,255));
global_speed_down_label.setForeground(new Color(0, 128, 255));
}
if(_main_panel.isLimit_upload_speed()) {
if (_main_panel.isLimit_upload_speed()) {
_main_panel.getStream_supervisor().setMaxBytesPerSecOutput(_main_panel.getMax_up_speed()*1024);
_main_panel.getStream_supervisor().setMaxBytesPerSecOutput(_main_panel.getMax_up_speed() * 1024);
global_speed_up_label.setForeground(new Color(255,0,0));
global_speed_up_label.setForeground(new Color(255, 0, 0));
} else {
_main_panel.getStream_supervisor().setMaxBytesPerSecOutput(0);
global_speed_up_label.setForeground(new Color(0,128,255));
global_speed_up_label.setForeground(new Color(0, 128, 255));
}
@ -645,26 +641,26 @@ public final class MainPanelView extends javax.swing.JFrame {
_main_panel.getUpload_manager().secureNotify();
}
if(!dialog.isRemember_master_pass()) {
if (!dialog.isRemember_master_pass()) {
_main_panel.setMega_master_pass(null);
}
dialog.dispose();
}//GEN-LAST:event_settings_menuActionPerformed
private void hide_tray_menuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hide_tray_menuActionPerformed
dispatchEvent(new WindowEvent(this, WINDOW_CLOSING));
}//GEN-LAST:event_hide_tray_menuActionPerformed
private void about_menuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_about_menuActionPerformed
AboutDialog dialog = new AboutDialog(this, true);
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
}//GEN-LAST:event_about_menuActionPerformed
@ -679,191 +675,190 @@ public final class MainPanelView extends javax.swing.JFrame {
}//GEN-LAST:event_close_all_finished_down_buttonActionPerformed
private void clean_all_down_menuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clean_all_down_menuActionPerformed
Object[] options = {"No",
"Yes"};
"Yes"};
int n = showOptionDialog(_main_panel.getView(),
"Remove all preprocessing, provisioning and waiting downloads?",
"Warning!", YES_NO_CANCEL_OPTION, QUESTION_MESSAGE,
null,
options,
options[0]);
int n = showOptionDialog(_main_panel.getView(),
"Remove all preprocessing, provisioning and waiting downloads?",
"Warning!", YES_NO_CANCEL_OPTION, QUESTION_MESSAGE,
null,
options,
options[0]);
if(n==1) {
_main_panel.getDownload_manager().closeAllPreProWaiting();
}
if (n == 1) {
_main_panel.getDownload_manager().closeAllPreProWaiting();
}
}//GEN-LAST:event_clean_all_down_menuActionPerformed
private void pause_all_down_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pause_all_down_buttonActionPerformed
_main_panel.getDownload_manager().pauseAll();
}//GEN-LAST:event_pause_all_down_buttonActionPerformed
private void new_stream_menuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_new_stream_menuActionPerformed
StreamerDialog dialog = new StreamerDialog(this, true, _main_panel.getClipboardspy());
_main_panel.getClipboardspy().attachObserver(dialog);
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
_main_panel.getClipboardspy().detachObserver(dialog);
}//GEN-LAST:event_new_stream_menuActionPerformed
private void new_upload_menuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_new_upload_menuActionPerformed
final FileGrabberDialog dialog = new FileGrabberDialog(this,true);
try{
new_upload_menu.setEnabled(false);
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
final FileGrabberDialog dialog = new FileGrabberDialog(this, true);
try {
new_upload_menu.setEnabled(false);
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
if (dialog.isUpload() && dialog.getFiles().size() > 0) {
if(dialog.isUpload() && dialog.getFiles().size() > 0) {
getMain_panel().getUpload_manager().addPre_count(dialog.getFiles().size());
getMain_panel().getUpload_manager().secureNotify();
final String mega_account = (String)dialog.getAccount_combobox().getSelectedItem();
final String mega_account = (String) dialog.getAccount_combobox().getSelectedItem();
final String base_path = dialog.getBase_path();
final String dir_name=dialog.getDir_name_textfield().getText();
final String dir_name = dialog.getDir_name_textfield().getText();
jTabbedPane1.setSelectedIndex(1);
Runnable run = new Runnable(){
Runnable run = new Runnable() {
@Override
public void run() {
MegaAPI ma=getMain_panel().getMega_active_accounts().get(mega_account);
try {
byte[] parent_key = ma.genFolderKey();
byte[] share_key = ma.genShareKey();
HashMap<String,Object> res = ma.createDir(dir_name!=null?dir_name:dialog.getFiles().get(0).getName()+"_"+genID(10), ma.getRoot_id(), parent_key, i32a2bin(ma.getMaster_key()));
String parent_node = (String)((Map)((List)res.get("f")).get(0)).get("h");
MegaAPI ma = getMain_panel().getMega_active_accounts().get(mega_account);
System.out.println("Dir "+ parent_node+" created");
ma.shareFolder(parent_node, parent_key, share_key);
String folder_link = ma.getPublicFolderLink(parent_node, share_key);
MegaDirNode file_paths = new MegaDirNode(parent_node);
for(File f:dialog.getFiles()) {
if(getMain_panel().getUpload_manager().getPre_count() > 0)
{
String file_path = f.getParentFile().getAbsolutePath().replace(base_path, "");
try {
String[] dirs = file_path.split("/");
byte[] parent_key = ma.genFolderKey();
System.out.println(file_path);
byte[] share_key = ma.genShareKey();
MegaDirNode current_node = file_paths;
HashMap<String, Object> res = ma.createDir(dir_name != null ? dir_name : dialog.getFiles().get(0).getName() + "_" + genID(10), ma.getRoot_id(), parent_key, i32a2bin(ma.getMaster_key()));
String file_parent = current_node.getNode_id();
String parent_node = (String) ((Map) ((List) res.get("f")).get(0)).get("h");
for(String d:dirs) {
System.out.println("Dir " + parent_node + " created");
if(!d.isEmpty()) {
ma.shareFolder(parent_node, parent_key, share_key);
if(current_node.getChildren().get(d) != null) {
String folder_link = ma.getPublicFolderLink(parent_node, share_key);
current_node = current_node.getChildren().get(d);
MegaDirNode file_paths = new MegaDirNode(parent_node);
file_parent = current_node.getNode_id();
for (File f : dialog.getFiles()) {
} else {
if (getMain_panel().getUpload_manager().getPre_count() > 0) {
String file_path = f.getParentFile().getAbsolutePath().replace(base_path, "");
res = ma.createDirInsideAnotherSharedDir(d, current_node.getNode_id(), ma.genFolderKey(), i32a2bin(ma.getMaster_key()), parent_node, share_key);
String[] dirs = file_path.split("/");
file_parent = (String)((Map)((List)res.get("f")).get(0)).get("h");
System.out.println(file_path);
current_node.getChildren().put(d, new MegaDirNode(file_parent));
MegaDirNode current_node = file_paths;
current_node = current_node.getChildren().get(d);
}
String file_parent = current_node.getNode_id();
for (String d : dirs) {
if (!d.isEmpty()) {
if (current_node.getChildren().get(d) != null) {
current_node = current_node.getChildren().get(d);
file_parent = current_node.getNode_id();
} else {
res = ma.createDirInsideAnotherSharedDir(d, current_node.getNode_id(), ma.genFolderKey(), i32a2bin(ma.getMaster_key()), parent_node, share_key);
file_parent = (String) ((Map) ((List) res.get("f")).get(0)).get("h");
current_node.getChildren().put(d, new MegaDirNode(file_parent));
current_node = current_node.getChildren().get(d);
}
}
Upload upload = new Upload(getMain_panel(), ma, f.getAbsolutePath(), file_parent, null, null, parent_node, share_key, folder_link, getMain_panel().isUse_slots_up(), getMain_panel().getDefault_slots_up(), false);
getMain_panel().getUpload_manager().getTransference_provision_queue().add(upload);
getMain_panel().getUpload_manager().addPre_count(-1);
getMain_panel().getUpload_manager().secureNotify();
}
}
} catch (Exception ex) {
getLogger(MainPanelView.class.getName()).log(SEVERE, null, ex);
Upload upload = new Upload(getMain_panel(), ma, f.getAbsolutePath(), file_parent, null, null, parent_node, share_key, folder_link, getMain_panel().isUse_slots_up(), getMain_panel().getDefault_slots_up(), false);
getMain_panel().getUpload_manager().getTransference_provision_queue().add(upload);
getMain_panel().getUpload_manager().addPre_count(-1);
getMain_panel().getUpload_manager().secureNotify();
}
}
}
};
getMain_panel().getUpload_manager().getTransference_preprocess_queue().add(run);
getMain_panel().getUpload_manager().secureNotify();
new_upload_menu.setEnabled(true);
} else {
new_upload_menu.setEnabled(true);
}
}catch(Exception ex) {}
if(!dialog.isRemember_master_pass()) {
} catch (Exception ex) {
getLogger(MainPanelView.class.getName()).log(SEVERE, null, ex);
}
}
};
getMain_panel().getUpload_manager().getTransference_preprocess_queue().add(run);
getMain_panel().getUpload_manager().secureNotify();
new_upload_menu.setEnabled(true);
} else {
new_upload_menu.setEnabled(true);
}
} catch (Exception ex) {
}
if (!dialog.isRemember_master_pass()) {
_main_panel.setMega_master_pass(null);
}
dialog.dispose();
}//GEN-LAST:event_new_upload_menuActionPerformed
private void close_all_finished_up_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_close_all_finished_up_buttonActionPerformed
_main_panel.getUpload_manager().closeAllFinished();
}//GEN-LAST:event_close_all_finished_up_buttonActionPerformed
private void pause_all_up_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pause_all_up_buttonActionPerformed
_main_panel.getUpload_manager().pauseAll();
}//GEN-LAST:event_pause_all_up_buttonActionPerformed
private void clean_all_up_menuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clean_all_up_menuActionPerformed
Object[] options = {"No",
"Yes"};
Object[] options = {"No",
"Yes"};
int n = showOptionDialog(_main_panel.getView(),
"Remove all preprocessing, provisioning and waiting uploads?",
"Warning!", YES_NO_CANCEL_OPTION, QUESTION_MESSAGE,
null,
options,
options[0]);
"Remove all preprocessing, provisioning and waiting uploads?",
"Warning!", YES_NO_CANCEL_OPTION, QUESTION_MESSAGE,
null,
options,
options[0]);
if(n==1) {
if (n == 1) {
_main_panel.getUpload_manager().closeAllPreProWaiting();
}
}//GEN-LAST:event_clean_all_up_menuActionPerformed
@ -903,8 +898,4 @@ public final class MainPanelView extends javax.swing.JFrame {
private javax.swing.JPanel uploads_panel;
// End of variables declaration//GEN-END:variables
}

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,9 @@
package megabasterd;
public final class MegaAPIException extends Exception {
public MegaAPIException(String message)
{
public MegaAPIException(String message) {
super(message);
}
}
}

View File

@ -32,90 +32,86 @@ import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.codehaus.jackson.map.ObjectMapper;
/**
*
* @author tonikelope
*/
public final class MegaCrypterAPI {
public static final Set<String> PASS_CACHE = new HashSet<>();
public static final Object PASS_LOCK = new Object();
private static String _rawRequest(String request, URL url_api) throws IOException, MegaCrypterAPIException {
String response=null;
try(CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient())
{
String response = null;
try (CloseableHttpClient httpclient = MiscTools.getApacheKissHttpClient()) {
boolean error;
int conta_error=0;
int conta_error = 0;
HttpPost httppost;
do{
do {
error = true;
try {
httppost = new HttpPost(url_api.toURI());
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("User-Agent", MainPanel.DEFAULT_USER_AGENT);
httppost.addHeader("Connection", "close");
httppost.setEntity(new StringEntity(request));
try(CloseableHttpResponse httpresponse = httpclient.execute(httppost)) {
if (httpresponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
{
System.out.println("Failed : HTTP error code : " + httpresponse.getStatusLine().getStatusCode());
httppost.setHeader("Content-type", "application/json");
} else {
httppost.setHeader("User-Agent", MainPanel.DEFAULT_USER_AGENT);
InputStream is=httpresponse.getEntity().getContent();
httppost.addHeader("Connection", "close");
ByteArrayOutputStream byte_res = new ByteArrayOutputStream();
httppost.setEntity(new StringEntity(request));
byte[] buffer = new byte[16*1024];
try (CloseableHttpResponse httpresponse = httpclient.execute(httppost)) {
int reads;
if (httpresponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
System.out.println("Failed : HTTP error code : " + httpresponse.getStatusLine().getStatusCode());
while( (reads=is.read(buffer)) != -1 ) {
} else {
byte_res.write(buffer, 0, reads);
}
InputStream is = httpresponse.getEntity().getContent();
response = new String(byte_res.toByteArray());
ByteArrayOutputStream byte_res = new ByteArrayOutputStream();
if(response.length() > 0) {
int mc_error;
byte[] buffer = new byte[16 * 1024];
if( (mc_error=MegaCrypterAPI.checkMCError(response))!=0 )
{
throw new MegaCrypterAPIException(String.valueOf(mc_error));
} else {
error = false;
int reads;
while ((reads = is.read(buffer)) != -1) {
byte_res.write(buffer, 0, reads);
}
response = new String(byte_res.toByteArray());
if (response.length() > 0) {
int mc_error;
if ((mc_error = MegaCrypterAPI.checkMCError(response)) != 0) {
throw new MegaCrypterAPIException(String.valueOf(mc_error));
} else {
error = false;
}
}
}
}
}
} catch (URISyntaxException ex) {
Logger.getLogger(MegaCrypterAPI.class.getName()).log(Level.SEVERE, null, ex);
}
if(error) {
if (error) {
try {
Thread.sleep( getWaitTimeExpBackOff(conta_error++) );
Thread.sleep(getWaitTimeExpBackOff(conta_error++));
} catch (InterruptedException ex) {
getLogger(MegaAPI.class.getName()).log(Level.SEVERE, null, ex);
}
@ -124,40 +120,38 @@ public final class MegaCrypterAPI {
conta_error = 0;
}
}while(error);
} while (error);
}
return response;
}
public static String getMegaFileDownloadUrl(String link, String pass_hash, String noexpire_token) throws IOException, MegaCrypterAPIException
{
String request = noexpire_token != null?"{\"m\":\"dl\", \"link\": \""+link+"\", \"noexpire\": \""+noexpire_token+"\"}":"{\"m\":\"dl\", \"link\": \""+link+"\"}";
URL url_api = new URL(findFirstRegex("https?://[^/]+", link, 0)+"/api");
public static String getMegaFileDownloadUrl(String link, String pass_hash, String noexpire_token) throws IOException, MegaCrypterAPIException {
String request = noexpire_token != null ? "{\"m\":\"dl\", \"link\": \"" + link + "\", \"noexpire\": \"" + noexpire_token + "\"}" : "{\"m\":\"dl\", \"link\": \"" + link + "\"}";
URL url_api = new URL(findFirstRegex("https?://[^/]+", link, 0) + "/api");
String res = MegaCrypterAPI._rawRequest(request, url_api);
ObjectMapper objectMapper = new ObjectMapper();
HashMap res_map = objectMapper.readValue(res, HashMap.class);
String dl_url = (String)res_map.get("url");
if(pass_hash != null)
{
String dl_url = (String) res_map.get("url");
if (pass_hash != null) {
try {
String pass = (String)res_map.get("pass");
String pass = (String) res_map.get("pass");
byte[] iv = BASE642Bin(pass);
Cipher decrypter = CryptTools.genDecrypter("AES", "AES/CBC/PKCS5Padding", BASE642Bin(pass_hash),iv);
Cipher decrypter = CryptTools.genDecrypter("AES", "AES/CBC/PKCS5Padding", BASE642Bin(pass_hash), iv);
byte[] decrypted_url = decrypter.doFinal(BASE642Bin(dl_url));
dl_url = new String(decrypted_url);
} catch (Exception ex) {
getLogger(MegaCrypterAPI.class.getName()).log(Level.SEVERE, null, ex);
}
@ -165,120 +159,116 @@ public final class MegaCrypterAPI {
return dl_url;
}
public static String[] getMegaFileMetadata(String link, MainPanelView panel) throws Exception, MegaCrypterAPIException
{
String request = "{\"m\":\"info\", \"link\": \""+link+"\"}";
URL url_api = new URL(findFirstRegex("https?://[^/]+", link, 0)+"/api");
public static String[] getMegaFileMetadata(String link, MainPanelView panel) throws Exception, MegaCrypterAPIException {
String request = "{\"m\":\"info\", \"link\": \"" + link + "\"}";
URL url_api = new URL(findFirstRegex("https?://[^/]+", link, 0) + "/api");
String res = MegaCrypterAPI._rawRequest(request, url_api);
ObjectMapper objectMapper = new ObjectMapper();
HashMap res_map = objectMapper.readValue(res, HashMap.class);
String fname = cleanFilename((String)res_map.get("name"));
String fpath=null;
String fname = cleanFilename((String) res_map.get("name"));
String fpath = null;
Object fpath_val = res_map.get("path");
if(fpath_val instanceof Boolean) {
if (fpath_val instanceof Boolean) {
fpath = null;
} else if (fpath_val instanceof String) {
fpath = cleanFilePath((String)fpath_val);
fpath = cleanFilePath((String) fpath_val);
}
String file_size;
try {
file_size = String.valueOf(res_map.get("size"));
} catch(java.lang.ClassCastException ex) {
} catch (java.lang.ClassCastException ex) {
file_size = String.valueOf(res_map.get("size"));
}
String fkey = (String)res_map.get("key");
String noexpire_token=null;
String fkey = (String) res_map.get("key");
String noexpire_token = null;
Object expire_val = res_map.get("expire");
if(expire_val instanceof Boolean) {
if (expire_val instanceof Boolean) {
noexpire_token = null;
} else if (expire_val instanceof String) {
String aux[] = ((String) expire_val).split("#");
noexpire_token = aux[1];
}
String pass=null;
String pass = null;
Object pass_val = res_map.get("pass");
if(pass_val instanceof Boolean) {
if (pass_val instanceof Boolean) {
pass = null;
} else if (expire_val instanceof String) {
pass = (String)pass_val;
pass = (String) pass_val;
}
System.out.println(noexpire_token);
if(pass != null)
{
if (pass != null) {
String[] pass_items = pass.split("#");
if(pass_items.length != 4)
{
if (pass_items.length != 4) {
throw new MegaCrypterAPIException("Bad password data!");
}
int iterations = Integer.parseInt(pass_items[0]);
byte[] key_check = BASE642Bin(pass_items[1]);
byte[] salt = BASE642Bin(pass_items[2]);
byte[] iv = BASE642Bin(pass_items[3]);
String password;
byte[] info_key = null;
boolean bad_pass;
Cipher decrypter;
synchronized(PASS_LOCK) {
synchronized (PASS_LOCK) {
LinkedList<String> pass_list = new LinkedList(PASS_CACHE);
do
{
do {
bad_pass = true;
if((password = pass_list.poll()) == null) {
if ((password = pass_list.poll()) == null) {
password = JOptionPane.showInputDialog(panel, "Enter password for MegaCrypter link:");
}
if(password != null) {
if (password != null) {
try {
info_key=CryptTools.PBKDF2HMACSHA256(password, salt, (int)Math.pow(2, iterations));
info_key = CryptTools.PBKDF2HMACSHA256(password, salt, (int) Math.pow(2, iterations));
decrypter = CryptTools.genDecrypter("AES", "AES/CBC/PKCS5Padding", info_key, iv);
@ -286,25 +276,24 @@ public final class MegaCrypterAPI {
bad_pass = !Arrays.equals(info_key, decrypter.doFinal(key_check));
if(!bad_pass) {
if (!bad_pass) {
PASS_CACHE.add(password);
}
} catch (IllegalBlockSizeException | BadPaddingException ex) {}
} catch (IllegalBlockSizeException | BadPaddingException ex) {
}
} catch (InvalidKeySpecException ex) {}
} catch (InvalidKeySpecException ex) {
}
}
}while(password!=null && bad_pass);
} while (password != null && bad_pass);
}
if(bad_pass)
{
if (bad_pass) {
throw new MegaCrypterAPIException("25");
}
else
{
} else {
decrypter = CryptTools.genDecrypter("AES", "AES/CBC/PKCS5Padding", info_key, iv);
byte[] decrypted_key = decrypter.doFinal(BASE642Bin(fkey));
@ -317,34 +306,31 @@ public final class MegaCrypterAPI {
fname = new String(decrypted_name);
if(fpath != null)
{
if (fpath != null) {
byte[] decrypted_fpath = decrypter.doFinal(BASE642Bin(fpath));
fpath = new String(decrypted_fpath);
}
pass=Bin2BASE64(info_key);
pass = Bin2BASE64(info_key);
}
}
if(fpath != null)
{
fname = fpath+fname;
if (fpath != null) {
fname = fpath + fname;
}
String file_data[] = {fname, file_size, fkey, pass, noexpire_token};
return file_data;
}
private static int checkMCError(String data)
{
private static int checkMCError(String data) {
String error = findFirstRegex("\"error\" *: *([0-9-]+)", data, 1);
return error != null?Integer.parseInt(error):0;
return error != null ? Integer.parseInt(error) : 0;
}
private MegaCrypterAPI() {

View File

@ -1,10 +1,9 @@
package megabasterd;
public final class MegaCrypterAPIException extends Exception {
public MegaCrypterAPIException(String message)
{
public MegaCrypterAPIException(String message) {
super(message);
}
}

View File

@ -7,15 +7,15 @@ import java.util.HashMap;
* @author tonikelope
*/
public final class MegaDirNode {
private final String _node_id;
private final HashMap <String,MegaDirNode> _children;
private final HashMap<String, MegaDirNode> _children;
public MegaDirNode(String node_id) {
_node_id = node_id;
_children = new HashMap<>();
}

View File

@ -9,32 +9,32 @@ import static megabasterd.MiscTools.formatBytes;
* @author tonikelope
*/
public final class MegaMutableTreeNode extends DefaultMutableTreeNode {
public MegaMutableTreeNode() {
super();
}
public MegaMutableTreeNode(Object o) {
super(o);
}
@Override
public String toString() {
if(userObject instanceof HashMap) {
HashMap<String,Object> user_object = (HashMap<String,Object>)userObject;
return user_object.get("name") + ((isLeaf() && user_object.get("size")!=null)?" ["+formatBytes((long)user_object.get("size"))+"]":"");
} else if(userObject instanceof Object) {
if (userObject instanceof HashMap) {
HashMap<String, Object> user_object = (HashMap<String, Object>) userObject;
return user_object.get("name") + ((isLeaf() && user_object.get("size") != null) ? " [" + formatBytes((long) user_object.get("size")) + "]" : "");
} else if (userObject instanceof Object) {
return userObject.toString();
} else {
return "";
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -3,45 +3,41 @@ package megabasterd;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Logger.getLogger;
public final class ProgressMeter implements Runnable, SecureNotifiable
{
public final class ProgressMeter implements Runnable, SecureNotifiable {
private final Transference _transference;
private volatile boolean _exit;
private final Object _secure_notify_lock;
private boolean _notified;
private long _progress;
ProgressMeter(Transference transference)
{
ProgressMeter(Transference transference) {
_notified = false;
_secure_notify_lock = new Object();
_transference = transference;
_progress = transference.getProgress();
_exit = false;
}
public void setExit(boolean value)
{
public void setExit(boolean value) {
_exit = value;
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -49,40 +45,36 @@ public final class ProgressMeter implements Runnable, SecureNotifiable
getLogger(ProgressMeter.class.getName()).log(SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
@Override
public void run()
{
public void run() {
System.out.println("ProgressMeter hello!");
while(!_exit || !_transference.getPartialProgress().isEmpty())
{
while (!_exit || !_transference.getPartialProgress().isEmpty()) {
Integer reads;
while( (reads=_transference.getPartialProgress().poll()) !=null )
{
_progress+=reads;
while ((reads = _transference.getPartialProgress().poll()) != null) {
_progress += reads;
}
_transference.setProgress(_progress);
if(!_exit)
{
if (!_exit) {
secureWait();
}
}

View File

@ -7,8 +7,8 @@ package megabasterd;
public interface SecureNotifiable {
public void secureNotify();
public void secureNotifyAll();
public void secureWait();
}

View File

@ -14,7 +14,6 @@ import static megabasterd.MiscTools.HashBin;
import static megabasterd.MiscTools.swingReflectionInvoke;
import static megabasterd.MiscTools.updateFont;
/**
*
* @author tonikelope
@ -22,11 +21,11 @@ import static megabasterd.MiscTools.updateFont;
public class SetMegaMasterPasswordDialog extends javax.swing.JDialog {
private boolean _pass_ok;
private String _new_pass_hash;
private byte[] _new_pass;
private final String _salt;
public boolean isPass_ok() {
@ -36,14 +35,14 @@ public class SetMegaMasterPasswordDialog extends javax.swing.JDialog {
public byte[] getNew_pass() {
return _new_pass;
}
public void deleteNewPass() {
if(_new_pass != null) {
Arrays.fill(_new_pass, (byte)0);
if (_new_pass != null) {
Arrays.fill(_new_pass, (byte) 0);
}
_new_pass = null;
}
@ -57,25 +56,26 @@ public class SetMegaMasterPasswordDialog extends javax.swing.JDialog {
public SetMegaMasterPasswordDialog(java.awt.Frame parent, boolean modal, String salt) {
super(parent, modal);
initComponents();
MiscTools.swingInvokeIt(new Runnable(){
MiscTools.swingInvokeIt(new Runnable() {
@Override
public void run() {updateFont(new_pass_label, FONT_DEFAULT, Font.PLAIN);
updateFont(confirm_pass_label, FONT_DEFAULT, Font.PLAIN);
updateFont(ok_button, FONT_DEFAULT, Font.PLAIN);
updateFont(cancel_button, FONT_DEFAULT, Font.PLAIN);
updateFont(warning_label, FONT_DEFAULT, Font.PLAIN);
updateFont(status_label, FONT_DEFAULT, Font.PLAIN);}}, true);
public void run() {
updateFont(new_pass_label, FONT_DEFAULT, Font.PLAIN);
updateFont(confirm_pass_label, FONT_DEFAULT, Font.PLAIN);
updateFont(ok_button, FONT_DEFAULT, Font.PLAIN);
updateFont(cancel_button, FONT_DEFAULT, Font.PLAIN);
updateFont(warning_label, FONT_DEFAULT, Font.PLAIN);
updateFont(status_label, FONT_DEFAULT, Font.PLAIN);
}
}, true);
_pass_ok = false;
_new_pass = null;
_new_pass_hash = null;
_salt = salt;
}
@ -207,66 +207,66 @@ public class SetMegaMasterPasswordDialog extends javax.swing.JDialog {
}// </editor-fold>//GEN-END:initComponents
private void cancel_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancel_buttonActionPerformed
swingReflectionInvoke("setVisible", this, false);
}//GEN-LAST:event_cancel_buttonActionPerformed
private void ok_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ok_buttonActionPerformed
swingReflectionInvoke("setText", status_label, "Verifying your password, please wait...");
final Dialog tthis = this;
THREAD_POOL.execute(new Runnable(){
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
try {
if(Arrays.equals(new_pass_textfield.getPassword(), confirm_pass_textfield.getPassword())) {
swingReflectionInvoke("setText", status_label, "Processing your password, please wait...");
if(new_pass_textfield.getPassword().length > 0) {
try {
_new_pass = CryptTools.PBKDF2HMACSHA256(new String(new_pass_textfield.getPassword()), MiscTools.BASE642Bin(_salt), CryptTools.PBKDF2_ITERATIONS);
if (Arrays.equals(new_pass_textfield.getPassword(), confirm_pass_textfield.getPassword())) {
_new_pass_hash =Bin2BASE64(HashBin("SHA-1", _new_pass));
swingReflectionInvoke("setText", status_label, "Processing your password, please wait...");
if (new_pass_textfield.getPassword().length > 0) {
_new_pass = CryptTools.PBKDF2HMACSHA256(new String(new_pass_textfield.getPassword()), MiscTools.BASE642Bin(_salt), CryptTools.PBKDF2_ITERATIONS);
_new_pass_hash = Bin2BASE64(HashBin("SHA-1", _new_pass));
}
_pass_ok = true;
swingReflectionInvoke("setVisible", tthis, false);
} else {
JOptionPane.showMessageDialog(tthis, "Passwords does not match!", "Error", JOptionPane.ERROR_MESSAGE);
swingReflectionInvoke("setText", status_label, "");
swingReflectionInvoke("setText", new_pass_textfield, "");
swingReflectionInvoke("setText", confirm_pass_textfield, "");
swingReflectionInvoke("grabFocus", new_pass_textfield);
}
} catch (Exception ex) {
Logger.getLogger(SetMegaMasterPasswordDialog.class.getName()).log(Level.SEVERE, null, ex);
}
_pass_ok = true;
swingReflectionInvoke("setVisible", tthis, false);
} else {
JOptionPane.showMessageDialog(tthis, "Passwords does not match!", "Error", JOptionPane.ERROR_MESSAGE);
swingReflectionInvoke("setText", status_label, "");
swingReflectionInvoke("setText", new_pass_textfield, "");
swingReflectionInvoke("setText", confirm_pass_textfield, "");
swingReflectionInvoke("grabFocus", new_pass_textfield);
}
} catch (Exception ex) {
Logger.getLogger(SetMegaMasterPasswordDialog.class.getName()).log(Level.SEVERE, null, ex);
}
}});
});
}//GEN-LAST:event_ok_buttonActionPerformed
private void confirm_pass_textfieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_confirm_pass_textfieldKeyPressed
if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
ok_buttonActionPerformed(null);
}
}//GEN-LAST:event_confirm_pass_textfieldKeyPressed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancel_button;
private javax.swing.JLabel confirm_pass_label;

File diff suppressed because it is too large Load Diff

View File

@ -5,8 +5,8 @@ import java.util.logging.Level;
import static java.util.logging.Logger.getLogger;
import static megabasterd.MiscTools.formatBytes;
public final class SpeedMeter implements Runnable, SecureNotifiable
{
public final class SpeedMeter implements Runnable, SecureNotifiable {
public static final int SLEEP = 3000;
private long _progress;
private final Transference _transference;
@ -15,36 +15,32 @@ public final class SpeedMeter implements Runnable, SecureNotifiable
private volatile boolean _exit;
private final Object _secure_notify_lock;
private boolean _notified;
SpeedMeter(Transference transference, GlobalSpeedMeter gspeed)
{
SpeedMeter(Transference transference, GlobalSpeedMeter gspeed) {
_notified = false;
_secure_notify_lock = new Object();
_transference = transference;
_progress = transference.getProgress();
_lastSpeed=0;
_lastSpeed = 0;
_gspeed = gspeed;
_exit=false;
_exit = false;
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -52,138 +48,128 @@ public final class SpeedMeter implements Runnable, SecureNotifiable
getLogger(SpeedMeter.class.getName()).log(Level.SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
public void setExit(boolean exit) {
_exit = exit;
}
public long getLastSpeed()
{
public long getLastSpeed() {
return _lastSpeed;
}
public void setLastSpeed(long speed)
{
public void setLastSpeed(long speed) {
_lastSpeed = speed;
}
public void updateProgress() {
_progress = _transference.getProgress();
_progress = _transference.getProgress();
}
@Override
public void run()
{
public void run() {
System.out.println("SpeedMeter hello!");
long last_progress=_progress, sp;
long last_progress = _progress, sp;
int no_data_count;
_transference.getView().updateSpeed("------", true);
_transference.getView().updateRemainingTime("--d --:--:--", true);
try
{
no_data_count = 0;
while(!_exit)
{
Thread.sleep(SpeedMeter.SLEEP*(no_data_count+1));
if(!_exit)
{
updateProgress();
try {
no_data_count = 0;
if(_transference.isPaused()) {
while (!_exit) {
Thread.sleep(SpeedMeter.SLEEP * (no_data_count + 1));
_transference.getView().updateSpeed("------", true);
_transference.getView().updateRemainingTime("--d --:--:--", true);
if (!_exit) {
updateProgress();
setLastSpeed(0);
if (_transference.isPaused()) {
_transference.getView().updateSpeed("------", true);
_transference.getView().updateRemainingTime("--d --:--:--", true);
setLastSpeed(0);
_gspeed.secureNotify();
secureWait();
} else if (_progress > last_progress) {
double sleep_time = ((double) SpeedMeter.SLEEP * (no_data_count + 1)) / 1000;
double current_speed = (_progress - last_progress) / sleep_time;
last_progress = _progress;
sp = Math.round(current_speed);
if (sp > 0) {
_transference.getView().updateSpeed(formatBytes(sp) + "/s", true);
_transference.getView().updateRemainingTime(calculateRemTime((long) Math.floor((_transference.getFile_size() - _progress) / sp)), true);
setLastSpeed(sp);
_gspeed.secureNotify();
secureWait();
} else if( _progress > last_progress) {
double sleep_time = ((double)SpeedMeter.SLEEP*(no_data_count+1))/1000 ;
double current_speed = (_progress - last_progress) / sleep_time;
last_progress = _progress;
sp = Math.round(current_speed);
if(sp > 0) {
_transference.getView().updateSpeed(formatBytes(sp)+"/s", true);
_transference.getView().updateRemainingTime(calculateRemTime((long)Math.floor((_transference.getFile_size()-_progress)/sp ) ), true);
setLastSpeed(sp);
_gspeed.secureNotify();
}
no_data_count=0;
} else {
_transference.getView().updateSpeed("------", true);
_transference.getView().updateRemainingTime("--d --:--:--", true);
setLastSpeed(0);
_gspeed.secureNotify();
no_data_count++;
}
no_data_count = 0;
} else {
_transference.getView().updateSpeed("------", true);
_transference.getView().updateRemainingTime("--d --:--:--", true);
setLastSpeed(0);
_gspeed.secureNotify();
no_data_count++;
}
}
}
catch (InterruptedException ex)
{
}
} catch (InterruptedException ex) {
}
}
private String calculateRemTime(long seconds)
{
private String calculateRemTime(long seconds) {
int days = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) -
TimeUnit.DAYS.toHours(days);
long minutes = TimeUnit.SECONDS.toMinutes(seconds) -
TimeUnit.DAYS.toMinutes(days) -
TimeUnit.HOURS.toMinutes(hours);
long secs = TimeUnit.SECONDS.toSeconds(seconds) -
TimeUnit.DAYS.toSeconds(days) -
TimeUnit.HOURS.toSeconds(hours) -
TimeUnit.MINUTES.toSeconds(minutes);
long hours = TimeUnit.SECONDS.toHours(seconds)
- TimeUnit.DAYS.toHours(days);
long minutes = TimeUnit.SECONDS.toMinutes(seconds)
- TimeUnit.DAYS.toMinutes(days)
- TimeUnit.HOURS.toMinutes(hours);
long secs = TimeUnit.SECONDS.toSeconds(seconds)
- TimeUnit.DAYS.toSeconds(days)
- TimeUnit.HOURS.toSeconds(hours)
- TimeUnit.MINUTES.toSeconds(minutes);
return String.format("%dd %d:%02d:%02d", days, hours, minutes, secs);
}
}

View File

@ -11,33 +11,36 @@ import static java.util.logging.Logger.getLogger;
* @author tonikelope
*/
public final class SqliteSingleton {
public static final String SQLITE_FILE="megabasterd.db";
public static final String SQLITE_FILE = "megabasterd.db";
public static SqliteSingleton getInstance() {
return LazyHolder.INSTANCE;
}
private SqliteSingleton() {}
private SqliteSingleton() {
}
public Connection getConn() {
Connection conn=null;
Connection conn = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:"+SQLITE_FILE);
}catch(ClassNotFoundException | SQLException ex) {
conn = DriverManager.getConnection("jdbc:sqlite:" + SQLITE_FILE);
} catch (ClassNotFoundException | SQLException ex) {
getLogger(SqliteSingleton.class.getName()).log(Level.SEVERE, null, ex);
}
return conn;
}
private final static class LazyHolder {
private static final SqliteSingleton INSTANCE = new SqliteSingleton();
}

View File

@ -11,32 +11,32 @@ import static java.util.logging.Logger.getLogger;
public final class StreamThrottlerSupervisor implements Runnable, SecureNotifiable {
private final ConcurrentLinkedQueue<Integer> _input_slice_queue;
private final ConcurrentLinkedQueue<Integer> _output_slice_queue;
private final int _slice_size;
private volatile int _maxBytesPerSecInput;
private volatile int _maxBytesPerSecOutput;
private final Object _secure_notify_lock;
private boolean _notified;
public StreamThrottlerSupervisor(int maxBytesPerSecInput, int maxBytesPerSecOutput, int slice_size) {
_notified = false;
_secure_notify_lock = new Object();
_maxBytesPerSecInput = maxBytesPerSecInput;
_maxBytesPerSecOutput = maxBytesPerSecOutput;
_slice_size = slice_size;
_input_slice_queue = new ConcurrentLinkedQueue<>();
_output_slice_queue = new ConcurrentLinkedQueue<>();
}
@ -64,24 +64,21 @@ public final class StreamThrottlerSupervisor implements Runnable, SecureNotifiab
return _output_slice_queue;
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -89,63 +86,61 @@ public final class StreamThrottlerSupervisor implements Runnable, SecureNotifiab
getLogger(StreamThrottlerSupervisor.class.getName()).log(Level.SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
@Override
public void run() {
while(true) {
if(_maxBytesPerSecInput > 0) {
while (true) {
if (_maxBytesPerSecInput > 0) {
_input_slice_queue.clear();
int slice_num = (int)Math.floor((double)_maxBytesPerSecInput / _slice_size);
for(int i=0; i<slice_num; i++)
{
int slice_num = (int) Math.floor((double) _maxBytesPerSecInput / _slice_size);
for (int i = 0; i < slice_num; i++) {
_input_slice_queue.add(_slice_size);
}
if(_maxBytesPerSecInput % _slice_size != 0) {
if (_maxBytesPerSecInput % _slice_size != 0) {
_input_slice_queue.add(_maxBytesPerSecInput % _slice_size);
}
}
if(_maxBytesPerSecOutput > 0) {
}
if (_maxBytesPerSecOutput > 0) {
_output_slice_queue.clear();
int slice_num = (int)Math.floor((double)_maxBytesPerSecOutput / _slice_size);
for(int i=0; i<slice_num; i++)
{
int slice_num = (int) Math.floor((double) _maxBytesPerSecOutput / _slice_size);
for (int i = 0; i < slice_num; i++) {
_output_slice_queue.add(_slice_size);
}
if(_maxBytesPerSecOutput % _slice_size != 0) {
if (_maxBytesPerSecOutput % _slice_size != 0) {
_output_slice_queue.add(_maxBytesPerSecOutput % _slice_size);
}
}
}
secureNotifyAll();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {

View File

@ -11,7 +11,6 @@ import static java.util.logging.Logger.getLogger;
import javax.swing.JOptionPane;
import static megabasterd.MainPanel.FONT_DEFAULT;
import static megabasterd.MainPanel.THREAD_POOL;
import static megabasterd.MiscTools.copyTextToClipboard;
import static megabasterd.MiscTools.deflateURL;
import static megabasterd.MiscTools.extractFirstMegaLinkFromString;
import static megabasterd.MiscTools.extractStringFromClipboardContents;
@ -27,9 +26,10 @@ import static megabasterd.MiscTools.updateFont;
public final class StreamerDialog extends javax.swing.JDialog implements ClipboardChangeObserver {
private final ClipboardSpy _clipboardspy;
/**
* Creates new form Streamer
*
* @param clipboardspy
*/
public StreamerDialog(java.awt.Frame parent, boolean modal, ClipboardSpy clipboardspy) {
@ -37,16 +37,17 @@ public final class StreamerDialog extends javax.swing.JDialog implements Clipboa
initComponents();
_clipboardspy = clipboardspy;
MiscTools.swingInvokeIt(new Runnable(){
MiscTools.swingInvokeIt(new Runnable() {
@Override
public void run() {updateFont(put_label, FONT_DEFAULT, Font.PLAIN);
updateFont(dance_button, FONT_DEFAULT, Font.PLAIN);}}, true);
public void run() {
updateFont(put_label, FONT_DEFAULT, Font.PLAIN);
updateFont(dance_button, FONT_DEFAULT, Font.PLAIN);
}
}, true);
notifyClipboardChange();
}
@ -119,103 +120,102 @@ public final class StreamerDialog extends javax.swing.JDialog implements Clipboa
}// </editor-fold>//GEN-END:initComponents
private void dance_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dance_buttonActionPerformed
dance_button.setEnabled(false);
original_link_textfield.setEnabled(false);
final Dialog tthis = this;
THREAD_POOL.execute(new Runnable(){
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
boolean error=false;
String stream_link=null;
String link=((String)swingReflectionInvokeAndWaitForReturn("getText", original_link_textfield)).trim();
if(link.length() > 0) {
boolean error = false;
try {
String stream_link = null;
link = CryptTools.decryptMegaDownloaderLink(link);
String link = ((String) swingReflectionInvokeAndWaitForReturn("getText", original_link_textfield)).trim();
} catch (Exception ex) {
getLogger(StreamerDialog.class.getName()).log(Level.SEVERE, null, ex);
}
if (link.length() > 0) {
String data;
try {
link=link.replace("/#!N?", "/#N!");
link = CryptTools.decryptMegaDownloaderLink(link);
if( findFirstRegex("://mega(\\.co)?\\.nz/#[^fF]", link, 0) != null)
{
data=findFirstRegex("/#(N?!.+)", link, 1);
} catch (Exception ex) {
getLogger(StreamerDialog.class.getName()).log(Level.SEVERE, null, ex);
}
stream_link = "http://localhost:1337/video/mega/"+data;
String data;
} else if( (data=findFirstRegex("https?://([^/]+/![^!]+![0-9a-fA-F]+)", link, 1)) != null) {
link = link.replace("/#!N?", "/#N!");
stream_link = "http://localhost:1337/video/"+data;
if (findFirstRegex("://mega(\\.co)?\\.nz/#[^fF]", link, 0) != null) {
data = findFirstRegex("/#(N?!.+)", link, 1);
} else {
stream_link = "http://localhost:1337/video/mega/" + data;
} else if ((data = findFirstRegex("https?://([^/]+/![^!]+![0-9a-fA-F]+)", link, 1)) != null) {
stream_link = "http://localhost:1337/video/" + data;
} else {
error = true;
}
error = true;
}
} else {
error = true;
}
if(error) {
if (error) {
JOptionPane.showMessageDialog(tthis, "Please, paste a mega/megacrypter link!", "Error", JOptionPane.ERROR_MESSAGE);
swingReflectionInvoke("setText", original_link_textfield, "");
swingReflectionInvoke("setEnabled", dance_button, true);
swingReflectionInvoke("setEnabled", original_link_textfield, true);
} else {
try {
copyTextToClipboard(deflateURL(stream_link));
MiscTools.copyTextToClipboard(deflateURL(stream_link));
JOptionPane.showMessageDialog(tthis, "Streaming link was copied to clipboard!\n(Remember to keep MegaBasterd running in background while playing)");
dispose();
getParent().dispatchEvent(new WindowEvent(tthis, WINDOW_CLOSING));
} catch (IOException ex) {
Logger.getLogger(StreamerDialog.class.getName()).log(Level.SEVERE, null, ex);
}
}
}});
}
});
}//GEN-LAST:event_dance_buttonActionPerformed
@Override
public void notifyClipboardChange() {
String link = extractFirstMegaLinkFromString(extractStringFromClipboardContents(_clipboardspy.getContents()));
if(!link.contains("/#F!")) {
swingReflectionInvoke("setText", original_link_textfield, link);
if (!link.contains("/#F!")) {
swingReflectionInvoke("setText", original_link_textfield, link);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton dance_button;
private javax.swing.JTextField original_link_textfield;
private javax.swing.JLabel put_label;
// End of variables declaration//GEN-END:variables
}
}

View File

@ -17,7 +17,6 @@ public final class ThrottledInputStream extends InputStream {
private boolean _stream_finish;
public ThrottledInputStream(InputStream rawStream, StreamThrottlerSupervisor stream_supervisor) {
_rawStream = rawStream;
@ -29,23 +28,22 @@ public final class ThrottledInputStream extends InputStream {
_slice_size = null;
}
@Override
public int read() throws IOException {
if(_stream_supervisor.getMaxBytesPerSecInput() > 0) {
if (_stream_supervisor.getMaxBytesPerSecInput() > 0) {
if(!_stream_finish) {
if (!_stream_finish) {
int r;
throttle(1);
if(_slice_size != null) {
if (_slice_size != null) {
r = _rawStream.read();
if(r == -1) {
if (r == -1) {
_stream_finish = true;
}
@ -69,46 +67,45 @@ public final class ThrottledInputStream extends InputStream {
}
@Override
public int read(byte[] b) throws IOException {
if(_stream_supervisor.getMaxBytesPerSecInput() > 0) {
if (_stream_supervisor.getMaxBytesPerSecInput() > 0) {
if(!_stream_finish) {
if (!_stream_finish) {
int readLen = 0, readSlice, len=b.length, r=0;
int readLen = 0, readSlice, len = b.length, r = 0;
do {
throttle(len - readLen);
if(_slice_size != null) {
if (_slice_size != null) {
readSlice=0;
readSlice = 0;
do{
r = _rawStream.read(b, readLen+readSlice, _slice_size-readSlice );
do {
r = _rawStream.read(b, readLen + readSlice, _slice_size - readSlice);
if(r!=-1){
if (r != -1) {
readSlice+=r;
readSlice += r;
} else {
_stream_finish = true;
}
}while(r != -1 && readSlice < _slice_size);
} while (r != -1 && readSlice < _slice_size);
readLen+=readSlice;
readLen += readSlice;
} else {
return _rawStream.read(b);
}
}while( r != -1 && readLen < len );
} while (r != -1 && readLen < len);
return readLen;
@ -123,47 +120,46 @@ public final class ThrottledInputStream extends InputStream {
}
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if(_stream_supervisor.getMaxBytesPerSecInput() > 0) {
if (_stream_supervisor.getMaxBytesPerSecInput() > 0) {
if(!_stream_finish) {
if (!_stream_finish) {
int readLen = 0, r=0;
int readLen = 0, r = 0;
do {
throttle(len-readLen);
throttle(len - readLen);
if(_slice_size != null) {
if (_slice_size != null) {
int readSlice=0;
int readSlice = 0;
do{
r = _rawStream.read(b, off+readSlice+readLen, _slice_size - readSlice);
do {
r = _rawStream.read(b, off + readSlice + readLen, _slice_size - readSlice);
if(r!=-1){
if (r != -1) {
readSlice+=r;
readSlice += r;
} else {
_stream_finish = true;
}
}while(r!=-1 && readSlice<_slice_size);
} while (r != -1 && readSlice < _slice_size);
readLen+=readSlice;
readLen += readSlice;
} else {
r = _rawStream.read(b, off+readLen, len-readLen);
r = _rawStream.read(b, off + readLen, len - readLen);
if(r!=-1){
if (r != -1) {
readLen+=r;
readLen += r;
} else {
@ -171,7 +167,7 @@ public final class ThrottledInputStream extends InputStream {
}
}
}while( r!=-1 && readLen < len );
} while (r != -1 && readLen < len);
return readLen;
@ -186,7 +182,6 @@ public final class ThrottledInputStream extends InputStream {
}
}
@Override
public void reset() throws IOException {
@ -197,17 +192,16 @@ public final class ThrottledInputStream extends InputStream {
}
private void throttle(int size) throws IOException {
_slice_size = null;
while(_stream_supervisor.getMaxBytesPerSecInput() > 0 && (_slice_size=_stream_supervisor.getInput_slice_queue().poll()) == null) {
while (_stream_supervisor.getMaxBytesPerSecInput() > 0 && (_slice_size = _stream_supervisor.getInput_slice_queue().poll()) == null) {
_stream_supervisor.secureWait();
}
if(_slice_size != null && size < _slice_size) {
if (_slice_size != null && size < _slice_size) {
_stream_supervisor.getInput_slice_queue().add(_slice_size - size);

View File

@ -15,7 +15,6 @@ public final class ThrottledOutputStream extends OutputStream {
private Integer slice_size;
public ThrottledOutputStream(OutputStream rawStream, StreamThrottlerSupervisor stream_supervisor) {
_rawStream = rawStream;
@ -26,32 +25,31 @@ public final class ThrottledOutputStream extends OutputStream {
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if(_stream_supervisor.getMaxBytesPerSecOutput() > 0) {
if (_stream_supervisor.getMaxBytesPerSecOutput() > 0) {
int writeLen=0;
int writeLen = 0;
do {
throttle(len-writeLen);
throttle(len - writeLen);
if(slice_size != null) {
if (slice_size != null) {
_rawStream.write(b, off+writeLen, slice_size);
_rawStream.write(b, off + writeLen, slice_size);
writeLen+=slice_size;
writeLen += slice_size;
} else {
_rawStream.write(b, off+writeLen, len-writeLen);
_rawStream.write(b, off + writeLen, len - writeLen);
writeLen = len;
}
}while( writeLen < len );
} while (writeLen < len);
} else {
@ -62,7 +60,7 @@ public final class ThrottledOutputStream extends OutputStream {
@Override
public void write(int i) throws IOException {
if(_stream_supervisor.getMaxBytesPerSecOutput() > 0) {
if (_stream_supervisor.getMaxBytesPerSecOutput() > 0) {
throttle(1);
@ -74,17 +72,16 @@ public final class ThrottledOutputStream extends OutputStream {
}
}
private void throttle(int size) throws IOException {
slice_size = null;
while(_stream_supervisor.getMaxBytesPerSecOutput() > 0 && (slice_size=_stream_supervisor.getOutput_slice_queue().poll()) == null) {
while (_stream_supervisor.getMaxBytesPerSecOutput() > 0 && (slice_size = _stream_supervisor.getOutput_slice_queue().poll()) == null) {
_stream_supervisor.secureWait();
}
if(slice_size != null && size < slice_size) {
if (slice_size != null && size < slice_size) {
_stream_supervisor.getOutput_slice_queue().add(slice_size - size);

View File

@ -7,48 +7,49 @@ import java.util.concurrent.ConcurrentLinkedQueue;
* @author tonikelope
*/
public interface Transference {
int MIN_WORKERS = 2;
int MAX_WORKERS = 20;
int MAX_SIM_TRANSFERENCES=20;
int MAX_SIM_TRANSFERENCES = 20;
boolean USE_SLOTS_DEFAULT = false;
int WORKERS_DEFAULT = 4;
int SIM_TRANSFERENCES_DEFAULT=2;
boolean LIMIT_TRANSFERENCE_SPEED_DEFAULT=false;
int MAX_TRANSFERENCE_SPEED_DEFAULT=5;
int SIM_TRANSFERENCES_DEFAULT = 2;
boolean LIMIT_TRANSFERENCE_SPEED_DEFAULT = false;
int MAX_TRANSFERENCE_SPEED_DEFAULT = 5;
int MAX_WAIT_WORKERS_SHUTDOWN = 10;
void start();
void stop();
void pause();
void restart();
void close();
boolean isPaused();
boolean isStopped();
void checkSlotsAndWorkers();
ConcurrentLinkedQueue<Integer> getPartialProgress();
long getProgress();
void setProgress(long progress);
String getFile_name();
long getFile_size();
SpeedMeter getSpeed_meter();
ProgressMeter getProgress_meter();
MainPanel getMain_panel();
TransferenceView getView();
}

View File

@ -17,7 +17,7 @@ import static megabasterd.MiscTools.swingReflectionInvokeAndWaitForReturn;
* @author tonikelope
*/
abstract public class TransferenceManager implements Runnable, SecureNotifiable {
private final ConcurrentLinkedQueue<Transference> _transference_provision_queue;
private final ConcurrentLinkedQueue<Transference> _transference_waitstart_queue;
private final ConcurrentLinkedQueue<Transference> _transference_remove_queue;
@ -38,13 +38,14 @@ abstract public class TransferenceManager implements Runnable, SecureNotifiable
private volatile boolean _starting_transferences;
private volatile boolean _preprocessing_transferences;
private volatile int _pre_count;
public TransferenceManager(MainPanel main_panel, int max_running_trans, javax.swing.JLabel status, javax.swing.JPanel scroll_panel, javax.swing.JButton close_all_button, javax.swing.JButton pause_all_button, javax.swing.MenuElement clean_all_menu) {
_notified = false;
_removing_transferences = false;
_provisioning_transferences = false;
_starting_transferences=false;
_preprocessing_transferences=false;
_pre_count=0;
_starting_transferences = false;
_preprocessing_transferences = false;
_pre_count = 0;
_main_panel = main_panel;
_max_running_trans = max_running_trans;
_scroll_panel = scroll_panel;
@ -62,9 +63,9 @@ abstract public class TransferenceManager implements Runnable, SecureNotifiable
}
abstract public void provision(Transference transference);
abstract public void remove(Transference transference);
public boolean isRemoving_transferences() {
return _removing_transferences;
}
@ -98,10 +99,10 @@ abstract public class TransferenceManager implements Runnable, SecureNotifiable
}
public synchronized void addPre_count(int pre_count) {
_pre_count+=pre_count;
if(_pre_count <0) {
_pre_count += pre_count;
if (_pre_count < 0) {
_pre_count = 0;
}
}
@ -109,26 +110,22 @@ abstract public class TransferenceManager implements Runnable, SecureNotifiable
public void setMax_running_trans(int _max_running_trans) {
this._max_running_trans = _max_running_trans;
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -140,14 +137,14 @@ abstract public class TransferenceManager implements Runnable, SecureNotifiable
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
@ -159,11 +156,11 @@ abstract public class TransferenceManager implements Runnable, SecureNotifiable
public int getPre_count() {
return _pre_count;
}
public boolean isPreprocessing_transferences() {
return _preprocessing_transferences;
}
public ConcurrentLinkedQueue<Transference> getTransference_provision_queue() {
return _transference_provision_queue;
}
@ -187,18 +184,16 @@ abstract public class TransferenceManager implements Runnable, SecureNotifiable
public JPanel getScroll_panel() {
return _scroll_panel;
}
public void closeAllFinished()
{
public void closeAllFinished() {
_transference_remove_queue.addAll(new ArrayList(_transference_finished_queue));
_transference_finished_queue.clear();
secureNotify();
}
public void closeAllPreProWaiting()
{
public void closeAllPreProWaiting() {
_transference_preprocess_queue.clear();
_pre_count = 0;
@ -211,217 +206,216 @@ abstract public class TransferenceManager implements Runnable, SecureNotifiable
secureNotify();
}
public void start(Transference transference) {
_transference_running_list.add(transference);
_scroll_panel.add((Component)transference.getView(), 0);
_scroll_panel.add((Component) transference.getView(), 0);
transference.start();
secureNotify();
}
public void pauseAll()
{
for(Transference transference:_transference_running_list) {
if(!transference.isPaused()) {
public void pauseAll() {
for (Transference transference : _transference_running_list) {
if (!transference.isPaused()) {
transference.pause();
}
}
secureNotify();
}
public void sortTransferenceStartQueue()
{
public void sortTransferenceStartQueue() {
ArrayList<Transference> trans_list = new ArrayList(_transference_waitstart_queue);
trans_list.sort(new Comparator<Transference> () {
trans_list.sort(new Comparator<Transference>() {
@Override
public int compare(Transference o1, Transference o2) {
return o1.getFile_name().compareToIgnoreCase(o2.getFile_name());
}
@Override
public int compare(Transference o1, Transference o2) {
return o1.getFile_name().compareToIgnoreCase(o2.getFile_name());
}
});
_transference_waitstart_queue.clear();
_transference_waitstart_queue.addAll(trans_list);
}
private void updateView() {
if(!_transference_running_list.isEmpty()) {
if (!_transference_running_list.isEmpty()) {
boolean show_pause_all = false;
for(Transference trans:_transference_running_list) {
if((show_pause_all = !trans.isPaused())) {
for (Transference trans : _transference_running_list) {
if ((show_pause_all = !trans.isPaused())) {
break;
}
}
swingReflectionInvoke("setVisible", _pause_all_button, show_pause_all);
} else {
swingReflectionInvoke("setVisible", _pause_all_button, false);
}
swingReflectionInvoke("setEnabled", _clean_all_menu, !_transference_preprocess_queue.isEmpty() || !_transference_provision_queue.isEmpty() || !_transference_waitstart_queue.isEmpty());
if(!_transference_finished_queue.isEmpty()) {
swingReflectionInvoke("setText", _close_all_button, "Close all finished ("+_transference_finished_queue.size()+")" );
swingReflectionInvoke("setEnabled", _clean_all_menu, !_transference_preprocess_queue.isEmpty() || !_transference_provision_queue.isEmpty() || !_transference_waitstart_queue.isEmpty());
if (!_transference_finished_queue.isEmpty()) {
swingReflectionInvoke("setText", _close_all_button, "Close all finished (" + _transference_finished_queue.size() + ")");
swingReflectionInvoke("setVisible", _close_all_button, true);
} else {
swingReflectionInvoke("setVisible", _close_all_button, false);
}
swingReflectionInvoke("setText", _status, genStatus());
}
private String genStatus() {
int prov = _transference_provision_queue.size();
int rem = _transference_remove_queue.size();
int wait = _transference_waitstart_queue.size();
int run = _transference_running_list.size();
int finish = _transference_finished_queue.size();
if(finish > 0 && _pre_count+prov+wait+run == 0 && !(boolean)swingReflectionInvokeAndWaitForReturn("isVisible", _main_panel.getView())) {
if (finish > 0 && _pre_count + prov + wait + run == 0 && !(boolean) swingReflectionInvokeAndWaitForReturn("isVisible", _main_panel.getView())) {
swingReflectionInvoke("displayMessage", _main_panel.getTrayicon(), "MegaBasterd says:", "All your transferences have finished", TrayIcon.MessageType.INFO);
}
return (_pre_count+prov+rem+wait+run+finish > 0)?"Pre: "+_pre_count+" / Pro: "+prov+" / Wait: "+wait+" / Run: "+run+" / Finish: "+finish+" / Rem: "+rem:"";
return (_pre_count + prov + rem + wait + run + finish > 0) ? "Pre: " + _pre_count + " / Pro: " + prov + " / Wait: " + wait + " / Run: " + run + " / Finish: " + finish + " / Rem: " + rem : "";
}
@Override
public void run() {
while(true)
{
if(!isPreprocessing_transferences() && !getTransference_preprocess_queue().isEmpty()) {
while (true) {
if (!isPreprocessing_transferences() && !getTransference_preprocess_queue().isEmpty()) {
setPreprocessing_transferences(true);
THREAD_POOL.execute(new Runnable(){
@Override
public void run(){
while(!getTransference_preprocess_queue().isEmpty())
{
Runnable run = getTransference_preprocess_queue().poll();
if(run != null) {
run.run();
}
}
setPreprocessing_transferences(false);
secureNotify();
}});
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
while (!getTransference_preprocess_queue().isEmpty()) {
Runnable run = getTransference_preprocess_queue().poll();
if (run != null) {
run.run();
}
}
setPreprocessing_transferences(false);
secureNotify();
}
});
}
if(!isProvisioning_transferences() && !getTransference_provision_queue().isEmpty()) {
if (!isProvisioning_transferences() && !getTransference_provision_queue().isEmpty()) {
setProvisioning_transferences(true);
THREAD_POOL.execute(new Runnable(){
@Override
public void run(){
while(!getTransference_provision_queue().isEmpty())
{
Transference transference = getTransference_provision_queue().poll();
if(transference != null) {
provision(transference);
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
}
}
setProvisioning_transferences(false);
secureNotify();
}});
while (!getTransference_provision_queue().isEmpty()) {
Transference transference = getTransference_provision_queue().poll();
if (transference != null) {
provision(transference);
}
}
setProvisioning_transferences(false);
secureNotify();
}
});
}
if(!isRemoving_transferences() && !getTransference_remove_queue().isEmpty()) {
if (!isRemoving_transferences() && !getTransference_remove_queue().isEmpty()) {
setRemoving_transferences(true);
THREAD_POOL.execute(new Runnable(){
@Override
public void run(){
while(!getTransference_remove_queue().isEmpty()) {
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
Transference transference = getTransference_remove_queue().poll();
while (!getTransference_remove_queue().isEmpty()) {
if(transference != null) {
remove(transference);
}
}
setRemoving_transferences(false);
secureNotify();
}});
Transference transference = getTransference_remove_queue().poll();
if (transference != null) {
remove(transference);
}
}
setRemoving_transferences(false);
secureNotify();
}
});
}
if(!isStarting_transferences() && !getTransference_waitstart_queue().isEmpty() && getTransference_running_list().size() < _max_running_trans) {
if (!isStarting_transferences() && !getTransference_waitstart_queue().isEmpty() && getTransference_running_list().size() < _max_running_trans) {
setStarting_transferences(true);
THREAD_POOL.execute(new Runnable(){
@Override
public void run(){
while(!getTransference_waitstart_queue().isEmpty() && getTransference_running_list().size() < _max_running_trans) {
Transference transference = getTransference_waitstart_queue().poll();
if(transference != null) {
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
start(transference);
}
}
setStarting_transferences(false);
secureNotify();
}});
while (!getTransference_waitstart_queue().isEmpty() && getTransference_running_list().size() < _max_running_trans) {
Transference transference = getTransference_waitstart_queue().poll();
if (transference != null) {
start(transference);
}
}
setStarting_transferences(false);
secureNotify();
}
});
}
updateView();
secureWait();
}
}
}
}

View File

@ -5,16 +5,25 @@ package megabasterd;
* @author tonikelope
*/
public interface TransferenceView {
void pause();
void stop();
void resume();
void updateSpeed(String speed, Boolean visible);
void updateRemainingTime(String rem_time, Boolean visible);
void updateProgressBar(long progress, double bar_rate);
void updateSlotsStatus();
void printStatusNormal(String msg);
void printStatusOK(String msg);
void printStatusError(String msg);
}

File diff suppressed because it is too large Load Diff

View File

@ -25,12 +25,13 @@ import static megabasterd.MiscTools.i32a2bin;
public final class UploadMACGenerator implements Runnable, SecureNotifiable {
private long _last_chunk_id_read;
private final ConcurrentHashMap<Long,Chunk> _chunk_queue;
private final ConcurrentHashMap<Long, Chunk> _chunk_queue;
private final Upload _upload;
private final Object _secure_notify_lock;
private boolean _notified;
private volatile boolean _exit;
private long _bytes_read;
public UploadMACGenerator(Upload upload) {
_secure_notify_lock = new Object();
_notified = false;
@ -38,27 +39,24 @@ public final class UploadMACGenerator implements Runnable, SecureNotifiable {
_chunk_queue = new ConcurrentHashMap();
_bytes_read = _upload.getProgress();
_last_chunk_id_read = _upload.getLast_chunk_id_dispatched();
_exit=false;
_exit = false;
}
@Override
public void secureNotify()
{
synchronized(_secure_notify_lock) {
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized(_secure_notify_lock)
{
while(!_notified) {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait();
@ -66,18 +64,18 @@ public final class UploadMACGenerator implements Runnable, SecureNotifiable {
getLogger(UploadMACGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void secureNotifyAll() {
synchronized(_secure_notify_lock) {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notifyAll();
}
}
@ -105,114 +103,106 @@ public final class UploadMACGenerator implements Runnable, SecureNotifiable {
public void setExit(boolean exit) {
_exit = exit;
}
@Override
public void run() {
try{
File temp_file = new File("."+HashString("SHA-1", _upload.getFile_name()));
FileOutputStream temp_file_out;
try {
File temp_file = new File("." + HashString("SHA-1", _upload.getFile_name()));
FileOutputStream temp_file_out;
Chunk chunk;
int[] file_iv = bin2i32a(_upload.getByte_file_iv()), int_block, file_mac = _upload.getSaved_file_mac(), mac_iv = CryptTools.AES_ZERO_IV_I32A;
int reads;
byte[] byte_block = new byte[16];
String temp_file_data = "";
boolean new_chunk=false;
boolean new_chunk = false;
while(!_exit && (!_upload.isStopped() || !_upload.getChunkworkers().isEmpty()) && (_bytes_read < _upload.getFile_size() || (_upload.getFile_size() == 0 && _last_chunk_id_read < 1)))
{
while(_chunk_queue.containsKey(_last_chunk_id_read+1))
{
chunk = _chunk_queue.get(_last_chunk_id_read+1);
try
{
while (!_exit && (!_upload.isStopped() || !_upload.getChunkworkers().isEmpty()) && (_bytes_read < _upload.getFile_size() || (_upload.getFile_size() == 0 && _last_chunk_id_read < 1))) {
while (_chunk_queue.containsKey(_last_chunk_id_read + 1)) {
chunk = _chunk_queue.get(_last_chunk_id_read + 1);
try {
int[] chunk_mac = {file_iv[0], file_iv[1], file_iv[0], file_iv[1]};
InputStream chunk_is = chunk.getInputStream();
while( (reads=chunk_is.read(byte_block)) != -1 )
{
if(reads<byte_block.length)
{
for(int i=reads; i<byte_block.length; i++)
byte_block[i]=0;
while ((reads = chunk_is.read(byte_block)) != -1) {
if (reads < byte_block.length) {
for (int i = reads; i < byte_block.length; i++) {
byte_block[i] = 0;
}
}
int_block = bin2i32a(byte_block);
for(int i=0; i<chunk_mac.length; i++)
{
chunk_mac[i]^=int_block[i];
for (int i = 0; i < chunk_mac.length; i++) {
chunk_mac[i] ^= int_block[i];
}
chunk_mac = CryptTools.aes_cbc_encrypt_ia32(chunk_mac, bin2i32a(_upload.getByte_file_key()), mac_iv);
}
for(int i=0; i<file_mac.length; i++)
{
file_mac[i]^=chunk_mac[i];
for (int i = 0; i < file_mac.length; i++) {
file_mac[i] ^= chunk_mac[i];
}
file_mac = CryptTools.aes_cbc_encrypt_ia32(file_mac, bin2i32a(_upload.getByte_file_key()), mac_iv);
_bytes_read+=chunk.getSize();
} catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) {
_bytes_read += chunk.getSize();
} catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) {
getLogger(UploadMACGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
_chunk_queue.remove(chunk.getId());
_last_chunk_id_read = chunk.getId();
new_chunk = true;
}
if(new_chunk) {
temp_file_data = (String.valueOf(_last_chunk_id_read)+"|"+String.valueOf(_bytes_read)+"|"+Bin2BASE64(i32a2bin(file_mac)));
System.out.println("Macgenerator -> "+temp_file_data);
if (new_chunk) {
temp_file_data = (String.valueOf(_last_chunk_id_read) + "|" + String.valueOf(_bytes_read) + "|" + Bin2BASE64(i32a2bin(file_mac)));
System.out.println("Macgenerator -> " + temp_file_data);
temp_file_out = new FileOutputStream(temp_file);
temp_file_out.write(temp_file_data.getBytes());
temp_file_out.close();
new_chunk = false;
}
if(!_exit && (!_upload.isStopped() || !_upload.getChunkworkers().isEmpty()) && (_bytes_read < _upload.getFile_size() || (_upload.getFile_size() == 0 && _last_chunk_id_read < 1)))
{
if (!_exit && (!_upload.isStopped() || !_upload.getChunkworkers().isEmpty()) && (_bytes_read < _upload.getFile_size() || (_upload.getFile_size() == 0 && _last_chunk_id_read < 1))) {
System.out.println("METAMAC wait...");
secureWait();
}
}
if(_bytes_read == _upload.getFile_size()) {
int[] meta_mac={file_mac[0]^file_mac[1], file_mac[2]^file_mac[3]};
}
if (_bytes_read == _upload.getFile_size()) {
int[] meta_mac = {file_mac[0] ^ file_mac[1], file_mac[2] ^ file_mac[3]};
_upload.setFile_meta_mac(meta_mac);
}
temp_file.delete();
_upload.secureNotify();
System.out.println("MAC GENERATOR BYE BYE...");
} catch (Exception ex) {
getLogger(UploadMACGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

View File

@ -8,80 +8,76 @@ import static java.util.logging.Logger.getLogger;
import static megabasterd.DBTools.deleteUpload;
import static megabasterd.MiscTools.HashString;
/**
*
* @author tonikelope
*/
public final class UploadManager extends TransferenceManager {
public UploadManager(MainPanel main_panel) {
super(main_panel, main_panel.getMax_ul(), main_panel.getView().getStatus_up_label(), main_panel.getView().getjPanel_scroll_up(), main_panel.getView().getClose_all_finished_up_button(), main_panel.getView().getPause_all_up_button(), main_panel.getView().getClean_all_up_menu());
}
@Override
public void provision(Transference upload)
{
getScroll_panel().add(((Upload)upload).getView());
((Upload)upload).provisionIt();
if(((Upload)upload).isProvision_ok()) {
@Override
public void provision(Transference upload) {
getScroll_panel().add(((Upload) upload).getView());
((Upload) upload).provisionIt();
if (((Upload) upload).isProvision_ok()) {
getTransference_waitstart_queue().add(upload);
if(getTransference_provision_queue().isEmpty()) {
if (getTransference_provision_queue().isEmpty()) {
sortTransferenceStartQueue();
for(Transference up:getTransference_waitstart_queue()) {
for (Transference up : getTransference_waitstart_queue()) {
getScroll_panel().remove((Component)up.getView());
getScroll_panel().add((Component)up.getView());
getScroll_panel().remove((Component) up.getView());
getScroll_panel().add((Component) up.getView());
}
for(Transference up:getTransference_finished_queue()) {
for (Transference up : getTransference_finished_queue()) {
getScroll_panel().remove((Component)up.getView());
getScroll_panel().add((Component)up.getView());
getScroll_panel().remove((Component) up.getView());
getScroll_panel().add((Component) up.getView());
}
}
}
} else {
getTransference_finished_queue().add(upload);
}
secureNotify();
}
@Override
public void remove(Transference upload) {
getScroll_panel().remove(((Upload)upload).getView());
getScroll_panel().remove(((Upload) upload).getView());
getTransference_waitstart_queue().remove(upload);
getTransference_running_list().remove(upload);
getTransference_finished_queue().remove(upload);
if(((Upload)upload).isProvision_ok()) {
if (((Upload) upload).isProvision_ok()) {
try {
deleteUpload(upload.getFile_name(), ((Upload)upload).getMa().getEmail());
deleteUpload(upload.getFile_name(), ((Upload) upload).getMa().getEmail());
} catch (SQLException ex) {
getLogger(UploadManager.class.getName()).log(SEVERE, null, ex);
}
try {
File temp_file = new File("."+HashString("SHA-1", upload.getFile_name()));
File temp_file = new File("." + HashString("SHA-1", upload.getFile_name()));
if(temp_file.exists()) {
if (temp_file.exists()) {
temp_file.delete();
}
@ -93,5 +89,5 @@ public final class UploadManager extends TransferenceManager {
secureNotify();
}
}
}

View File

@ -11,7 +11,6 @@ import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import static megabasterd.MainPanel.FONT_DEFAULT;
import static megabasterd.MainPanel.THREAD_POOL;
import static megabasterd.MiscTools.copyTextToClipboard;
import static megabasterd.MiscTools.swingReflectionInvoke;
import static megabasterd.MiscTools.swingReflectionInvokeAndWait;
import static megabasterd.MiscTools.updateFont;
@ -82,45 +81,44 @@ public final class UploadView extends javax.swing.JPanel implements Transference
return status_label;
}
public UploadView(Upload upload){
public UploadView(Upload upload) {
initComponents();
_upload = upload;
MiscTools.swingInvokeIt(new Runnable(){
MiscTools.swingInvokeIt(new Runnable() {
@Override
public void run() {
updateFont(status_label, FONT_DEFAULT, BOLD);
updateFont(remtime_label, FONT_DEFAULT, PLAIN);
updateFont(speed_label, FONT_DEFAULT, BOLD);
updateFont(progress_pbar, FONT_DEFAULT, PLAIN);
updateFont(slots_label, FONT_DEFAULT, BOLD);
updateFont(slots_spinner, FONT_DEFAULT, PLAIN);
updateFont(pause_button, FONT_DEFAULT, BOLD);
updateFont(stop_button, FONT_DEFAULT, BOLD);
updateFont(folder_link_button, FONT_DEFAULT, PLAIN);
updateFont(file_link_button, FONT_DEFAULT, PLAIN);
updateFont(file_name_label, FONT_DEFAULT, PLAIN);
updateFont(file_size_label, FONT_DEFAULT, BOLD);
updateFont(close_button, FONT_DEFAULT, PLAIN);
updateFont(restart_button, FONT_DEFAULT, PLAIN);
updateFont(slot_status_label, FONT_DEFAULT, BOLD);
}}, true);
updateFont(status_label, FONT_DEFAULT, BOLD);
updateFont(remtime_label, FONT_DEFAULT, PLAIN);
updateFont(speed_label, FONT_DEFAULT, BOLD);
updateFont(progress_pbar, FONT_DEFAULT, PLAIN);
updateFont(slots_label, FONT_DEFAULT, BOLD);
updateFont(slots_spinner, FONT_DEFAULT, PLAIN);
updateFont(pause_button, FONT_DEFAULT, BOLD);
updateFont(stop_button, FONT_DEFAULT, BOLD);
updateFont(folder_link_button, FONT_DEFAULT, PLAIN);
updateFont(file_link_button, FONT_DEFAULT, PLAIN);
updateFont(file_name_label, FONT_DEFAULT, PLAIN);
updateFont(file_size_label, FONT_DEFAULT, BOLD);
updateFont(close_button, FONT_DEFAULT, PLAIN);
updateFont(restart_button, FONT_DEFAULT, PLAIN);
updateFont(slot_status_label, FONT_DEFAULT, BOLD);
}
}, true);
swingReflectionInvokeAndWait("setModel", slots_spinner, new SpinnerNumberModel(_upload.getMain_panel().getDefault_slots_up(), MIN_WORKERS, MAX_WORKERS, 1));
swingReflectionInvoke("setEditable", ((JSpinner.DefaultEditor)slots_spinner.getEditor()).getTextField(), false);
swingReflectionInvoke("setVisible", new Object[]{slots_spinner, slots_label,pause_button,stop_button,speed_label,remtime_label,progress_pbar,file_name_label,close_button,restart_button,file_size_label}, false);
swingReflectionInvoke("setForeground", speed_label, new Color(0,128,255));
swingReflectionInvoke("setEditable", ((JSpinner.DefaultEditor) slots_spinner.getEditor()).getTextField(), false);
swingReflectionInvoke("setVisible", new Object[]{slots_spinner, slots_label, pause_button, stop_button, speed_label, remtime_label, progress_pbar, file_name_label, close_button, restart_button, file_size_label}, false);
swingReflectionInvoke("setForeground", speed_label, new Color(0, 128, 255));
}
/**
@ -326,11 +324,11 @@ public final class UploadView extends javax.swing.JPanel implements Transference
private void slots_spinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_slots_spinnerStateChanged
THREAD_POOL.execute(new Runnable(){
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
_upload.checkSlotsAndWorkers();
}
});
@ -341,33 +339,32 @@ public final class UploadView extends javax.swing.JPanel implements Transference
}//GEN-LAST:event_close_buttonActionPerformed
private void restart_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restart_buttonActionPerformed
_upload.restart();
}//GEN-LAST:event_restart_buttonActionPerformed
private void stop_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stop_buttonActionPerformed
_upload.stop();
}//GEN-LAST:event_stop_buttonActionPerformed
private void pause_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pause_buttonActionPerformed
_upload.pause();
}//GEN-LAST:event_pause_buttonActionPerformed
public void hideAllExceptStatus()
{
swingReflectionInvoke("setVisible", new Object[]{speed_label, remtime_label, slots_spinner, slots_label,slot_status_label,pause_button,stop_button,progress_pbar}, false);
public void hideAllExceptStatus() {
swingReflectionInvoke("setVisible", new Object[]{speed_label, remtime_label, slots_spinner, slots_label, slot_status_label, pause_button, stop_button, progress_pbar}, false);
}
private void folder_link_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_folder_link_buttonActionPerformed
folder_link_button.setEnabled(false);
folder_link_button.setText("Please wait...");
copyTextToClipboard(_upload.getFolder_link());
MiscTools.copyTextToClipboard(_upload.getFolder_link());
folder_link_button.setText("Copy folder link");
@ -379,44 +376,43 @@ public final class UploadView extends javax.swing.JPanel implements Transference
private void file_link_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_file_link_buttonActionPerformed
file_link_button.setEnabled(false);
file_link_button.setText("Please wait...");
copyTextToClipboard(_upload.getFile_link());
MiscTools.copyTextToClipboard(_upload.getFile_link());
file_link_button.setText("Copy file link");
JOptionPane.showMessageDialog(_upload.getMain_panel().getView(), "MEGA file link was copied to clipboard!");
file_link_button.setEnabled(true);
}//GEN-LAST:event_file_link_buttonActionPerformed
}//GEN-LAST:event_file_link_buttonActionPerformed
@Override
public void pause() {
printStatusNormal("Pausing upload ...");
swingReflectionInvoke("setEnabled", new Object[]{pause_button,speed_label,slots_label,slots_spinner}, false);
swingReflectionInvoke("setEnabled", new Object[]{pause_button, speed_label, slots_label, slots_spinner}, false);
swingReflectionInvoke("setVisible", stop_button, true);
}
@Override
public void stop() {
printStatusNormal("Stopping upload safely, please wait...");
swingReflectionInvoke("setEnabled", new Object[]{pause_button,stop_button,speed_label,slots_label,slots_spinner}, false);
swingReflectionInvoke("setEnabled", new Object[]{pause_button, stop_button, speed_label, slots_label, slots_spinner}, false);
}
@Override
public void resume() {
printStatusNormal("Uploading file to mega ...");
swingReflectionInvoke("setEnabled", new Object[]{pause_button,speed_label,slots_label,slots_spinner}, true);
swingReflectionInvoke("setEnabled", new Object[]{pause_button, speed_label, slots_label, slots_spinner}, true);
swingReflectionInvoke("setVisible", stop_button, false);
swingReflectionInvoke("setText", pause_button, "PAUSE UPLOAD");
swingReflectionInvoke("setVisible", _upload.getMain_panel().getView().getPause_all_up_button(), true);
@ -424,36 +420,36 @@ public final class UploadView extends javax.swing.JPanel implements Transference
@Override
public void updateSpeed(String sp, Boolean visible) {
if(sp != null) {
if (sp != null) {
swingReflectionInvoke("setText", speed_label, sp);
}
if(visible != null) {
if (visible != null) {
swingReflectionInvoke("setVisible", speed_label, visible);
}
}
@Override
public void updateRemainingTime(String remtime, Boolean visible) {
if(remtime != null) {
if (remtime != null) {
swingReflectionInvoke("setText", remtime_label, remtime);
}
if(visible != null) {
if (visible != null) {
swingReflectionInvoke("setVisible", remtime_label, visible);
}
}
@Override
public void updateProgressBar(long progress, double bar_rate) {
swingReflectionInvoke("setValue", progress_pbar, (int)Math.ceil(bar_rate*progress));
swingReflectionInvoke("setValue", progress_pbar, (int) Math.ceil(bar_rate * progress));
}
@Override
@ -464,53 +460,52 @@ public final class UploadView extends javax.swing.JPanel implements Transference
@Override
public void printStatusOK(String msg) {
swingReflectionInvoke("setForeground", status_label, new Color(0,128,0));
swingReflectionInvoke("setForeground", status_label, new Color(0, 128, 0));
swingReflectionInvoke("setText", status_label, msg);
}
@Override
public void printStatusError(String msg) {
swingReflectionInvoke("setForeground", status_label, Color.red);
swingReflectionInvoke("setText", status_label, msg);
}
@Override
@Override
public synchronized void updateSlotsStatus() {
int conta_exit = 0;
for(ChunkUploader c:_upload.getChunkworkers()) {
if(c.isExit()) {
for (ChunkUploader c : _upload.getChunkworkers()) {
if (c.isExit()) {
conta_exit++;
}
}
int conta_error = 0;
for(ChunkUploader c:_upload.getChunkworkers()) {
if(c.isError_wait()) {
for (ChunkUploader c : _upload.getChunkworkers()) {
if (c.isError_wait()) {
conta_error++;
}
}
if(conta_error > 0) {
if (conta_error > 0) {
swingReflectionInvoke("setForeground", slot_status_label, Color.red);
} else {
swingReflectionInvoke("setForeground", slot_status_label, Color.black);
}
swingReflectionInvoke("setText", slot_status_label, (conta_exit>0?"Removing: "+conta_exit:"") + (conta_error>0?((conta_exit>0?" / ":"")+"Error: " + conta_error):""));
swingReflectionInvoke("setText", slot_status_label, (conta_exit > 0 ? "Removing: " + conta_exit : "") + (conta_error > 0 ? ((conta_exit > 0 ? " / " : "") + "Error: " + conta_error) : ""));
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton close_button;
private javax.swing.JButton file_link_button;