From c03d14dc068dd6569f489e4f0bf3316d211ff4e5 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 27 Sep 2023 23:17:03 +0200 Subject: [PATCH] saving working (#1173) * saving working * log fix --- .../radiodroid2/ActivityMain.java | 92 ++++++++++++-- .../radiodroid2/StationSaveManager.java | 119 +++++++++++++----- 2 files changed, 172 insertions(+), 39 deletions(-) diff --git a/app/src/main/java/net/programmierecke/radiodroid2/ActivityMain.java b/app/src/main/java/net/programmierecke/radiodroid2/ActivityMain.java index 944630cd5..163e0f12c 100644 --- a/app/src/main/java/net/programmierecke/radiodroid2/ActivityMain.java +++ b/app/src/main/java/net/programmierecke/radiodroid2/ActivityMain.java @@ -9,8 +9,10 @@ import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Resources; +import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; +import android.provider.DocumentsContract; import android.text.TextUtils; import android.util.Log; import android.view.Menu; @@ -65,7 +67,13 @@ import net.programmierecke.radiodroid2.station.DataRadioStation; import net.programmierecke.radiodroid2.station.StationsFilter; +import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; import java.util.Date; import okhttp3.OkHttpClient; @@ -99,6 +107,10 @@ public class ActivityMain extends AppCompatActivity implements SearchView.OnQuer public static final int PERM_REQ_STORAGE_FAV_SAVE = 1; public static final int PERM_REQ_STORAGE_FAV_LOAD = 2; + // Request code for creating a PDF document. + private static final int ACTION_SAVE_FILE = 1; + private static final int ACTION_LOAD_FILE = 2; + private SearchView mSearchView; private AppBarLayout appBarLayout; @@ -149,13 +161,16 @@ protected void onCreate(Bundle savedInstanceState) { setTheme(Utils.getThemeResId(this)); setContentView(R.layout.layout_main); + Log.d(TAG, "FilesDir: "+getFilesDir().getAbsolutePath()); + Log.d(TAG, "CacheDir: "+getCacheDir().getAbsolutePath()); try { File dir = new File(getFilesDir().getAbsolutePath()); if (dir.isDirectory()) { + String[] children = dir.list(); for (String aChildren : children) { if (BuildConfig.DEBUG) { - Log.d("MAIN", "delete file:" + aChildren); + Log.d(TAG, "delete file:" + aChildren); } try { new File(dir, aChildren).delete(); @@ -433,12 +448,18 @@ public void onRequestPermissionsResult(int requestCode, case PERM_REQ_STORAGE_FAV_LOAD: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { LoadFavourites(); + } else { + Log.w(TAG,"permission not granted -> simple load"); + LoadFavouritesSimple(); } return; } case PERM_REQ_STORAGE_FAV_SAVE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { SaveFavourites(); + } else { + Log.w(TAG,"permission not granted -> simple save"); + SaveFavouritesSimple(); } return; } @@ -667,17 +688,50 @@ public void onFocusChange(View v, boolean hasFocus) { return true; } - /*@Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - - if (requestCode == 1 && resultCode == RESULT_OK) { - String filePath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH); - RadioDroidApp radioDroidApp = (RadioDroidApp) getApplication(); - FavouriteManager favouriteManager = radioDroidApp.getFavouriteManager(); - favouriteManager.SaveM3U(filePath, "radiodroid.m3u"); + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent resultData) { + super.onActivityResult(requestCode, resultCode, resultData); + + if (requestCode == ACTION_SAVE_FILE && resultCode == RESULT_OK) { + Uri uri = null; + if (resultData != null) { + uri = resultData.getData(); + Log.d(TAG, "Choosen save path: " + uri); + RadioDroidApp radioDroidApp = (RadioDroidApp) getApplication(); + FavouriteManager favouriteManager = radioDroidApp.getFavouriteManager(); + HistoryManager historyManager = radioDroidApp.getHistoryManager(); + try{ + OutputStream os = getContentResolver().openOutputStream(uri); + OutputStreamWriter writer = new OutputStreamWriter(os); + if (selectedMenuItem == R.id.nav_item_starred) { + favouriteManager.SaveM3UWriter(writer); + }else if (selectedMenuItem == R.id.nav_item_history) { + historyManager.SaveM3UWriter(writer); + } + } + catch (Exception e){ + Log.e(TAG, "Unable to write to file " + e); + } + } + } + if (requestCode == ACTION_LOAD_FILE && resultCode == RESULT_OK) { + Uri uri = null; + if (resultData != null) { + uri = resultData.getData(); + Log.d(TAG, "Choosen load path: " + uri); + RadioDroidApp radioDroidApp = (RadioDroidApp) getApplication(); + FavouriteManager favouriteManager = radioDroidApp.getFavouriteManager(); + try{ + InputStream is = getContentResolver().openInputStream(uri); + InputStreamReader reader = new InputStreamReader(is); + favouriteManager.LoadM3USimple(reader); + } + catch (Exception e){ + Log.e(TAG, "Unable to load to file " + e); + } + } } - }*/ + } @Override public void onFileSelected(FileDialog dialog, File file) { @@ -710,6 +764,14 @@ void SaveFavourites() { dialog.show(getSupportFragmentManager(), SaveFileDialog.class.getName()); } + void SaveFavouritesSimple() { + Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType("audio/x-mpegurl"); + intent.putExtra(Intent.EXTRA_TITLE, "playlist.m3u"); + startActivityForResult(intent, ACTION_SAVE_FILE); + } + void LoadFavourites() { OpenFileDialog dialogOpen = new OpenFileDialog(); dialogOpen.setStyle(DialogFragment.STYLE_NO_TITLE, Utils.getThemeResId(this)); @@ -719,6 +781,14 @@ void LoadFavourites() { dialogOpen.show(getSupportFragmentManager(), OpenFileDialog.class.getName()); } + void LoadFavouritesSimple() { + Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType("audio/x-mpegurl"); + intent.putExtra(Intent.EXTRA_TITLE, "playlist.m3u"); + startActivityForResult(intent, ACTION_LOAD_FILE); + } + @Override public boolean onOptionsItemSelected(MenuItem menuItem) { switch (menuItem.getItemId()) { diff --git a/app/src/main/java/net/programmierecke/radiodroid2/StationSaveManager.java b/app/src/main/java/net/programmierecke/radiodroid2/StationSaveManager.java index 8f7b823fb..35d0a48ed 100644 --- a/app/src/main/java/net/programmierecke/radiodroid2/StationSaveManager.java +++ b/app/src/main/java/net/programmierecke/radiodroid2/StationSaveManager.java @@ -24,6 +24,8 @@ import java.io.File; import java.io.FileReader; import java.io.FileWriter; +import java.io.Reader; +import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -361,6 +363,32 @@ protected void onPostExecute(Boolean result) { }.execute(); } + public void SaveM3USimple(final String filePath, final String fileName) { + Toast toast = Toast.makeText(context, context.getResources().getString(R.string.notify_save_playlist_now, filePath, fileName), Toast.LENGTH_LONG); + toast.show(); + + new AsyncTask() { + @Override + protected Boolean doInBackground(Void... params) { + return SaveM3UInternal(filePath, fileName); + } + + @Override + protected void onPostExecute(Boolean result) { + if (result.booleanValue()) { + Log.i("SAVE", "OK"); + Toast toast = Toast.makeText(context, context.getResources().getString(R.string.notify_save_playlist_ok, filePath, fileName), Toast.LENGTH_LONG); + toast.show(); + } else { + Log.i("SAVE", "NOK"); + Toast toast = Toast.makeText(context, context.getResources().getString(R.string.notify_save_playlist_nok, filePath, fileName), Toast.LENGTH_LONG); + toast.show(); + } + super.onPostExecute(result); + } + }.execute(); + } + public void LoadM3U(final String filePath, final String fileName) { Toast toast = Toast.makeText(context, context.getResources().getString(R.string.notify_load_playlist_now, filePath, fileName), Toast.LENGTH_LONG); toast.show(); @@ -391,6 +419,36 @@ protected void onPostExecute(List result) { }.execute(); } + public void LoadM3USimple(final Reader reader) { + Toast toast = Toast.makeText(context, context.getResources().getString(R.string.notify_load_playlist_now, "", ""), Toast.LENGTH_LONG); + toast.show(); + + new AsyncTask>() { + @Override + protected List doInBackground(Void... params) { + return LoadM3UReader(reader); + } + + @Override + protected void onPostExecute(List result) { + if (result != null) { + Log.i("LOAD", "Loaded " + result.size() + "stations"); + addMultiple(result); + Toast toast = Toast.makeText(context, context.getResources().getString(R.string.notify_load_playlist_ok, result.size(), "", ""), Toast.LENGTH_LONG); + toast.show(); + } else { + Log.e("LOAD", "Load failed"); + Toast toast = Toast.makeText(context, context.getResources().getString(R.string.notify_load_playlist_nok, "", ""), Toast.LENGTH_LONG); + toast.show(); + } + + notifyObservers(); + + super.onPostExecute(result); + } + }.execute(); + } + protected final String M3U_PREFIX = "#RADIOBROWSERUUID:"; boolean SaveM3UInternal(String filePath, String fileName) { @@ -400,38 +458,33 @@ boolean SaveM3UInternal(String filePath, String fileName) { try { File f = new File(filePath, fileName); BufferedWriter bw = new BufferedWriter(new FileWriter(f, false)); - bw.write("#EXTM3U\n"); - for (DataRadioStation station : listStations) { - /* - String result = null; - for (int i = 0; i < 20; i++) { - result = Utils.getRealStationLink(httpClient, context, station.StationUuid); - if (result != null) { - break; - } - try { - Thread.sleep(500); - } catch (InterruptedException e) { - Log.e("ERR", "Play() " + e); - } - } - */ - - //if (result != null) { - bw.write(M3U_PREFIX + station.StationUuid + "\n"); - bw.write("#EXTINF:-1," + station.Name + "\n"); - bw.write(station.StreamUrl + "\n\n"); - //} - } - bw.flush(); - bw.close(); - + var r = SaveM3UWriter(bw); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)))); } else { MediaScannerConnection .scanFile(context, new String[]{f.getAbsolutePath()}, null, null); } + return r; + } catch (Exception e) { + Log.e("Exception", "File write failed: " + e.toString()); + return false; + } + } + + public boolean SaveM3UWriter(Writer bw) { + final RadioDroidApp radioDroidApp = (RadioDroidApp) context.getApplicationContext(); + final OkHttpClient httpClient = radioDroidApp.getHttpClient(); + + try { + bw.write("#EXTM3U\n"); + for (DataRadioStation station : listStations) { + bw.write(M3U_PREFIX + station.StationUuid + "\n"); + bw.write("#EXTINF:-1," + station.Name + "\n"); + bw.write(station.StreamUrl + "\n\n"); + } + bw.flush(); + bw.close(); return true; } catch (Exception e) { @@ -443,15 +496,25 @@ boolean SaveM3UInternal(String filePath, String fileName) { List LoadM3UInternal(String filePath, String fileName) { try { File f = new File(filePath, fileName); + FileReader fr = new FileReader(f); + return LoadM3UReader(fr); + } catch (Exception e) { + Log.e("LOAD", "File read failed: " + e.toString()); + return null; + } + } - BufferedReader br = new BufferedReader(new FileReader(f)); + List LoadM3UReader(Reader reader) { + try { String line; final RadioDroidApp radioDroidApp = (RadioDroidApp) context.getApplicationContext(); final OkHttpClient httpClient = radioDroidApp.getHttpClient(); ArrayList listUuids = new ArrayList(); + BufferedReader br = new BufferedReader(reader); while ((line = br.readLine()) != null) { + Log.v("LOAD", "line: "+line); if (line.startsWith(M3U_PREFIX)) { try { String uuid = line.substring(M3U_PREFIX.length()).trim(); @@ -468,7 +531,7 @@ List LoadM3UInternal(String filePath, String fileName) { return listStationsNew; } } catch (Exception e) { - Log.e("LOAD", "File write failed: " + e.toString()); + Log.e("LOAD", "File read failed: " + e.toString()); return null; } List loadedItems = new ArrayList<>();