diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 5b39c61..4a2a092 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -20,20 +20,6 @@ android:supportsRtl="true" android:theme="@style/Theme.AsgardiusS3Manager" tools:targetApi="31" > - - - - - - - - - - - - - - objects = (List) s3client.listObjects(bucket, "/"); - ObjectListing result = s3client.listObjects(orequest); - ArrayList objectl = new ArrayList(); - List objects = result.getObjectSummaries(); - for (S3ObjectSummary os : objects) { - objectl.add(os.getKey()); - } - if (objectl.size() >= 1) { - DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucket).withKeys(objectl.toArray(new String[0])); - s3client.deleteObjects(deleteObjectsRequest); - } - while (result.isTruncated()) { - objectl = new ArrayList(); - result = s3client.listNextBatchOfObjects (result); - objects = result.getObjectSummaries(); - for (S3ObjectSummary os : objects) { - objectl.add(os.getKey()); - //i++; - } - DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucket).withKeys(objectl.toArray(new String[0])); - s3client.deleteObjects(deleteObjectsRequest); - - } - //System.out.println("bucket items: " + objectl.size()); - s3client.deleteBucket(bucket); - runOnUiThread(new Runnable() { - - @Override - public void run() { - // Sending reference and data to Adapter - Toast.makeText(getApplicationContext(),getResources().getString(R.string.bucket_del_success), Toast.LENGTH_SHORT).show(); - recreate(); - - } - }); - //System.out.println("tree "+treelevel); - //System.out.println("prefix "+prefix); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - finish(); - } - } - }); - simpleProgressBar.setVisibility(View.VISIBLE); - deleteBucket.start(); - } - }); - builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - } - }); - AlertDialog dialog = builder.create(); - dialog.show(); - } - - private void upload(String bucket, boolean isfolder) { - Intent intent = new Intent(this, Uploader.class); - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("bucket", bucket); - intent.putExtra("prefix", prefix); - intent.putExtra("region", location); - intent.putExtra("style", style); - intent.putExtra("isfolder", isfolder); - startActivity(intent); - } - - private void objectInfo(String bucket) { - - Intent intent = new Intent(this, ObjectInfo.class); - //treelevel ++; - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("bucket", bucket); - intent.putExtra("region", location); - intent.putExtra("style", style); - startActivity(intent); - - } - - private void newBucket() { - Intent intent = new Intent(this, CreateBucket.class); - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("region", location); - intent.putExtra("style", style); - //startActivity(intent); - ((Activity) this).startActivityForResult(intent, 25); - } - - private void download(String bucket) { - - Intent intent = new Intent(this, Downloader.class); - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("prefix", prefix); - intent.putExtra("region", location); - intent.putExtra("style", style); - intent.putExtra("bucket", bucket); - intent.putExtra("isfolder", true); - startActivity(intent); - } - - private void corsConfig(String bucket) { - Intent intent = new Intent(this, CorsConfig.class); - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("bucket", bucket); - intent.putExtra("region", location); - intent.putExtra("style", style); - intent.putExtra("pdfendpoint", pdfendpoint); - startActivity(intent); - } - - private void policyConfig(String bucket) { - Intent intent = new Intent(this, BucketPolicy.class); - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("bucket", bucket); - intent.putExtra("region", location); - intent.putExtra("style", style); - intent.putExtra("pdfendpoint", pdfendpoint); - startActivity(intent); - } - - public void copyName (String name) { - ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip = ClipData.newPlainText("name", name); - clipboard.setPrimaryClip(clip); - if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.copy_ok), Toast.LENGTH_SHORT).show(); - } - } - - public void onActivityResult(int requestCode, int resultCode, final Intent resultData) { - // The ACTION_OPEN_DOCUMENT intent was sent with the request code OPEN_DIRECTORY_REQUEST_CODE. - // If the request code seen here doesn't match, it's the response to some other intent, - // and the below code shouldn't run at all. - super.onActivityResult(requestCode, resultCode, resultData); - if(requestCode == 25 && resultCode == 25) { - recreate(); - } - } - } \ No newline at end of file diff --git a/app/src/main/java/asgardius/page/s3music/CorsConfig.java b/app/src/main/java/asgardius/page/s3music/CorsConfig.java deleted file mode 100644 index 827f5a2..0000000 --- a/app/src/main/java/asgardius/page/s3music/CorsConfig.java +++ /dev/null @@ -1,278 +0,0 @@ -package asgardius.page.s3music; - -import android.os.Bundle; -import android.view.View; -import android.widget.Button; -import android.widget.ProgressBar; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.appcompat.app.AppCompatActivity; - -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Region; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3Client; -import com.amazonaws.services.s3.S3ClientOptions; -import com.amazonaws.services.s3.model.BucketCrossOriginConfiguration; -import com.amazonaws.services.s3.model.CORSRule; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; - -public class CorsConfig extends AppCompatActivity { - String username, password, endpoint, bucket, location; - URI pdfendpoint; - Region region; - S3ClientOptions s3ClientOptions; - AWSCredentials myCredentials; - AmazonS3 s3client; - ProgressBar simpleProgressBar; - BucketCrossOriginConfiguration bucketcors; - boolean style; - boolean allorigins, pdfcompatible, found = false; - TextView origins; - Button allowall, allowpdf, deletecors; - BucketCrossOriginConfiguration corsconfig; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_cors_config); - simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar); - endpoint = getIntent().getStringExtra("endpoint"); - username = getIntent().getStringExtra("username"); - password = getIntent().getStringExtra("password"); - bucket = getIntent().getStringExtra("bucket"); - style = getIntent().getBooleanExtra("style", false); - location = getIntent().getStringExtra("region"); - allowall = (Button)findViewById(R.id.allow_all); - allowpdf = (Button)findViewById(R.id.allow_pdf); - deletecors = (Button)findViewById(R.id.delete_cors); - try { - pdfendpoint = new URI(getIntent().getStringExtra("pdfendpoint")); - } catch (URISyntaxException e) { - e.printStackTrace(); - } - getSupportActionBar().setTitle(bucket+"/"); - region = Region.getRegion(location); - s3ClientOptions = S3ClientOptions.builder().build(); - myCredentials = new BasicAWSCredentials(username, password); - origins = (TextView) findViewById(R.id.origins); - try { - s3client = new AmazonS3Client(myCredentials, region); - } catch (Exception e) { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - s3client.setEndpoint(endpoint); - s3ClientOptions.setPathStyleAccess(style); - s3client.setS3ClientOptions(s3ClientOptions); - Thread getCors = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - bucketcors = s3client.getBucketCrossOriginConfiguration(bucket); - if (bucketcors != null) { - List corsRules = bucketcors.getRules(); - if (!corsRules.isEmpty()) { - found = true; - for (CORSRule rule: corsRules) { - //System.out.println("allowOrigins: "+rule.getAllowedOrigins()); - //System.out.println("AllowedMethod: "+rule.getAllowedMethods()); - if (rule.getAllowedOrigins().toString().equals("[*]")) { - allorigins = true; - } else if (rule.getAllowedOrigins().toString().contains("https://"+pdfendpoint.getHost())) { - pdfcompatible = true; - } - } - } - } - - runOnUiThread(new Runnable() { - - @Override - public void run() { - simpleProgressBar.setVisibility(View.INVISIBLE); - if (allorigins) { - origins.setText(getResources().getString(R.string.cors_all)); - deletecors.setVisibility(View.VISIBLE); - } else if (pdfcompatible) { - origins.setText(getResources().getString(R.string.cors_pdf)); - deletecors.setVisibility(View.VISIBLE); - allowall.setVisibility(View.VISIBLE); - } else if (found) { - origins.setText(getResources().getString(R.string.cors_npdf)); - deletecors.setVisibility(View.VISIBLE); - allowpdf.setVisibility(View.VISIBLE); - allowall.setVisibility(View.VISIBLE); - } else { - origins.setText(getResources().getString(R.string.cors_none)); - allowall.setVisibility(View.VISIBLE); - allowpdf.setVisibility(View.VISIBLE); - } - } - }); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - finish(); - } - } - }); - getCors.start(); - allowall.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - simpleProgressBar.setVisibility(View.VISIBLE); - setAllowall(); - } - }); - allowpdf.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - simpleProgressBar.setVisibility(View.VISIBLE); - setAllowpdf(); - } - }); - deletecors.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - simpleProgressBar.setVisibility(View.VISIBLE); - setDeletecors(); - } - }); - } - - private void setAllowall() { - Thread addAll = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - List allowMethods = new ArrayList<>(); - allowMethods.add(CORSRule.AllowedMethods.GET); - List allowOrigins = new ArrayList<>(); - allowOrigins.add("*"); - CORSRule corsRules = new CORSRule().withAllowedMethods(allowMethods).withAllowedOrigins(allowOrigins); - corsconfig = new BucketCrossOriginConfiguration().withRules(corsRules); - s3client.setBucketCrossOriginConfiguration(bucket, corsconfig); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.policy_ok), Toast.LENGTH_SHORT).show(); - finish(); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - simpleProgressBar.setVisibility(View.INVISIBLE); - Toast.makeText(getApplicationContext(),getResources().getString(R.string.policy_error), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - } - } - }); - addAll.start(); - } - - private void setAllowpdf() { - Thread addPdf = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - List allowMethods = new ArrayList<>(); - allowMethods.add(CORSRule.AllowedMethods.GET); - List allowOrigins = new ArrayList<>(); - allowOrigins.add("https://"+pdfendpoint.getHost()); - CORSRule corsRules = new CORSRule().withAllowedMethods(allowMethods).withAllowedOrigins(allowOrigins); - corsconfig = new BucketCrossOriginConfiguration().withRules(corsRules); - s3client.setBucketCrossOriginConfiguration(bucket, corsconfig); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.policy_ok), Toast.LENGTH_SHORT).show(); - finish(); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - simpleProgressBar.setVisibility(View.INVISIBLE); - Toast.makeText(getApplicationContext(),getResources().getString(R.string.policy_error), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - } - } - }); - addPdf.start(); - } - - private void setDeletecors() { - Thread delCors = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - s3client.deleteBucketCrossOriginConfiguration(bucket); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.policy_ok), Toast.LENGTH_SHORT).show(); - finish(); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - simpleProgressBar.setVisibility(View.INVISIBLE); - Toast.makeText(getApplicationContext(),getResources().getString(R.string.policy_error), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - } - } - }); - delCors.start(); - } -} \ No newline at end of file diff --git a/app/src/main/java/asgardius/page/s3music/CreateBucket.java b/app/src/main/java/asgardius/page/s3music/CreateBucket.java deleted file mode 100644 index c4bb389..0000000 --- a/app/src/main/java/asgardius/page/s3music/CreateBucket.java +++ /dev/null @@ -1,110 +0,0 @@ -package asgardius.page.s3music; - -import android.os.Bundle; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ProgressBar; -import android.widget.Toast; - -import androidx.appcompat.app.AppCompatActivity; - -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Region; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3Client; -import com.amazonaws.services.s3.S3ClientOptions; - -public class CreateBucket extends AppCompatActivity { - String username, password, endpoint, bucket, location; - boolean style; - EditText bname; - Region region; - S3ClientOptions s3ClientOptions; - AWSCredentials myCredentials; - AmazonS3 s3client; - ProgressBar simpleProgressBar; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_create_bucket); - endpoint = getIntent().getStringExtra("endpoint"); - username = getIntent().getStringExtra("username"); - password = getIntent().getStringExtra("password"); - location = getIntent().getStringExtra("region"); - style = getIntent().getBooleanExtra("style", false); - region = Region.getRegion("us-east-1"); - s3ClientOptions = S3ClientOptions.builder().build(); - s3ClientOptions.setPathStyleAccess(style); - myCredentials = new BasicAWSCredentials(username, password); - s3client = new AmazonS3Client(myCredentials, region); - s3client.setEndpoint(endpoint); - s3client.setS3ClientOptions(s3ClientOptions); - bname = (EditText)findViewById(R.id.bname); - Button cbucket = (Button)findViewById(R.id.cbucket); - simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar); - cbucket.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - bucket = bname.getText().toString(); - if (bucket.equals("")) { - Toast.makeText(CreateBucket.this, getResources().getString(R.string.bucket_name_empty), Toast.LENGTH_SHORT).show(); - } else { - //Toast.makeText(CreateBucket.this, getResources().getString(R.string.pending_feature), Toast.LENGTH_SHORT).show(); - Thread newBucket = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - s3client.createBucket(bucket, location); - runOnUiThread(new Runnable() { - - @Override - public void run() { - // Sending reference and data to Adapter - setResult(25); - Toast.makeText(getApplicationContext(),getResources().getString(R.string.create_bucket_success), Toast.LENGTH_SHORT).show(); - finish(); - //mainmenu(); - - } - }); - //System.out.println("tree "+treelevel); - //System.out.println("prefix "+prefix); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - finish(); - } - } - }); - simpleProgressBar.setVisibility(View.VISIBLE); - newBucket.start(); - } - } - - }); - - } - - /*private void mainmenu() { - - Intent intent = new Intent(this, MainActivity.class); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - intent.putExtra("EXIT", true); - startActivity(intent); - - }*/ -} \ No newline at end of file diff --git a/app/src/main/java/asgardius/page/s3music/Downloader.java b/app/src/main/java/asgardius/page/s3music/Downloader.java deleted file mode 100644 index c9c7d3c..0000000 --- a/app/src/main/java/asgardius/page/s3music/Downloader.java +++ /dev/null @@ -1,358 +0,0 @@ -package asgardius.page.s3music; - -import static android.content.ContentValues.TAG; - -import androidx.appcompat.app.AppCompatActivity; -import androidx.documentfile.provider.DocumentFile; - -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.database.Cursor; -import android.net.Uri; -import android.net.wifi.WifiManager; -import android.os.Bundle; -import android.os.PowerManager; -import android.provider.MediaStore; -import android.util.Log; -import android.view.View; -import android.widget.Button; -import android.widget.ProgressBar; -import android.widget.Toast; - -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Region; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3Client; -import com.amazonaws.services.s3.S3ClientOptions; -import com.amazonaws.services.s3.model.ListObjectsRequest; -import com.amazonaws.services.s3.model.ObjectListing; -import com.amazonaws.services.s3.model.S3Object; -import com.amazonaws.services.s3.model.S3ObjectSummary; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -public class Downloader extends AppCompatActivity { - String username, password, endpoint, bucket, filename, prefix, location; - Uri fileuri, filepath; - Region region; - String[] folder; - S3ClientOptions s3ClientOptions; - AWSCredentials myCredentials; - AmazonS3 s3client; - ProgressBar simpleProgressBar; - ListObjectsRequest orequest; - Intent intent; - Button fileDownload; - Thread downloadFile, downloadProgress; - S3Object object; - DocumentFile document; - boolean started = false; - boolean cancel = false; - boolean style, isfolder; - long filesize = 0; - long objectsize; - long transfered = 0; - private WifiManager.WifiLock mWifiLock; - private PowerManager.WakeLock mWakeLock; - private PowerManager powerManager; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_downloader); - // create Wifi and wake locks - mWifiLock = ((WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "Transistor:wifi_lock"); - powerManager = (PowerManager) getSystemService(POWER_SERVICE); - mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Transistor:wake_lock"); - filename = getIntent().getStringExtra("filename"); - endpoint = getIntent().getStringExtra("endpoint"); - username = getIntent().getStringExtra("username"); - password = getIntent().getStringExtra("password"); - bucket = getIntent().getStringExtra("bucket"); - location = getIntent().getStringExtra("region"); - style = getIntent().getBooleanExtra("style", false); - isfolder = getIntent().getBooleanExtra("isfolder", false); - prefix = getIntent().getStringExtra("prefix"); - if(isfolder) { - getSupportActionBar().setTitle(getResources().getString(R.string.download_files)); - } else { - getSupportActionBar().setTitle(getResources().getString(R.string.download_file)); - } - simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar); - fileDownload = (Button)findViewById(R.id.filedownload); - region = Region.getRegion(location); - s3ClientOptions = S3ClientOptions.builder().build(); - s3ClientOptions.setPathStyleAccess(style); - myCredentials = new BasicAWSCredentials(username, password); - s3client = new AmazonS3Client(myCredentials, region); - s3client.setEndpoint(endpoint); - s3client.setS3ClientOptions(s3ClientOptions); - performFileSearch("Select download location"); - fileDownload.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - if (started) { - cancel = true; - downloadFile.interrupt(); - //simpleProgressBar.setVisibility(View.INVISIBLE); - } else { - downloadFile(); - } - } - - }); - } - - private void downloadFile () { - started = true; - simpleProgressBar.setVisibility(View.VISIBLE); - //fileDownload.setEnabled(false); - fileDownload.setText(getResources().getString(R.string.cancel_download)); - //Acquiring WakeLock and WifiLock if not held - if (!mWifiLock.isHeld()) { - mWifiLock.acquire(); - //System.out.println("WifiLock acquired"); - } - if (!mWakeLock.isHeld()) { - mWakeLock.acquire(); - //System.out.println("WakeLock acquired"); - } - downloadFile = new Thread(new Runnable() { - - @Override - public void run() { - simpleProgressBar.setVisibility(View.VISIBLE); - try { - //Your code goes here - //s3client.createBucket(bucket, location); - //System.out.println(fkey); - if (isfolder) { - if (prefix == null) { - orequest = new ListObjectsRequest().withBucketName(bucket).withMaxKeys(1000); - } else { - orequest = new ListObjectsRequest().withBucketName(bucket).withPrefix(prefix).withMaxKeys(1000); - } - ArrayList objectlist = new ArrayList(); - ObjectListing result = s3client.listObjects(orequest); - List objects = result.getObjectSummaries(); - for (S3ObjectSummary os : objects) { - objectlist.add(os.getKey()); - objectsize = os.getSize(); - if (objectsize%1024 == 0) { - filesize = filesize+(objectsize/1024); - } else { - filesize = filesize+(objectsize/1024)+1; - } - } - while (result.isTruncated()) { - result = s3client.listNextBatchOfObjects (result); - objects = result.getObjectSummaries(); - for (S3ObjectSummary os : objects) { - objectlist.add(os.getKey()); - objectsize = os.getSize(); - if (objectsize%1024 == 0) { - filesize = filesize+(objectsize/1024); - } else { - filesize = filesize+(objectsize/1024)+1; - } - } - - } - for (String os : objectlist) { - document = DocumentFile.fromTreeUri(getApplicationContext(), fileuri); - object = s3client.getObject(bucket, os); - if (os.replace(prefix, "").contains("/")) { - folder = os.replace(prefix, "").split("/"); - for (int i = 0; i < folder.length-1; i++) { - DocumentFile subfolder = document.findFile(folder[i].replace("/", "")); - if (subfolder != null) { - document = subfolder; - } else { - document = document.createDirectory(folder[i].replace("/", "")); - } - } - filepath = document.createFile(null, folder[folder.length-1]).getUri(); - } else { - filepath = document.createFile(null, os.replace(prefix, "")).getUri(); - } - writeContentToFile(filepath, object); - } - } else { - object = s3client.getObject(bucket, prefix+filename); - filesize = (object.getObjectMetadata().getContentLength())/1024; - writeContentToFile(fileuri, object); - } - runOnUiThread(new Runnable() { - @Override - public void run() { - //simpleProgressBar.setProgress(100); - //Releasing WifiLock and WakeLock if held - if (mWifiLock.isHeld()) { - mWifiLock.release(); - //System.out.println("WifiLock released"); - } - if (mWakeLock.isHeld()) { - mWakeLock.release(); - //System.out.println("WakeLock released"); - } - simpleProgressBar.setProgress(100); - if (isfolder) { - fileDownload.setText(getResources().getString(R.string.batch_download_success)); - } else { - fileDownload.setText(getResources().getString(R.string.download_success)); - } - fileDownload.setEnabled(false); - //simpleProgressBar.setVisibility(View.INVISIBLE); - } - }); - //System.out.println("tree "+treelevel); - //System.out.println("prefix "+prefix); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - //Releasing WifiLock and WakeLock if held - if (mWifiLock.isHeld()) { - mWifiLock.release(); - //System.out.println("WifiLock released"); - } - if (mWakeLock.isHeld()) { - mWakeLock.release(); - //System.out.println("WakeLock released"); - } - if (cancel) { - fileDownload.setText(getResources().getString(R.string.download_canceled)); - } else { - fileDownload.setText(getResources().getString(R.string.download_failed)); - } - fileDownload.setEnabled(false); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - //finish(); - } - } - }); - downloadProgress = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - while (fileDownload.isEnabled()) { - try { - if (filesize != 0) { - simpleProgressBar.setProgress((int)((transfered*100)/filesize)); - } - Thread.sleep(500); - } catch (Exception e) { - e.printStackTrace(); - } - } - - } catch (Exception e) { - e.printStackTrace(); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - //finish(); - } - } - }); - downloadFile.start(); - downloadProgress.start(); - } - - private void performFileSearch(String messageTitle) { - //uri = Uri.parse("content://com.android.externalstorage.documents/document/home"); - intent = new Intent(); - if (isfolder) { - intent.setAction(Intent.ACTION_OPEN_DOCUMENT_TREE); - } else { - intent.setAction(Intent.ACTION_CREATE_DOCUMENT); - //intent.addCategory(Intent.CATEGORY_OPENABLE); - //intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); - //intent.putExtra("android.provider.extra.INITIAL_URI", uri); - intent.putExtra(Intent.EXTRA_TITLE, filename); - intent.setType("*/*"); - } - ((Activity) this).startActivityForResult(intent, 50); - } - - @Override - - public void onDestroy() { - if (!mWifiLock.isHeld()) { - mWifiLock.acquire(); - //System.out.println("WifiLock acquired"); - } - if (!mWakeLock.isHeld()) { - mWakeLock.acquire(); - //System.out.println("WakeLock acquired"); - } - super.onDestroy(); - } - - public void onActivityResult(int requestCode, int resultCode, final Intent resultData) { - // The ACTION_OPEN_DOCUMENT intent was sent with the request code OPEN_DIRECTORY_REQUEST_CODE. - // If the request code seen here doesn't match, it's the response to some other intent, - // and the below code shouldn't run at all. - super.onActivityResult(requestCode, resultCode, resultData); - if (requestCode == 50) { - if (resultCode == Activity.RESULT_OK) { - // The document selected by the user won't be returned in the intent. - // Instead, a URI to that document will be contained in the return intent - // provided to this method as a parameter. Pull that uri using "resultData.getData()" - if (resultData != null && resultData.getData() != null) { - fileuri = resultData.getData(); - System.out.println(fileuri.toString()); - downloadFile(); - //System.out.println("File selected successfully"); - //System.out.println("content://com.android.externalstorage.documents"+file.getPath()); - } else { - Toast.makeText(Downloader.this, getResources().getString(R.string.file_path_fail), Toast.LENGTH_SHORT).show(); - finish(); - } - } else { - //System.out.println("User cancelled file browsing {}"); - finish(); - } - } - } - - private void writeContentToFile(Uri uri, S3Object object) throws IOException { - try ( - final InputStream in = object.getObjectContent(); - final OutputStream out = getContentResolver().openOutputStream(uri); - ) { - byte[] buffer = new byte[1024]; - for (int len; (len = in.read(buffer)) != -1; ) { - out.write(buffer, 0, len); - transfered ++; - } - } - } - - private String getDisplayName(Uri uri) { - final String[] projection = { MediaStore.Images.Media.DISPLAY_NAME }; - try ( - Cursor cursor = getContentResolver().query(uri, projection, null, null, null); - ){ - int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME); - if (cursor.moveToFirst()) { - return cursor.getString(columnIndex); - } - } - // If the display name is not found for any reason, use the Uri path as a fallback. - Log.w(TAG, "Couldnt determine DISPLAY_NAME for Uri. Falling back to Uri path: " + uri.getPath()); - return uri.getPath(); - } -} \ No newline at end of file diff --git a/app/src/main/java/asgardius/page/s3music/ImageViewer.java b/app/src/main/java/asgardius/page/s3music/ImageViewer.java deleted file mode 100644 index 6a3cc44..0000000 --- a/app/src/main/java/asgardius/page/s3music/ImageViewer.java +++ /dev/null @@ -1,136 +0,0 @@ -package asgardius.page.s3music; - -import android.annotation.SuppressLint; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.os.Bundle; -import android.view.MotionEvent; -import android.view.View; -import android.view.WindowManager; -import android.widget.ProgressBar; -import android.widget.Toast; - -import androidx.appcompat.app.AppCompatActivity; - -import com.otaliastudios.zoom.ZoomImageView; - -import java.net.URL; - -public class ImageViewer extends AppCompatActivity { - String videoURL, title; - ZoomImageView iv; - boolean controls = false; - float cursorx, cursory; - - @SuppressLint("ClickableViewAccessibility") - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_image_viewer); - videoURL = getIntent().getStringExtra("video_url"); - title = getIntent().getStringExtra("title"); - getSupportActionBar().setTitle(title); - final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar); - iv = (ZoomImageView) findViewById(R.id.imageViewer); - //System.out.println(videoURL); - Thread imgread = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - URL thumb_u = new URL(videoURL); - Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src"); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - simpleProgressBar.setVisibility(View.INVISIBLE); - iv.setImageDrawable(thumb_d); - - } - }); - - } catch (OutOfMemoryError e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.picture_too_big), Toast.LENGTH_SHORT).show(); - finish(); - } - }); - finish(); - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - finish(); - } - }); - finish(); - } - } - }); - imgread.start(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; - } - iv.setOnTouchListener((v, event) -> { - - if (event.getAction() == MotionEvent.ACTION_DOWN) { - cursorx = event.getX(); - cursory = event.getY(); - iv.performClick(); - - return true; - } else if (event.getAction() == MotionEvent.ACTION_UP) { - if(Math.abs(event.getX() - cursorx) < 5 || Math.abs(event.getY() - cursory) < 5) { - if(controls) { - controls = false; - hideSystemBars(); - } - else { - controls = true; - showSystemBars(); - } - } - return true; - } - return false; - }); - } - - @Override - public void onWindowFocusChanged(boolean hasFocus) { - super.onWindowFocusChanged(hasFocus); - controls = false; - hideSystemBars(); - - } - - private void hideSystemBars() { - // Set the IMMERSIVE flag. - // Set the content to appear under the system bars so that the content - // doesn't resize when the system bars hide and show. - View decorView = getWindow().getDecorView(); - decorView.setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar - | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar - | View.SYSTEM_UI_FLAG_IMMERSIVE); - } - - private void showSystemBars() { - View decorView = getWindow().getDecorView(); - decorView.setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE); - } -} \ No newline at end of file diff --git a/app/src/main/java/asgardius/page/s3music/ObjectInfo.java b/app/src/main/java/asgardius/page/s3music/ObjectInfo.java deleted file mode 100644 index 5666175..0000000 --- a/app/src/main/java/asgardius/page/s3music/ObjectInfo.java +++ /dev/null @@ -1,150 +0,0 @@ -package asgardius.page.s3music; - -import android.os.Bundle; -import android.view.View; -import android.widget.ProgressBar; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.appcompat.app.AppCompatActivity; - -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Region; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3Client; -import com.amazonaws.services.s3.S3ClientOptions; -import com.amazonaws.services.s3.model.ListObjectsRequest; -import com.amazonaws.services.s3.model.ObjectListing; -import com.amazonaws.services.s3.model.S3ObjectSummary; - -import java.util.List; - -public class ObjectInfo extends AppCompatActivity { - String username, password, endpoint, bucket, object, location, title; - Region region; - S3ClientOptions s3ClientOptions; - AWSCredentials myCredentials; - AmazonS3 s3client; - ProgressBar simpleProgressBar; - TextView filesize, filesizeinfo, objectcount; - boolean isobject, isfolder, style; - long totalSize = 0; - int totalItems = 0; - ListObjectsRequest orequest; - long KiB, MiB, GiB; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_object_info); - KiB = 1024; - MiB = 1024 * KiB; - GiB = 1024 * MiB; - simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar); - filesize = (TextView) findViewById(R.id.size); - filesizeinfo = (TextView) findViewById(R.id.size_info); - objectcount = (TextView) findViewById(R.id.object_count); - endpoint = getIntent().getStringExtra("endpoint"); - title = getIntent().getStringExtra("title"); - username = getIntent().getStringExtra("username"); - password = getIntent().getStringExtra("password"); - bucket = getIntent().getStringExtra("bucket"); - style = getIntent().getBooleanExtra("style", false); - location = getIntent().getStringExtra("region"); - object = getIntent().getStringExtra("object"); - if (object == null) { - getSupportActionBar().setTitle(bucket+"/"); - } else { - getSupportActionBar().setTitle(title); - } - region = Region.getRegion(location); - s3ClientOptions = S3ClientOptions.builder().build(); - myCredentials = new BasicAWSCredentials(username, password); - try { - s3client = new AmazonS3Client(myCredentials, region); - } catch (Exception e) { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - s3client.setEndpoint(endpoint); - s3ClientOptions.setPathStyleAccess(style); - s3client.setS3ClientOptions(s3ClientOptions); - Thread getInfo = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - if (object == null) { - isobject = false; - orequest = new ListObjectsRequest().withBucketName(bucket).withMaxKeys(1000); - } else { - isobject = true; - if (object.endsWith("/")) { - isfolder = true; - } else { - isfolder = false; - } - orequest = new ListObjectsRequest().withBucketName(bucket).withPrefix(object).withMaxKeys(1000); - } - ObjectListing result = s3client.listObjects(orequest); - List objects = result.getObjectSummaries(); - for (S3ObjectSummary os : objects) { - totalSize += os.getSize(); - totalItems++; - } - while (result.isTruncated()) { - result = s3client.listNextBatchOfObjects (result); - objects = result.getObjectSummaries(); - for (S3ObjectSummary os : objects) { - totalSize += os.getSize(); - totalItems++; - } - - } - - runOnUiThread(new Runnable() { - - @Override - public void run() { - if (isobject) { - if (isfolder) { - filesizeinfo.setText(getResources().getString(R.string.folder_size)); - objectcount.setText(totalItems+" "+getResources().getString(R.string.file_count)); - } else { - filesizeinfo.setText(getResources().getString(R.string.file_size)); - } - } else { - filesizeinfo.setText(getResources().getString(R.string.bucket_size)); - objectcount.setText(totalItems+" "+getResources().getString(R.string.file_count)); - } - if (totalSize >= GiB) { - filesize.setText(Long.toString(totalSize/GiB)+" GiB"); - } else if (totalSize >= MiB) { - filesize.setText(Long.toString(totalSize/MiB)+" MiB"); - } else if (totalSize >= KiB) { - filesize.setText(Long.toString(totalSize/KiB)+" KiB"); - } else { - filesize.setText(Long.toString(totalSize)+" Bytes"); - } - simpleProgressBar.setVisibility(View.INVISIBLE); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - finish(); - } - } - }); - getInfo.start(); - } -} \ No newline at end of file diff --git a/app/src/main/java/asgardius/page/s3music/ObjectPolicy.java b/app/src/main/java/asgardius/page/s3music/ObjectPolicy.java deleted file mode 100644 index 83c80d7..0000000 --- a/app/src/main/java/asgardius/page/s3music/ObjectPolicy.java +++ /dev/null @@ -1,260 +0,0 @@ -package asgardius.page.s3music; - -import androidx.appcompat.app.AppCompatActivity; -import android.os.Bundle; -import android.view.View; -import android.widget.Button; -import android.widget.ProgressBar; -import android.widget.TextView; -import android.widget.Toast; - -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Region; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3Client; -import com.amazonaws.services.s3.S3ClientOptions; - -public class ObjectPolicy extends AppCompatActivity { - String username, password, endpoint, bucket, location, filename, title, policy; - Region region; - S3ClientOptions s3ClientOptions; - AWSCredentials myCredentials; - AmazonS3 s3client; - boolean style, publicbucket, publicobject, parent; - ProgressBar simpleProgressBar; - TextView permission; - Button setpublic, setprivate; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_object_policy); - simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar); - permission = (TextView) findViewById(R.id.permission); - endpoint = getIntent().getStringExtra("endpoint"); - filename = getIntent().getStringExtra("filename"); - username = getIntent().getStringExtra("username"); - password = getIntent().getStringExtra("password"); - bucket = getIntent().getStringExtra("bucket"); - title = getIntent().getStringExtra("title"); - style = getIntent().getBooleanExtra("style", false); - location = getIntent().getStringExtra("region"); - getSupportActionBar().setTitle(title); - region = Region.getRegion(location); - s3ClientOptions = S3ClientOptions.builder().build(); - myCredentials = new BasicAWSCredentials(username, password); - try { - s3client = new AmazonS3Client(myCredentials, region); - } catch (Exception e) { - Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show(); - } - s3client.setEndpoint(endpoint); - s3ClientOptions.setPathStyleAccess(style); - s3client.setS3ClientOptions(s3ClientOptions); - setprivate = (Button)findViewById(R.id.set_private); - setpublic = (Button)findViewById(R.id.set_public); - Thread getPolicy = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - policy = s3client.getBucketPolicy(bucket).getPolicyText(); - publicbucket = policy.contains("arn:aws:s3:::"+bucket+"/*") && policy.contains("s3:GetObject"); - publicobject = false; - parent = true; - if(!publicbucket && policy.contains("s3:GetObject")) { - if((policy.contains("\"arn:aws:s3:::"+bucket+"/"+filename+"\"") || policy.contains("\"arn:aws:s3:::"+bucket+"/"+filename+"*\"") || policy.contains("\"arn:aws:s3:::"+bucket+"/"+filename+"**\"")) && policy.contains("s3:GetObject")) { - publicobject = true; - parent = false; - } else { - String[] path = filename.split("/"); - String filepath = ""; - for (int i = 0; i < path.length-1; i++) { - filepath = filepath+path[i]+"/"; - //System.out.println(filepath); - if(policy.contains("\"arn:aws:s3:::"+bucket+"/"+filepath+"*\"") || policy.contains("\"arn:aws:s3:::"+bucket+"/"+filepath+"**\"")) { - publicobject = true; - i = path.length; - } - } - } - } - //System.out.println(policy); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - //Your code goes here - if(publicbucket){ - permission.setText(getResources().getString(R.string.public_object)); - setprivate.setEnabled(false); - setprivate.setText(getResources().getString(R.string.parent_policy)); - setprivate.setVisibility(View.VISIBLE); - }else if(publicobject) { - permission.setText(getResources().getString(R.string.public_object)); - if(parent) { - setprivate.setEnabled(false); - setprivate.setText(getResources().getString(R.string.parent_policy)); - } - setprivate.setVisibility(View.VISIBLE); - }else { - permission.setText(getResources().getString(R.string.private_object)); - setpublic.setVisibility(View.VISIBLE); - } - simpleProgressBar.setVisibility(View.INVISIBLE); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - if(e.toString().contains("NoSuchBucketPolicy")) { - permission.setText(getResources().getString(R.string.private_object)); - setpublic.setVisibility(View.VISIBLE); - simpleProgressBar.setVisibility(View.INVISIBLE); - } - else { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - finish(); - } - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - } - } - }); - getPolicy.start(); - setpublic.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - simpleProgressBar.setVisibility(View.VISIBLE); - setPublic(); - } - }); - setprivate.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - simpleProgressBar.setVisibility(View.VISIBLE); - setPrivate(); - } - }); - } - - private void setPublic() { - Thread setPublic = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - if(policy == null) { - if(filename.endsWith("/")) { - policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::"+bucket+"/"+filename+"*\"]}]}"; - } else { - policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::"+bucket+"/"+filename+"\"]}]}"; - } - } else if(policy.endsWith("]}]}")) { - if(filename.endsWith("/")) { - policy = policy.substring(0, policy.length()-4)+",\"arn:aws:s3:::"+bucket+"/"+filename+"*\"]}]}"; - } else { - policy = policy.substring(0, policy.length()-4)+",\"arn:aws:s3:::"+bucket+"/"+filename+"\"]}]}"; - } - } else { - if(filename.endsWith("/")) { - policy = policy.substring(0, policy.length()-3)+",\"arn:aws:s3:::"+bucket+"/"+filename+"*\"}]}"; - } else { - policy = policy.substring(0, policy.length()-3)+",\"arn:aws:s3:::"+bucket+"/"+filename+"\"}]}"; - } - } - s3client.setBucketPolicy(bucket, policy); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.policy_ok), Toast.LENGTH_SHORT).show(); - finish(); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - simpleProgressBar.setVisibility(View.INVISIBLE); - Toast.makeText(getApplicationContext(),getResources().getString(R.string.policy_error), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - } - } - }); - setPublic.start(); - } - - private void setPrivate() { - Thread setPrivate = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - String newpolicy = null; - if(policy.contains(",\"arn:aws:s3:::"+bucket+"/"+filename+"*\"")) { - newpolicy = policy.replace(",\"arn:aws:s3:::"+bucket+"/"+filename+"*\"", ""); - s3client.setBucketPolicy(bucket, newpolicy); - } else if(policy.contains(",\"arn:aws:s3:::"+bucket+"/"+filename+"**\"")) { - newpolicy = policy.replace(",\"arn:aws:s3:::"+bucket+"/"+filename+"**\"", ""); - s3client.setBucketPolicy(bucket, newpolicy); - } else if(policy.contains(",\"arn:aws:s3:::"+bucket+"/"+filename+"\"")) { - newpolicy = policy.replace(",\"arn:aws:s3:::"+bucket+"/"+filename+"\"", ""); - s3client.setBucketPolicy(bucket, newpolicy); - } else if(policy.contains("\"arn:aws:s3:::"+bucket+"/"+filename+"*\",")) { - newpolicy = policy.replace("\"arn:aws:s3:::"+bucket+"/"+filename+"*\",", ""); - s3client.setBucketPolicy(bucket, newpolicy); - } else if(policy.contains("\"arn:aws:s3:::"+bucket+"/"+filename+"**\",")) { - newpolicy = policy.replace("\"arn:aws:s3:::"+bucket+"/"+filename+"**\",", ""); - s3client.setBucketPolicy(bucket, newpolicy); - } else if(policy.contains("\"arn:aws:s3:::"+bucket+"/"+filename+"\",")) { - newpolicy = policy.replace("\"arn:aws:s3:::"+bucket+"/"+filename+"\",", ""); - s3client.setBucketPolicy(bucket, newpolicy); - } else { - s3client.deleteBucketPolicy(bucket); - } - - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.policy_ok), Toast.LENGTH_SHORT).show(); - finish(); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - simpleProgressBar.setVisibility(View.INVISIBLE); - Toast.makeText(getApplicationContext(),getResources().getString(R.string.policy_error), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - } - } - }); - setPrivate.start(); - } -} \ No newline at end of file diff --git a/app/src/main/java/asgardius/page/s3music/ObjectSelect.java b/app/src/main/java/asgardius/page/s3music/ObjectSelect.java index 190d669..caac28e 100644 --- a/app/src/main/java/asgardius/page/s3music/ObjectSelect.java +++ b/app/src/main/java/asgardius/page/s3music/ObjectSelect.java @@ -1,21 +1,14 @@ package asgardius.page.s3music; -import androidx.appcompat.app.AlertDialog; +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.widget.ProgressBar; +import android.widget.Toast; + import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import android.content.ClipData; -import android.content.ClipboardManager; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Build; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.PopupMenu; -import android.widget.ProgressBar; -import android.widget.Toast; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; @@ -23,15 +16,10 @@ import com.amazonaws.regions.Region; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.S3ClientOptions; -import com.amazonaws.services.s3.model.DeleteObjectRequest; -import com.amazonaws.services.s3.model.DeleteObjectsRequest; -import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3ObjectSummary; -import java.net.URL; -import java.net.URLEncoder; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; @@ -246,80 +234,6 @@ public class ObjectSelect extends AppCompatActivity { if (Img.get(position).equals(R.drawable.folder)) { //go to subfolder explorer(Name.get(position).toString()); - } else if (Img.get(position).equals(R.drawable.imagefile)) { - //load media file - try { - GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket, prefix + Name.get(position).toString()); - URL objectURL = s3client.generatePresignedUrl(request); - imageViewer(objectURL.toString(), Name.get(position).toString()); - } catch (Exception e) { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - } /*else if (Img.get(position).equals(R.drawable.textfile)) { - //load media file - try { - GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket, prefix + Name.get(position).toString()); - URL objectURL = s3client.generatePresignedUrl(request); - textViewer(objectURL.toString()); - } catch (Exception e) { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - }*/ else if (Img.get(position).equals(R.drawable.webpage) || Img.get(position).equals(R.drawable.ptextfile)) { - //load media file - try { - GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket, prefix + Name.get(position).toString()); - URL objectURL = s3client.generatePresignedUrl(request); - webBrowser(objectURL.toString(), Name.get(position).toString()); - } catch (Exception e) { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - } else if (Img.get(position).equals(R.drawable.pdffile)) { - //load media file - Thread pdfread = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket, prefix + Name.get(position).toString()); - URL objectURL = s3client.generatePresignedUrl(request); - //System.out.println(getResources().getString(R.string.pdf_reader)+ URLEncoder.encode(objectURL.toString(), "UTF-8" )); - if (pdfendpoint.endsWith("/")) { - query = pdfendpoint + "web/viewer.html?file=" + URLEncoder.encode(objectURL.toString(), "UTF-8" ); - } else { - query = pdfendpoint + "/web/viewer.html?file=" + URLEncoder.encode(objectURL.toString(), "UTF-8" ); - } - - runOnUiThread(new Runnable() { - - @Override - public void run() { - // Sending reference and data to Adapter - webBrowser(query, Name.get(position).toString()); - } - }); - //System.out.println("tree "+treelevel); - //System.out.println("prefix "+prefix); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - finish(); - } - } - }); - if (pdfendpoint == null || pdfendpoint.equals("")) { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.pdf_reader_notready), Toast.LENGTH_SHORT).show(); - } else { - pdfread.start(); - } } else if (Img.get(position).equals(R.drawable.audiofile) || Img.get(position).equals(R.drawable.videofile)) { simpleProgressBar.setVisibility(View.VISIBLE); if (isplaylist) { @@ -382,90 +296,6 @@ public class ObjectSelect extends AppCompatActivity { @Override public void onLongClick(View view, int position) { //System.out.println("Long click on "+Name.get(position).toString()); - if (Img.get(position).equals(R.drawable.folder)) { - //go to subfolder - /// Initializing the popup menu and giving the reference as current context - PopupMenu popupMenu = new PopupMenu(recyclerView.getContext(), view); - - // Inflating popup menu from popup_menu.xml file - popupMenu.getMenuInflater().inflate(R.menu.folder_menu, popupMenu.getMenu()); - popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem menuItem) { - // Toast message on menu item clicked - //Toast.makeText(MainActivity.this, "You Clicked " + menuItem.getTitle(), Toast.LENGTH_SHORT).show(); - if (menuItem.getTitle() == getResources().getString(R.string.upload_file_here)) { - //Toast.makeText(ObjectSelect.this, getResources().getString(R.string.pending_feature), Toast.LENGTH_SHORT).show(); - upload(false); - } else if (menuItem.getTitle() == getResources().getString(R.string.upload_folder_here)) { - //Toast.makeText(ObjectSelect.this, getResources().getString(R.string.pending_feature), Toast.LENGTH_SHORT).show(); - upload(true); - } else if (menuItem.getTitle() == getResources().getString(R.string.download_folder)) { - //Toast.makeText(ObjectSelect.this, getResources().getString(R.string.pending_feature), Toast.LENGTH_SHORT).show(); - download(Name.get(position).toString(), true); - } else if (menuItem.getTitle() == getResources().getString(R.string.bucket_policy)) { - policyConfig(prefix + Name.get(position).toString(), Name.get(position).toString()); - } else if (menuItem.getTitle() == getResources().getString(R.string.create_link)) { - share( Name.get(position).toString(), Img.get(position).equals(R.drawable.audiofile) || Img.get(position).equals(R.drawable.videofile)); - } else if (menuItem.getTitle() == getResources().getString(R.string.object_info)) { - objectInfo(prefix + Name.get(position).toString(), Name.get(position).toString()); - } else if (menuItem.getTitle() == getResources().getString(R.string.copy_name)) { - copyName(Name.get(position).toString()); - } else if (menuItem.getTitle() == getResources().getString(R.string.file_del)) { - if (Name.size() == 1 && treelevel >= 1) { - Toast.makeText(ObjectSelect.this, getResources().getString(R.string.only_item_onlist), Toast.LENGTH_SHORT).show(); - } else { - delete(prefix + Name.get(position).toString(), true); - } - } - return true; - } - }); - // Showing the popup menu - popupMenu.show(); - } else { - // Initializing the popup menu and giving the reference as current context - PopupMenu popupMenu = new PopupMenu(recyclerView.getContext(), view); - - // Inflating popup menu from popup_menu.xml file - popupMenu.getMenuInflater().inflate(R.menu.object_menu, popupMenu.getMenu()); - popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem menuItem) { - // Toast message on menu item clicked - //Toast.makeText(MainActivity.this, "You Clicked " + menuItem.getTitle(), Toast.LENGTH_SHORT).show(); - if (menuItem.getTitle() == getResources().getString(R.string.download_file)) { - //Toast.makeText(ObjectSelect.this, getResources().getString(R.string.pending_feature), Toast.LENGTH_SHORT).show(); - download(Name.get(position).toString(), false); - } else if (menuItem.getTitle() == getResources().getString(R.string.bucket_policy)) { - policyConfig(prefix + Name.get(position).toString(), Name.get(position).toString()); - } else if (menuItem.getTitle() == getResources().getString(R.string.upload_file_here)) { - //Toast.makeText(ObjectSelect.this, getResources().getString(R.string.pending_feature), Toast.LENGTH_SHORT).show(); - upload(false); - } else if (menuItem.getTitle() == getResources().getString(R.string.upload_folder_here)) { - //Toast.makeText(ObjectSelect.this, getResources().getString(R.string.pending_feature), Toast.LENGTH_SHORT).show(); - upload(true); - } else if (menuItem.getTitle() == getResources().getString(R.string.create_link)) { - share(Name.get(position).toString(), Img.get(position).equals(R.drawable.audiofile) || Img.get(position).equals(R.drawable.videofile)); - } else if (menuItem.getTitle() == getResources().getString(R.string.object_info)) { - objectInfo(prefix + Name.get(position).toString(), Name.get(position).toString()); - } else if (menuItem.getTitle() == getResources().getString(R.string.copy_name)) { - copyName(Name.get(position).toString()); - } else if (menuItem.getTitle() == getResources().getString(R.string.file_del)) { - if (menuItem.getTitle() == getResources().getString(R.string.file_del)) { - if (Name.size() == 1 && treelevel >= 1) { - Toast.makeText(ObjectSelect.this, getResources().getString(R.string.only_item_onlist), Toast.LENGTH_SHORT).show(); - } else { - delete(prefix + Name.get(position).toString(), false); - } - } - } - return true; - } - }); - // Showing the popup menu - popupMenu.show(); - } } })); } @@ -531,31 +361,6 @@ public class ObjectSelect extends AppCompatActivity { startActivity(intent); } - } - private void textViewer(String url) { - - Intent intent = new Intent(this, TextViewer.class); - intent.putExtra("video_url", url); - startActivity(intent); - - } - - private void imageViewer(String url, String title) { - - Intent intent = new Intent(this, ImageViewer.class); - intent.putExtra("video_url", url); - intent.putExtra("title", title); - startActivity(intent); - - } - - private void webBrowser(String url, String pagetitle) { - - Intent intent = new Intent(this, WebBrowser.class); - intent.putExtra("web_url", url); - intent.putExtra("title", pagetitle); - startActivity(intent); - } private void explorer(String object) { @@ -579,200 +384,6 @@ public class ObjectSelect extends AppCompatActivity { startActivity(intent); } - - private void share(String object, boolean mediafile) { - - Intent intent = new Intent(this, Share.class); - //treelevel ++; - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("bucket", bucket); - intent.putExtra("object", prefix+object); - intent.putExtra("title", object); - intent.putExtra("region", location); - intent.putExtra("mediafile", mediafile); - intent.putExtra("videotime", videotime); - intent.putExtra("playlisttime", playlisttime); - intent.putExtra("style", style); - startActivity(intent); - - } - - private void objectInfo(String object, String title) { - - Intent intent = new Intent(this, ObjectInfo.class); - //treelevel ++; - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("bucket", bucket); - intent.putExtra("object", object); - intent.putExtra("title", title); - intent.putExtra("region", location); - intent.putExtra("style", style); - startActivity(intent); - - } - - private void delete(String object, boolean folder) { - AlertDialog.Builder builder = new AlertDialog.Builder(ObjectSelect.this); - builder.setCancelable(true); - builder.setTitle(object); - if (folder) { - builder.setMessage(getResources().getString(R.string.folder_del_confirm)); - } else { - builder.setMessage(getResources().getString(R.string.file_del_confirm)); - } - builder.setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - //Toast.makeText(ObjectSelect.this, getResources().getString(R.string.pending_feature), Toast.LENGTH_SHORT).show(); - Thread deleteObject = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - //List buckets = s3client.listBuckets(); - if (folder) { - ListObjectsRequest orequest = new ListObjectsRequest().withBucketName(bucket).withPrefix(object).withMaxKeys(1000); - //List objects = (List) s3client.listObjects(bucket, "/"); - ObjectListing result = s3client.listObjects(orequest); - ArrayList objectl = new ArrayList(); - List objects = result.getObjectSummaries(); - for (S3ObjectSummary os : objects) { - objectl.add(os.getKey()); - } - if (objectl.size() >= 1) { - DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucket).withKeys(objectl.toArray(new String[0])); - s3client.deleteObjects(deleteObjectsRequest); - } - while (result.isTruncated()) { - objectl = new ArrayList(); - result = s3client.listNextBatchOfObjects (result); - objects = result.getObjectSummaries(); - for (S3ObjectSummary os : objects) { - objectl.add(os.getKey()); - //i++; - } - DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucket).withKeys(objectl.toArray(new String[0])); - s3client.deleteObjects(deleteObjectsRequest); - - } - - } else { - DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucket, object); - s3client.deleteObject(deleteObjectRequest); - } - - //System.out.println(Name); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - // Sending reference and data to Adapter - if (folder) { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.folder_del_success), Toast.LENGTH_SHORT).show(); - } else { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.file_del_success), Toast.LENGTH_SHORT).show(); - } - recreate(); - - } - }); - //System.out.println("tree "+treelevel); - //System.out.println("prefix "+prefix); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - finish(); - } - } - }); - simpleProgressBar.setVisibility(View.VISIBLE); - deleteObject.start(); - } - }); - builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - } - }); - AlertDialog dialog = builder.create(); - dialog.show(); - } - - private void upload(boolean isfolder) { - Intent intent = new Intent(this, Uploader.class); - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("bucket", bucket); - intent.putExtra("prefix", prefix); - intent.putExtra("region", location); - intent.putExtra("style", style); - intent.putExtra("isfolder", isfolder); - startActivity(intent); - } - - private void download(String filename, boolean isfolder) { - - Intent intent = new Intent(this, Downloader.class); - if(isfolder) { - intent.putExtra("prefix", prefix+filename); - } else { - intent.putExtra("prefix", prefix); - intent.putExtra("filename", filename); - } - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("region", location); - intent.putExtra("style", style); - intent.putExtra("bucket", bucket); - intent.putExtra("isfolder", isfolder); - startActivity(intent); - } - - private void policyConfig(String filename, String title) { - Intent intent = new Intent(this, ObjectPolicy.class); - intent.putExtra("endpoint", endpoint); - intent.putExtra("username", username); - intent.putExtra("password", password); - intent.putExtra("bucket", bucket); - intent.putExtra("filename", filename); - intent.putExtra("region", location); - intent.putExtra("style", style); - intent.putExtra("title", title); - intent.putExtra("pdfendpoint", pdfendpoint); - startActivity(intent); - } - - public void copyName (String name) { - ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip; - if(name.endsWith("/")) { - clip = ClipData.newPlainText("name", name.replace("/", "")); - } else { - clip = ClipData.newPlainText("name", name); - } - clipboard.setPrimaryClip(clip); - if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.copy_ok), Toast.LENGTH_SHORT).show(); - } - } - public ArrayList getLinks (ArrayList medialist) throws InterruptedException { ArrayList links = new ArrayList(); Date expiration = new Date(); diff --git a/app/src/main/java/asgardius/page/s3music/Share.java b/app/src/main/java/asgardius/page/s3music/Share.java deleted file mode 100644 index eb59d99..0000000 --- a/app/src/main/java/asgardius/page/s3music/Share.java +++ /dev/null @@ -1,467 +0,0 @@ -package asgardius.page.s3music; - -import androidx.appcompat.app.AppCompatActivity; - -import android.app.Activity; -import android.content.ClipData; -import android.content.ClipboardManager; -import android.content.Context; -import android.content.Intent; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ProgressBar; -import android.widget.TextView; -import android.widget.Toast; - -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Region; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3Client; -import com.amazonaws.services.s3.S3ClientOptions; -import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest; -import com.amazonaws.services.s3.model.ListObjectsRequest; -import com.amazonaws.services.s3.model.ObjectListing; -import com.amazonaws.services.s3.model.S3ObjectSummary; - -import java.io.OutputStreamWriter; -import java.net.URL; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -public class Share extends AppCompatActivity { - String username, password, endpoint, bucket, object, location, title, objectlist, policy; - boolean mediafile, style, publicobject; - TextView expirationtext; - ProgressBar simpleProgressBar; - Region region; - S3ClientOptions s3ClientOptions; - AWSCredentials myCredentials; - AmazonS3 s3client; - ListObjectsRequest orequest; - Calendar mycal; - EditText datepick, hourpick, minutepick; - int date, hour, minute; - Button share, copylinks, savelinks; - GeneratePresignedUrlRequest request; - Date expiration; - URL objectURL; - Uri fileuri; - Intent intent; - int videotime, playlisttime; - - public static String URLify(String str) { - str = str.trim(); - int length = str.length(); - int trueL = length; - if(str.contains(" ")) { - for(int i = 0; i < length; i++) { - if(str.charAt(i) == ' ') { - trueL = trueL + 2; - } - } - char[] oldArr = str.toCharArray(); - char[] newArr = new char[trueL]; - int x = 0; - for(int i = 0; i < length; i++) { - if(oldArr[i] == ' ') { - newArr[x] = '%'; - newArr[x+1] = '2'; - newArr[x+2] = '0'; - x += 3; - } else { - newArr[x] = oldArr[i]; - x++; - } - } - str = new String(newArr, 0, trueL); - } - return str; - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_share); - simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar); - expirationtext = (TextView) findViewById(R.id.expirationtext); - mycal = Calendar.getInstance(); - datepick = (EditText)findViewById(R.id.Date); - hourpick = (EditText)findViewById(R.id.Hour); - minutepick = (EditText)findViewById(R.id.Minute); - share = (Button)findViewById(R.id.share); - copylinks = (Button)findViewById(R.id.copy_links); - savelinks = (Button)findViewById(R.id.save_links); - endpoint = getIntent().getStringExtra("endpoint"); - username = getIntent().getStringExtra("username"); - password = getIntent().getStringExtra("password"); - bucket = getIntent().getStringExtra("bucket"); - location = getIntent().getStringExtra("region"); - style = getIntent().getBooleanExtra("style", false); - object = getIntent().getStringExtra("object"); - mediafile = getIntent().getBooleanExtra("mediafile", false); - videotime = getIntent().getIntExtra("videotime", 1); - playlisttime = getIntent().getIntExtra("playlisttime", 1); - title = getIntent().getStringExtra("title"); - getSupportActionBar().setTitle(title); - region = Region.getRegion(location); - s3ClientOptions = S3ClientOptions.builder().build(); - myCredentials = new BasicAWSCredentials(username, password); - try { - s3client = new AmazonS3Client(myCredentials, region); - } catch (Exception e) { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - } - s3client.setEndpoint(endpoint); - s3ClientOptions.setPathStyleAccess(style); - s3client.setS3ClientOptions(s3ClientOptions); - Thread getPolicy = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - policy = s3client.getBucketPolicy(bucket).getPolicyText(); - publicobject = false; - if(policy.contains("arn:aws:s3:::"+bucket+"/*") && policy.contains("s3:GetObject")) { - publicobject = true; - } else if(policy.contains("s3:GetObject")) { - if((policy.contains("\"arn:aws:s3:::"+bucket+"/"+object+"\"") || policy.contains("\"arn:aws:s3:::"+bucket+"/"+object+"*\"") || policy.contains("\"arn:aws:s3:::"+bucket+"/"+object+"**\"")) && policy.contains("s3:GetObject")) { - publicobject = true; - } else { - String[] path = object.split("/"); - String filepath = ""; - for (int i = 0; i < path.length-1; i++) { - filepath = filepath+path[i]+"/"; - //System.out.println(filepath); - if(policy.contains("\"arn:aws:s3:::"+bucket+"/"+filepath+"*\"") || policy.contains("\"arn:aws:s3:::"+bucket+"/"+filepath+"**\"")) { - publicobject = true; - i = path.length; - } - } - } - } - //System.out.println(policy); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - //Your code goes here - if(publicobject){ - expirationtext.setText(getResources().getString(R.string.expiration_not_required)); - - } else { - datepick.setEnabled(true); - hourpick.setEnabled(true); - minutepick.setEnabled(true); - expirationtext.setText(getResources().getString(R.string.expiration_time)); - } - if(object == null || object.endsWith("/")) { - copylinks.setVisibility(View.VISIBLE); - savelinks.setVisibility(View.VISIBLE); - } else { - share.setVisibility(View.VISIBLE); - copylinks.setVisibility(View.VISIBLE); - } - simpleProgressBar.setVisibility(View.INVISIBLE); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - publicobject = false; - datepick.setEnabled(true); - hourpick.setEnabled(true); - minutepick.setEnabled(true); - expirationtext.setText(getResources().getString(R.string.expiration_time)); - if(object == null || object.endsWith("/")) { - copylinks.setVisibility(View.VISIBLE); - savelinks.setVisibility(View.VISIBLE); - } else { - share.setVisibility(View.VISIBLE); - copylinks.setVisibility(View.VISIBLE); - } - simpleProgressBar.setVisibility(View.INVISIBLE); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - } - } - }); - getPolicy.start(); - share.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - try { - sharefile(); - //System.out.println(URLify(objectURL.toString())); - Intent shareIntent = new Intent(Intent.ACTION_SEND); - shareIntent.setType("text/plain"); - shareIntent.putExtra(Intent.EXTRA_TEXT, URLify(objectURL.toString())); - startActivity(Intent.createChooser(shareIntent, "choose one")); - } catch (Exception e) { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.invalid_expiration_date), Toast.LENGTH_SHORT).show(); - } - } - - }); - copylinks.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - if(object == null || object.endsWith("/")) { - simpleProgressBar.setVisibility(View.VISIBLE); - } - Thread copyLinks = new Thread(new Runnable() { - - @Override - public void run() { - try { - //load media file - if(object == null || object.endsWith("/")) { - getLinks(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - // Sending reference and data to Adapter - simpleProgressBar.setVisibility(View.INVISIBLE); - ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip; - clip = ClipData.newPlainText("name", objectlist); - clipboard.setPrimaryClip(clip); - if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.copy_ok), Toast.LENGTH_SHORT).show(); - } - } - }); - } else { - sharefile(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - // Sending reference and data to Adapter - ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip; - clip = ClipData.newPlainText("name", URLify(objectURL.toString())); - clipboard.setPrimaryClip(clip); - if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.copy_ok), Toast.LENGTH_SHORT).show(); - } - } - }); - } - - //System.out.println("tree "+treelevel); - //System.out.println("prefix "+prefix); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - simpleProgressBar.setVisibility(View.INVISIBLE); - Toast.makeText(getApplicationContext(),getResources().getString(R.string.invalid_expiration_date), Toast.LENGTH_SHORT).show(); - } - }); - } - } - }); - copyLinks.start(); - } - - }); - savelinks.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - performFileSearch("Select download location"); - } - - }); - } - - private void performFileSearch(String messageTitle) { - //uri = Uri.parse("content://com.android.externalstorage.documents/document/home"); - intent = new Intent(); - intent.setAction(Intent.ACTION_CREATE_DOCUMENT); - //intent.addCategory(Intent.CATEGORY_OPENABLE); - //intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); - //intent.putExtra("android.provider.extra.INITIAL_URI", uri); - intent.putExtra(Intent.EXTRA_TITLE, "links.txt"); - intent.setType("*/*"); - ((Activity) this).startActivityForResult(intent, 70); - } - - @Override - public void onActivityResult(int requestCode, int resultCode, final Intent resultData) { - // The ACTION_OPEN_DOCUMENT intent was sent with the request code OPEN_DIRECTORY_REQUEST_CODE. - // If the request code seen here doesn't match, it's the response to some other intent, - // and the below code shouldn't run at all. - super.onActivityResult(requestCode, resultCode, resultData); - if (requestCode == 70) { - if (resultCode == Activity.RESULT_OK) { - // The document selected by the user won't be returned in the intent. - // Instead, a URI to that document will be contained in the return intent - // provided to this method as a parameter. Pull that uri using "resultData.getData()" - if (resultData != null && resultData.getData() != null) { - fileuri = resultData.getData(); - System.out.println(fileuri.toString()); - savelinks(); - //System.out.println("File selected successfully"); - //System.out.println("content://com.android.externalstorage.documents"+file.getPath()); - } else { - Toast.makeText(Share.this, getResources().getString(R.string.file_path_fail), Toast.LENGTH_SHORT).show(); - finish(); - } - } else { - //System.out.println("User cancelled file browsing {}"); - finish(); - } - } - } - - private void getLinks() { - if (datepick.getText().toString().equals("")) { - date = 0; - } else { - date = Integer.parseInt(datepick.getText().toString()); - } - if (hourpick.getText().toString().equals("")) { - hour = 0; - } else { - hour = Integer.parseInt(hourpick.getText().toString()); - } - if (minutepick.getText().toString().equals("")) { - minute = 0; - } else { - minute = Integer.parseInt(minutepick.getText().toString()); - } - expiration = new Date(); - //System.out.println("today is " + mycal.getTime()); - mycal.setTime(expiration); - if (date == 0 && hour == 0 && minute == 0) { - mycal.add(Calendar.HOUR, playlisttime); - } else { - mycal.add(Calendar.DATE, date); - mycal.add(Calendar.HOUR, hour); - mycal.add(Calendar.MINUTE, minute); - } - //System.out.println("Expiration date: " + mycal.getTime()); - expiration = mycal.getTime(); - //System.out.println(expiration); - if (object == null) { - orequest = new ListObjectsRequest().withBucketName(bucket).withMaxKeys(1000); - } else { - orequest = new ListObjectsRequest().withBucketName(bucket).withPrefix(object).withMaxKeys(1000); - } - ObjectListing result = s3client.listObjects(orequest); - objectlist = ""; - List objects = result.getObjectSummaries(); - for (S3ObjectSummary os : objects) { - objectlist = objectlist+PolicyCheck.getFileKey(s3client, bucket, os.getKey(), expiration, policy)+"\n"; - } - while (result.isTruncated()) { - result = s3client.listNextBatchOfObjects (result); - objects = result.getObjectSummaries(); - for (S3ObjectSummary os : objects) { - objectlist = objectlist+PolicyCheck.getFileKey(s3client, bucket, os.getKey(), expiration, policy)+"\n"; - } - - } - } - - private void sharefile() { - if(publicobject) { - objectURL = s3client.getUrl(bucket, object); - } else { - if (datepick.getText().toString().equals("")) { - date = 0; - } else { - date = Integer.parseInt(datepick.getText().toString()); - } - if (hourpick.getText().toString().equals("")) { - hour = 0; - } else { - hour = Integer.parseInt(hourpick.getText().toString()); - } - if (minutepick.getText().toString().equals("")) { - minute = 0; - } else { - minute = Integer.parseInt(minutepick.getText().toString()); - } - expiration = new Date(); - //System.out.println("today is " + mycal.getTime()); - mycal.setTime(expiration); - if (date == 0 && hour == 0 && minute == 0) { - if (mediafile) { - mycal.add(Calendar.HOUR, videotime); - } else { - mycal.add(Calendar.MINUTE, 15); - } - } else { - mycal.add(Calendar.DATE, date); - mycal.add(Calendar.HOUR, hour); - mycal.add(Calendar.MINUTE, minute); - } - //System.out.println("Expiration date: " + mycal.getTime()); - expiration = mycal.getTime(); - //System.out.println(expiration); - request = new GeneratePresignedUrlRequest(bucket, object).withExpiration(expiration); - objectURL = s3client.generatePresignedUrl(request); - } - } - - private void savelinks() { - simpleProgressBar.setVisibility(View.VISIBLE); - Thread saveLinks = new Thread(new Runnable() { - - @Override - public void run() { - try { - getLinks(); - OutputStreamWriter outputStreamWriter = new OutputStreamWriter(getContentResolver().openOutputStream(fileuri)); - outputStreamWriter.write(objectlist); - outputStreamWriter.close(); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - // Sending reference and data to Adapter - simpleProgressBar.setVisibility(View.INVISIBLE); - Toast.makeText(getApplicationContext(),getResources().getString(R.string.save_ok), Toast.LENGTH_SHORT).show(); - } - }); - //System.out.println("tree "+treelevel); - //System.out.println("prefix "+prefix); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - simpleProgressBar.setVisibility(View.INVISIBLE); - Toast.makeText(getApplicationContext(),getResources().getString(R.string.invalid_expiration_date), Toast.LENGTH_SHORT).show(); - } - }); - } - } - }); - saveLinks.start(); - } -} \ No newline at end of file diff --git a/app/src/main/java/asgardius/page/s3music/TextViewer.java b/app/src/main/java/asgardius/page/s3music/TextViewer.java deleted file mode 100644 index 50a50de..0000000 --- a/app/src/main/java/asgardius/page/s3music/TextViewer.java +++ /dev/null @@ -1,89 +0,0 @@ -package asgardius.page.s3music; - -import android.os.Build; -import android.os.Bundle; -import android.view.View; -import android.widget.EditText; -import android.widget.ProgressBar; -import android.widget.Toast; - -import androidx.appcompat.app.AppCompatActivity; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.stream.Collectors; - -public class TextViewer extends AppCompatActivity { - EditText filecontent; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_text_viewer); - filecontent = (EditText)findViewById(R.id.textShow); - final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - String videoURL = getIntent().getStringExtra("video_url"); - Thread textread = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - URL fileurl = new URL(videoURL); - - // Read all the text returned by the server - BufferedReader in = new BufferedReader(new InputStreamReader(fileurl.openStream())); - String str = in.lines().collect(Collectors.joining()); - in.close(); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - // Sending reference and data to Adapter - simpleProgressBar.setVisibility(View.INVISIBLE); - filecontent.setText(str); - - } - }); - //System.out.println("tree "+treelevel); - //System.out.println("prefix "+prefix); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - finish(); - } - }); - //Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); - finish(); - } - } - }); - textread.start(); - } else { - finish(); - } - - /*try { - // Create a URL for the desired page - URL fileurl = new URL(videoURL); - - // Read all the text returned by the server - BufferedReader in = new BufferedReader(new InputStreamReader(fileurl.openStream())); - String str = in.readLine(); - in.close(); - filecontent.setText(str); - } catch (MalformedURLException e) { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_conn_fail), Toast.LENGTH_SHORT).show(); - } catch (IOException e) { - Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_conn_fail), Toast.LENGTH_SHORT).show(); - }*/ - } -} \ No newline at end of file diff --git a/app/src/main/java/asgardius/page/s3music/Uploader.java b/app/src/main/java/asgardius/page/s3music/Uploader.java deleted file mode 100644 index 725bac2..0000000 --- a/app/src/main/java/asgardius/page/s3music/Uploader.java +++ /dev/null @@ -1,575 +0,0 @@ -package asgardius.page.s3music; - -import static android.content.ContentValues.TAG; - -import androidx.appcompat.app.AppCompatActivity; -import androidx.documentfile.provider.DocumentFile; - -import android.annotation.SuppressLint; -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.database.Cursor; -import android.net.Uri; -import android.net.wifi.WifiManager; -import android.os.Bundle; -import android.os.PowerManager; -import android.provider.MediaStore; -import android.util.Log; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ProgressBar; -import android.widget.TextView; -import android.widget.Toast; - -import com.amazonaws.AbortedException; -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Region; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3Client; -import com.amazonaws.services.s3.S3ClientOptions; -import com.amazonaws.services.s3.model.AbortMultipartUploadRequest; -import com.amazonaws.services.s3.model.AmazonS3Exception; -import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest; -import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; -import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; -import com.amazonaws.services.s3.model.PartETag; -import com.amazonaws.services.s3.model.PutObjectRequest; -import com.amazonaws.services.s3.model.PutObjectResult; -import com.amazonaws.services.s3.model.UploadPartRequest; -import com.amazonaws.services.s3.model.UploadPartResult; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -public class Uploader extends AppCompatActivity { - String username, password, endpoint, bucket, prefix, location; - Uri fileuri, folder; - EditText fprefix; - TextView fprefixlabel; - Region region; - S3ClientOptions s3ClientOptions; - AWSCredentials myCredentials; - AmazonS3 s3client; - ProgressBar simpleProgressBar; - long filesize; - File ufile; - DocumentFile document; - Intent intent; - Button fileUpload; - Thread uploadFile, uploadProgress, calculateProgress; - boolean style, isfolder; - boolean started = false; - boolean cancel = false; - long transfered = 0; - private static final long MAX_SINGLE_PART_UPLOAD_BYTES = 5 * 1024 * 1024; - private WifiManager.WifiLock mWifiLock; - private PowerManager.WakeLock mWakeLock; - private PowerManager powerManager; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_uploader); - // create Wifi and wake locks - mWifiLock = ((WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "Transistor:wifi_lock"); - powerManager = (PowerManager) getSystemService(POWER_SERVICE); - mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Transistor:wake_lock"); - endpoint = getIntent().getStringExtra("endpoint"); - username = getIntent().getStringExtra("username"); - password = getIntent().getStringExtra("password"); - bucket = getIntent().getStringExtra("bucket"); - location = getIntent().getStringExtra("region"); - style = getIntent().getBooleanExtra("style", false); - isfolder = getIntent().getBooleanExtra("isfolder", false); - prefix = getIntent().getStringExtra("prefix"); - if(isfolder) { - getSupportActionBar().setTitle(getResources().getString(R.string.batch_upload_button)); - } else { - getSupportActionBar().setTitle(getResources().getString(R.string.upload_button)); - } - fprefix = (EditText)findViewById(R.id.fprefix); - fprefixlabel = (TextView) findViewById(R.id.fprefixlabel); - region = Region.getRegion(location); - s3ClientOptions = S3ClientOptions.builder().build(); - s3ClientOptions.setPathStyleAccess(style); - myCredentials = new BasicAWSCredentials(username, password); - s3client = new AmazonS3Client(myCredentials, region); - s3client.setEndpoint(endpoint); - s3client.setS3ClientOptions(s3ClientOptions); - fileUpload = (Button)findViewById(R.id.fileupload); - simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar); - //Toast.makeText(Uploader.this, getResources().getString(R.string.pending_feature), Toast.LENGTH_SHORT).show(); - performFileSearch("Select file to upload"); - //fprefix.setText(prefix); - fileUpload.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View view) { - //buttonaction - if (started) { - started = false; - cancel = true; - uploadFile.interrupt(); - //simpleProgressBar.setVisibility(View.INVISIBLE); - } else { - started = true; - transfered = 0; - //simpleProgressBar.setProgress(0); - simpleProgressBar.setVisibility(View.VISIBLE); - if (fileuri == null && folder == null) { - Toast.makeText(Uploader.this, getResources().getString(R.string.no_file_selected), Toast.LENGTH_SHORT).show(); - } else { - //Acquiring WakeLock and WifiLock if not held - if (!mWifiLock.isHeld()) { - mWifiLock.acquire(); - //System.out.println("WifiLock acquired"); - } - if (!mWakeLock.isHeld()) { - mWakeLock.acquire(); - //System.out.println("WakeLock acquired"); - } - //eUpload.setEnabled(false); - fileUpload.setText(getResources().getString(R.string.cancel_upload)); - fprefix.setEnabled(false); - uploadFile = new Thread(new Runnable() { - - @Override - public void run() { - //System.out.println(fkey); - //filesize = 0; - try { - //Your code goes here - //s3client.createBucket(bucket, location); - //System.out.println(fkey); - if (isfolder) { - if(prefix.endsWith("/")) { - prefix = fprefix.getText().toString(); - } else { - prefix = fprefix.getText().toString().concat("/"); - } - document = DocumentFile.fromTreeUri(getApplicationContext(), fileuri); - DocumentFile[] filelist = document.listFiles(); - ArrayList filepath = new ArrayList(); - int treelevel = 0; - ArrayList fileindex = new ArrayList(); - fileindex.add(0); - for (int i = 0; i < filelist.length && !cancel; i++) { - filepath.add(filelist[i].getName()); - if(filelist[i].isDirectory()) { - treelevel++; - fileindex.add(0); - document = filelist[i]; - filelist = document.listFiles(); - while (treelevel >= 1 && fileindex.get(treelevel) < filelist.length+1 && !cancel) { - if(fileindex.get(treelevel) == filelist.length) { - fileindex.remove(treelevel); - document = document.getParentFile(); - filelist = document.listFiles(); - treelevel--; - filepath.remove(treelevel); - fileindex.set(treelevel, fileindex.get(treelevel)+1); - } else { - filepath.add(filelist[fileindex.get(treelevel)].getName()); - if (filelist[fileindex.get(treelevel)].isDirectory()) { - document = filelist[fileindex.get(treelevel)]; - filelist = document.listFiles(); - treelevel++; - fileindex.add(0); - } else { - ufile = readContentToFile(filelist[fileindex.get(treelevel)].getUri()); - putS3Object(bucket, prefix+String.join("/", filepath), ufile); - filepath.remove(treelevel); - fileindex.set(treelevel, fileindex.get(treelevel)+1); - } - } - } - } else { - ufile = readContentToFile(filelist[i].getUri()); - putS3Object(bucket, prefix+String.join("/", filepath), ufile); - } - filepath.clear(); - fileindex.clear(); - fileindex.add(0); - } - } else { - ufile = readContentToFile(fileuri); - if(ufile.length()%MAX_SINGLE_PART_UPLOAD_BYTES == 0) { - filesize = ufile.length()/MAX_SINGLE_PART_UPLOAD_BYTES; - } else { - filesize = (ufile.length()/MAX_SINGLE_PART_UPLOAD_BYTES)+1; - } - //PutObjectRequest request = new PutObjectRequest(bucket, fkey, ufile); - //upload = s3client.putObject(request); - putS3Object(bucket, fprefix.getText().toString(), ufile); - } - runOnUiThread(new Runnable() { - - @Override - public void run() { - //Releasing WifiLock and WakeLock if held - if (mWifiLock.isHeld()) { - mWifiLock.release(); - //System.out.println("WifiLock released"); - } - if (mWakeLock.isHeld()) { - mWakeLock.release(); - //System.out.println("WakeLock released"); - } - if(!cancel) { - simpleProgressBar.setProgress(100); - } - //simpleProgressBar.setVisibility(View.INVISIBLE); - if (cancel) { - fileUpload.setText(getResources().getString(R.string.upload_canceled)); - } else if (isfolder) { - fileUpload.setText(getResources().getString(R.string.batch_upload_success)); - } else { - fileUpload.setText(getResources().getString(R.string.upload_success)); - } - started = false; - fileUpload.setEnabled(false); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.upload_success), Toast.LENGTH_SHORT).show(); - //simpleProgressBar.setVisibility(View.INVISIBLE); - } - }); - //System.out.println("tree "+treelevel); - //System.out.println("prefix "+prefix); - - } catch (Exception e) { - e.printStackTrace(); - runOnUiThread(new Runnable() { - - @Override - public void run() { - //Releasing WifiLock and WakeLock if held - if (mWifiLock.isHeld()) { - mWifiLock.release(); - //System.out.println("WifiLock released"); - } - if (mWakeLock.isHeld()) { - mWakeLock.release(); - //System.out.println("WakeLock released"); - } - started = false; - //simpleProgressBar.setVisibility(View.INVISIBLE); - //fileUpload.setEnabled(true); - if (cancel) { - fileUpload.setText(getResources().getString(R.string.upload_canceled)); - } else { - fileUpload.setText(getResources().getString(R.string.upload_failed)); - } - fileUpload.setEnabled(false); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - } - }); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - //finish(); - } - } - }); - uploadProgress = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - while (started) { - try { - if (filesize != 0) { - //simpleProgressBar.setProgress((int)((transfered*100)/filesize)); - simpleProgressBar.setProgress((int)((transfered*100)/filesize)); - } - Thread.sleep(500); - } catch (Exception e) { - e.printStackTrace(); - } - } - - runOnUiThread(new Runnable() { - @Override - public void run() { - //simpleProgressBar.setProgress(100); - } - }); - //System.out.println("tree "+treelevel); - //System.out.println("prefix "+prefix); - - } catch (Exception e) { - e.printStackTrace(); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - //finish(); - } - } - }); - //simpleProgressBar.setVisibility(View.VISIBLE); - uploadFile.start(); - uploadProgress.start(); - /*while (progress <= 99) { - System.out.println("Upload in progress"); - if (upload != null) { - System.out.println(upload.getMetadata().getContentLength()); - if(upload.getMetadata().getContentLength() != 0) { - progress = (int) (((int)filesize / (int)upload.getMetadata().getContentLength())*100); - simpleProgressBar.setProgress(progress); - } - } - System.out.println(filesize); - try { - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }*/ - } - } - } - - }); - } - - private void performFileSearch(String messageTitle) { - //uri = Uri.parse("content://com.android.externalstorage.documents/document/home"); - intent = new Intent(); - if (isfolder) { - intent.setAction(Intent.ACTION_OPEN_DOCUMENT_TREE); - } else { - intent.setAction(Intent.ACTION_OPEN_DOCUMENT); - intent.addCategory(Intent.CATEGORY_OPENABLE); - //intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); - //intent.putExtra("android.provider.extra.INITIAL_URI", uri); - intent.setType("*/*"); - } - ((Activity) this).startActivityForResult(intent, 100); - } - - @SuppressLint("SetTextI18n") - @Override - - public void onDestroy() { - if (!mWifiLock.isHeld()) { - mWifiLock.acquire(); - //System.out.println("WifiLock acquired"); - } - if (!mWakeLock.isHeld()) { - mWakeLock.acquire(); - //System.out.println("WakeLock acquired"); - } - super.onDestroy(); - } - - public void onActivityResult(int requestCode, int resultCode, final Intent resultData) { - // The ACTION_OPEN_DOCUMENT intent was sent with the request code OPEN_DIRECTORY_REQUEST_CODE. - // If the request code seen here doesn't match, it's the response to some other intent, - // and the below code shouldn't run at all. - super.onActivityResult(requestCode, resultCode, resultData); - if (requestCode == 100) { - if (resultCode == Activity.RESULT_OK) { - // The document selected by the user won't be returned in the intent. - // Instead, a URI to that document will be contained in the return intent - // provided to this method as a parameter. Pull that uri using "resultData.getData()" - if (resultData != null && resultData.getData() != null) { - fileuri = resultData.getData(); - System.out.println(fileuri.toString()); - if (isfolder) { - fprefix.setText(prefix); - fprefix.setHint(getResources().getString(R.string.upload_prefix)); - fprefixlabel.setText(getResources().getString(R.string.upload_prefix)); - fileUpload.setText(getResources().getString(R.string.upload_calculate)); - fileUpload.setEnabled(false); - calculateSize(); - } else { - fprefix.setText(prefix+getDisplayName(fileuri)); - } - //System.out.println("File selected successfully"); - //System.out.println("content://com.android.externalstorage.documents"+file.getPath()); - } else { - Toast.makeText(Uploader.this, getResources().getString(R.string.file_path_fail), Toast.LENGTH_SHORT).show(); - finish(); - } - } else { - //System.out.println("User cancelled file browsing {}"); - finish(); - } - } - } - - private File readContentToFile(Uri uri) throws IOException { - final File file = new File(getCacheDir(), getDisplayName(uri)); - try ( - final InputStream in = getContentResolver().openInputStream(uri); - final OutputStream out = new FileOutputStream(file, false); - ) { - byte[] buffer = new byte[1024]; - for (int len; (len = in.read(buffer)) != -1; ) { - out.write(buffer, 0, len); - } - return file; - } - } - - private String getDisplayName(Uri uri) { - final String[] projection = { MediaStore.Images.Media.DISPLAY_NAME }; - try ( - Cursor cursor = getContentResolver().query(uri, projection, null, null, null); - ){ - int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME); - if (cursor.moveToFirst()) { - return cursor.getString(columnIndex); - } - } - // If the display name is not found for any reason, use the Uri path as a fallback. - Log.w(TAG, "Couldnt determine DISPLAY_NAME for Uri. Falling back to Uri path: " + uri.getPath()); - return uri.getPath(); - } - - public void putS3Object(String bucket, String objectKey, File file) { - if (file.length() <= MAX_SINGLE_PART_UPLOAD_BYTES) { - putS3ObjectSinglePart(bucket, objectKey, file); - } else { - putS3ObjectMultiPart(bucket, objectKey, file); - } - } - - private void putS3ObjectSinglePart(String bucket, String objectKey, File file) { - PutObjectRequest request = new PutObjectRequest(bucket, objectKey, file); - PutObjectResult result = s3client.putObject(request); - long bytesPushed = result.getMetadata().getContentLength(); - transfered++; - //LOGGER.info("Pushed {} bytes to s3://{}/{}", bytesPushed, bucket, objectKey); - } - - private void putS3ObjectMultiPart(String bucket, String objectKey, File file) { - long contentLength = file.length(); - long partSize = MAX_SINGLE_PART_UPLOAD_BYTES; - List partETags = new ArrayList<>(); - - // Initiate the multipart upload. - InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucket, objectKey); - InitiateMultipartUploadResult initResponse = s3client.initiateMultipartUpload(initRequest); - - // Upload the file parts. - long fileOffset = 0; - try{ - for (int partNumber = 1; fileOffset < contentLength && !cancel; ++partNumber) { - // Because the last part could be less than 5 MB, adjust the part size as needed. - partSize = Math.min(partSize, (contentLength - fileOffset)); - - // Create the request to upload a part. - UploadPartRequest uploadRequest = new UploadPartRequest() - .withBucketName(bucket) - .withKey(objectKey) - .withUploadId(initResponse.getUploadId()) - .withPartNumber(partNumber) - .withFileOffset(fileOffset) - .withFile(file) - .withPartSize(partSize); - - // Upload the part and add the response's ETag to our list. - UploadPartResult uploadResult = s3client.uploadPart(uploadRequest); - //LOGGER.info("Uploading part {} of Object s3://{}/{}", partNumber, bucket, objectKey); - partETags.add(uploadResult.getPartETag()); - - fileOffset += partSize; - transfered++; - } - - // Complete the multipart upload. - CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(bucket, objectKey, initResponse.getUploadId(), partETags); - s3client.completeMultipartUpload(compRequest); - } catch (AbortedException | AmazonS3Exception e) { - e.printStackTrace(); - AbortMultipartUploadRequest abort = new AbortMultipartUploadRequest(bucket, objectKey, initResponse.getUploadId()); - s3client.abortMultipartUpload(abort); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - //finish(); - } - } - - private void calculateSize() { - calculateProgress = new Thread(new Runnable() { - - @Override - public void run() { - try { - //Your code goes here - document = DocumentFile.fromTreeUri(getApplicationContext(), fileuri); - DocumentFile[] filelist = document.listFiles(); - ArrayList filepath = new ArrayList(); - int treelevel = 0; - ArrayList fileindex = new ArrayList(); - fileindex.add(0); - for (int i = 0; i < filelist.length; i++) { - filepath.add(filelist[i].getName()); - if(filelist[i].isDirectory()) { - treelevel++; - fileindex.add(0); - document = filelist[i]; - filelist = document.listFiles(); - while (treelevel >= 1 && fileindex.get(treelevel) < filelist.length+1) { - if(fileindex.get(treelevel) == filelist.length) { - fileindex.remove(treelevel); - document = document.getParentFile(); - filelist = document.listFiles(); - treelevel--; - filepath.remove(treelevel); - fileindex.set(treelevel, fileindex.get(treelevel)+1); - } else { - filepath.add(filelist[fileindex.get(treelevel)].getName()); - if (filelist[fileindex.get(treelevel)].isDirectory()) { - document = filelist[fileindex.get(treelevel)]; - filelist = document.listFiles(); - treelevel++; - fileindex.add(0); - } else { - filepath.remove(treelevel); - if(filelist[fileindex.get(treelevel)].length()%MAX_SINGLE_PART_UPLOAD_BYTES == 0) { - filesize = filesize+(filelist[fileindex.get(treelevel)].length()/MAX_SINGLE_PART_UPLOAD_BYTES); - } else { - filesize = filesize+((filelist[fileindex.get(treelevel)].length()/MAX_SINGLE_PART_UPLOAD_BYTES)+1); - } - fileindex.set(treelevel, fileindex.get(treelevel)+1); - } - } - } - //document = document.getParentFile(); - //filelist = document.listFiles(); - //treelevel--; - } else { - if(filelist[i].length()%MAX_SINGLE_PART_UPLOAD_BYTES == 0) { - filesize = filesize+(filelist[i].length()/MAX_SINGLE_PART_UPLOAD_BYTES); - } else { - filesize = filesize+((filelist[i].length()/MAX_SINGLE_PART_UPLOAD_BYTES)+1); - } - } - filepath.clear(); - fileindex.clear(); - fileindex.add(0); - } - - runOnUiThread(new Runnable() { - - @Override - public void run() { - fileUpload.setText(getResources().getString(R.string.batch_upload_button)); - fileUpload.setEnabled(true); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - //Toast.makeText(getApplicationContext(),getResources().getString(R.string.media_list_fail), Toast.LENGTH_SHORT).show(); - //finish(); - } - } - }); - calculateProgress.start(); - } - -} \ No newline at end of file diff --git a/app/src/main/java/asgardius/page/s3music/VideoPlayer.java b/app/src/main/java/asgardius/page/s3music/VideoPlayer.java index 6bc3797..89d0431 100644 --- a/app/src/main/java/asgardius/page/s3music/VideoPlayer.java +++ b/app/src/main/java/asgardius/page/s3music/VideoPlayer.java @@ -69,7 +69,6 @@ public class VideoPlayer extends AppCompatActivity { MediaSessionCompat mediaSession; MediaSessionConnector mediaSessionConnector; StyledPlayerView.ControllerVisibilityListener control; - AppOpsManager appOpsManager; private PlayerNotificationManager playerNotificationManager; private int notificationId = 1234; boolean isplaylist; @@ -77,6 +76,36 @@ public class VideoPlayer extends AppCompatActivity { String videoURL, title; Rational ratio; + public static String URLify(String str) { + str = str.trim(); + int length = str.length(); + int trueL = length; + if(str.contains(" ")) { + for(int i = 0; i < length; i++) { + if(str.charAt(i) == ' ') { + trueL = trueL + 2; + } + } + char[] oldArr = str.toCharArray(); + char[] newArr = new char[trueL]; + int x = 0; + for(int i = 0; i < length; i++) { + if(oldArr[i] == ' ') { + newArr[x] = '%'; + newArr[x+1] = '2'; + newArr[x+2] = '0'; + x += 3; + } else { + newArr[x] = oldArr[i]; + x++; + } + } + str = new String(newArr, 0, trueL); + } + return str; + } + + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -91,7 +120,6 @@ public class VideoPlayer extends AppCompatActivity { channel.setSound(null, null); manager.createNotificationChannel(channel); } - appOpsManager = (AppOpsManager)getSystemService(Context.APP_OPS_SERVICE); mediaSession = new MediaSessionCompat(this, getPackageName()); mediaSessionConnector = new MediaSessionConnector(mediaSession); hideSystemBars(); @@ -156,7 +184,7 @@ public class VideoPlayer extends AppCompatActivity { if (isplaylist) { for (int i = 0; i < queue.size(); i++) { if (names.get(i).endsWith(".m3u8")) { - MediaItem mediaItem = MediaItem.fromUri(Share.URLify(queue.get(i))); + MediaItem mediaItem = MediaItem.fromUri(URLify(queue.get(i))); player.addMediaItem(mediaItem); } else { mediaSource = new ProgressiveMediaSource.Factory( @@ -165,7 +193,7 @@ public class VideoPlayer extends AppCompatActivity { .setUpstreamDataSourceFactory(new DefaultHttpDataSource.Factory() .setUserAgent("S3 Manager")) .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR) - ).createMediaSource(MediaItem.fromUri(Share.URLify(queue.get(i)))); + ).createMediaSource(MediaItem.fromUri(URLify(queue.get(i)))); player.addMediaSource(mediaSource); } } @@ -173,7 +201,7 @@ public class VideoPlayer extends AppCompatActivity { player.seekTo(names.indexOf(title), 0); } else { if (title.endsWith(".m3u8")) { - MediaItem mediaItem = MediaItem.fromUri(Share.URLify(videoURL)); + MediaItem mediaItem = MediaItem.fromUri(URLify(videoURL)); player.setMediaItem(mediaItem); } else { mediaSource = new ProgressiveMediaSource.Factory( @@ -182,7 +210,7 @@ public class VideoPlayer extends AppCompatActivity { .setUpstreamDataSourceFactory(new DefaultHttpDataSource.Factory() .setUserAgent("S3 Manager")) .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR) - ).createMediaSource(MediaItem.fromUri(Share.URLify(videoURL))); + ).createMediaSource(MediaItem.fromUri(URLify(videoURL))); player.setMediaSource(mediaSource); } player.prepare(); @@ -283,49 +311,6 @@ public class VideoPlayer extends AppCompatActivity { Objects.requireNonNull(getSupportActionBar()).show(); } - - protected void enterPIPMode() { - try { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N - && this.getPackageManager() - .hasSystemFeature( - PackageManager.FEATURE_PICTURE_IN_PICTURE) && appOpsManager.checkOpNoThrow( - AppOpsManager.OPSTR_PICTURE_IN_PICTURE, - this.getPackageManager().getApplicationInfo(this.getPackageName(), - PackageManager.GET_META_DATA).uid, this.getPackageName()) - == AppOpsManager.MODE_ALLOWED) { - videoPosition = player.getCurrentPosition(); - playerView.setUseController(false); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - if(player.getVideoFormat() != null) { - ratio = new Rational(Math.round(player.getVideoFormat().width*20*player.getVideoSize().pixelWidthHeightRatio), Math.round(player.getVideoFormat().height*20)); - } else if(player.getAudioFormat() != null) { - ratio = new Rational(player.getAudioFormat().width, player.getAudioFormat().height); - } else { - ratio = new Rational(1, 1); - } - PictureInPictureParams params = new PictureInPictureParams.Builder().setAspectRatio(ratio).build(); - this.enterPictureInPictureMode(params); - }else { - this.enterPictureInPictureMode(); - } - } - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - } - - public boolean isScreenOn(Context context) { - DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); - boolean screenOn = false; - for (Display display : dm.getDisplays()) { - if (display.getState() == Display.STATE_ON) { - screenOn = true; - } - } - return screenOn; - } - @Override public void onDestroy() { @@ -357,11 +342,6 @@ public class VideoPlayer extends AppCompatActivity { hideSystemBars(); } - public void onUserLeaveHint() { - super.onUserLeaveHint(); - enterPIPMode(); - } - protected void onNewIntent(Intent intent) { videoURL = intent.getStringExtra("video_url"); title = intent.getStringExtra("title"); @@ -411,45 +391,8 @@ public class VideoPlayer extends AppCompatActivity { super.onNewIntent(intent); } - public void onStop() { - try { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S - && this.getPackageManager() - .hasSystemFeature( - PackageManager.FEATURE_PICTURE_IN_PICTURE) && appOpsManager.checkOpNoThrow( - AppOpsManager.OPSTR_PICTURE_IN_PICTURE, - this.getPackageManager().getApplicationInfo(this.getPackageName(), - PackageManager.GET_META_DATA).uid, this.getPackageName()) - == AppOpsManager.MODE_ALLOWED && isScreenOn(this) && this.isInPictureInPictureMode()) { - finish(); - } - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - super.onStop(); - } - /*static void deleteCache(Context context, StandaloneDatabaseProvider database) { SimpleCache.delete(new File(context.getCacheDir(), "media"), database); }*/ - public void onBackPressed() { - try { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N - && this.getPackageManager() - .hasSystemFeature( - PackageManager.FEATURE_PICTURE_IN_PICTURE) && appOpsManager.checkOpNoThrow( - AppOpsManager.OPSTR_PICTURE_IN_PICTURE, - this.getPackageManager().getApplicationInfo(this.getPackageName(), - PackageManager.GET_META_DATA).uid, this.getPackageName()) - == AppOpsManager.MODE_ALLOWED) { - enterPIPMode(); - } else { - super.onBackPressed(); - } - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - super.onBackPressed(); - } - } } \ No newline at end of file