OSDN Git Service

FUJIのファイルダウンロード中、進捗ダイアログの進捗が適切に表現されていなかったのを修正。する。
[gokigen/Gr2Control.git] / app / src / main / java / net / osdn / gokigen / gr2control / playback / detail / MyContentDownloader.java
1 package net.osdn.gokigen.gr2control.playback.detail;
2
3 import android.app.Activity;
4 import android.app.AlertDialog;
5 import android.app.ProgressDialog;
6 import android.content.ContentResolver;
7 import android.content.ContentValues;
8 import android.content.Intent;
9 import android.content.SharedPreferences;
10 import android.net.Uri;
11 import android.os.Environment;
12 import android.provider.MediaStore;
13 import android.util.Log;
14 import android.view.View;
15
16 import com.google.android.material.snackbar.Snackbar;
17
18 import net.osdn.gokigen.gr2control.R;
19 import net.osdn.gokigen.gr2control.camera.ICameraFileInfo;
20 import net.osdn.gokigen.gr2control.camera.playback.IDownloadContentCallback;
21 import net.osdn.gokigen.gr2control.camera.playback.IPlaybackControl;
22 import net.osdn.gokigen.gr2control.camera.playback.ProgressEvent;
23 import net.osdn.gokigen.gr2control.preference.IPreferencePropertyAccessor;
24
25 import java.io.File;
26 import java.io.FileOutputStream;
27 import java.text.SimpleDateFormat;
28 import java.util.Calendar;
29 import java.util.Locale;
30
31 import androidx.annotation.NonNull;
32 import androidx.preference.PreferenceManager;
33
34 /**
35  *   コンテントのダウンロード
36  *
37  */
38 public class MyContentDownloader implements IDownloadContentCallback
39 {
40     private final String TAG = toString();
41     private final Activity activity;
42     private final IPlaybackControl playbackControl;
43     private static final String RAW_SUFFIX_1 = ".DNG";
44     private static final String RAW_SUFFIX_2 = ".ORF";
45     private static final String RAW_SUFFIX_3 = ".PEF";
46     private static final String RAW_SUFFIX_4 = ".RAF";
47     private static final String MOVIE_SUFFIX = ".MOV";
48     private static final String JPEG_SUFFIX = ".JPG";
49     private ProgressDialog downloadDialog = null;
50     private FileOutputStream outputStream = null;
51     private String targetFileName = "";
52     private String filepath = "";
53     private String mimeType = "image/jpeg";
54
55     /**
56      *   コンストラクタ
57      *
58      */
59     public MyContentDownloader(@NonNull Activity activity, @NonNull final IPlaybackControl playbackControl)
60     {
61         this.activity = activity;
62         this.playbackControl = playbackControl;
63     }
64
65     /**
66      *   ダウンロードの開始
67      *
68      */
69     public void startDownload(final ICameraFileInfo fileInfo, final String appendTitle, String replaceJpegSuffix, boolean isSmallSize)
70     {
71         if (fileInfo == null)
72         {
73             Log.v(TAG, "startDownload() ICameraFileInfo is NULL...");
74             return;
75         }
76         Log.v(TAG, "startDownload() " + fileInfo.getFilename());
77
78         // Download the image.
79         try
80         {
81             Calendar calendar = Calendar.getInstance();
82             String extendName = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.getDefault()).format(calendar.getTime());
83             targetFileName = fileInfo.getOriginalFilename().toUpperCase();
84             if (replaceJpegSuffix != null)
85             {
86                 targetFileName = targetFileName.replace(JPEG_SUFFIX, replaceJpegSuffix);
87             }
88             if (targetFileName.toUpperCase().contains(RAW_SUFFIX_1))
89             {
90                 mimeType = "image/x-adobe-dng";
91                 isSmallSize = false;
92             }
93             else if (targetFileName.toUpperCase().contains(RAW_SUFFIX_2))
94             {
95                 mimeType = "image/x-olympus-orf";
96                 isSmallSize = false;
97             }
98             else if (targetFileName.toUpperCase().contains(RAW_SUFFIX_3))
99             {
100                 mimeType = "image/x-pentax-pef";
101                 isSmallSize = false;
102             }
103             else if (targetFileName.toUpperCase().contains(RAW_SUFFIX_4))
104             {
105                 mimeType = "image/x-fuji-raf";
106                 isSmallSize = false;
107             }
108             else if (targetFileName.toUpperCase().contains(MOVIE_SUFFIX))
109             {
110                 mimeType =  "video/mp4";
111                 isSmallSize = false;
112             }
113             else
114             {
115                 mimeType = "image/jpeg";
116             }
117
118             ////// ダイアログの表示
119             activity.runOnUiThread(new Runnable() {
120                 @Override
121                 public void run() {
122                     downloadDialog = new ProgressDialog(activity);
123                     downloadDialog.setTitle(activity.getString(R.string.dialog_download_file_title) + appendTitle);
124                     downloadDialog.setMessage(activity.getString(R.string.dialog_download_message) + " " + targetFileName);
125                     downloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
126                     downloadDialog.setCancelable(false);
127                     downloadDialog.show();
128                 }
129             });
130             String fileName = fileInfo.getDirectoryPath() + "/" + fileInfo.getFilename();
131
132             final String directoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/" + activity.getString(R.string.app_name2) + "/";
133             String suffix = targetFileName.substring(targetFileName.indexOf("."));
134             String picName = targetFileName.substring(0, targetFileName.indexOf("."));
135             String outputFileName = picName + "_" +  extendName + suffix;
136             filepath = new File(directoryPath.toLowerCase(), outputFileName.toLowerCase()).getPath();
137             try
138             {
139                 final File directory = new File(directoryPath);
140                 if (!directory.exists())
141                 {
142                     if (!directory.mkdirs())
143                     {
144                         Log.v(TAG, "MKDIR FAIL. : " + directoryPath);
145                     }
146                 }
147                 outputStream = new FileOutputStream(filepath);
148             }
149             catch (Exception e)
150             {
151                 final String message = e.getMessage();
152                 activity.runOnUiThread(new Runnable() {
153                     @Override
154                     public void run() {
155                         if (downloadDialog != null) {
156                             downloadDialog.dismiss();
157                         }
158                         presentMessage(activity.getString(R.string.download_control_save_failed), message);
159                     }
160                 });
161             }
162             Log.v(TAG, "downloadContent : " + fileName + " (small: " + isSmallSize + ")");
163             playbackControl.downloadContent(null, fileName, isSmallSize, this);
164         }
165         catch (Exception ex)
166         {
167             ex.printStackTrace();
168         }
169     }
170
171     @Override
172     public void onProgress(byte[] bytes, int length, ProgressEvent progressEvent)
173     {
174         if (downloadDialog != null)
175         {
176             int percent = (int)(progressEvent.getProgress() * 100.0f);
177             downloadDialog.setProgress(percent);
178             //downloadDialog.setCancelable(progressEvent.isCancellable()); // キャンセルできるようにしないほうが良さそうなので
179             //Log.v(TAG, "DOWNLOAD (" + percent + "%) " + bytes.length);
180         }
181         try
182         {
183             if (outputStream != null)
184             {
185                 outputStream.write(bytes, 0, length);
186             }
187         }
188         catch (Exception e)
189         {
190             e.printStackTrace();
191         }
192     }
193
194     @Override
195     public void onCompleted()
196     {
197         try
198         {
199             if (outputStream != null)
200             {
201                 outputStream.flush();
202                 outputStream.close();
203                 outputStream = null;
204             }
205             //if ((!targetFileName.toUpperCase().endsWith(RAW_SUFFIX_1))&&(!targetFileName.toUpperCase().endsWith(RAW_SUFFIX_2))&&(!targetFileName.toUpperCase().endsWith(RAW_SUFFIX_3)))
206             {
207                 // ギャラリーに受信したファイルを登録する
208                 long now = System.currentTimeMillis();
209                 ContentValues values = new ContentValues();
210                 ContentResolver resolver = activity.getContentResolver();
211                 values.put(MediaStore.Images.Media.MIME_TYPE, mimeType);
212                 values.put(MediaStore.Images.Media.DATA, filepath);
213                 values.put(MediaStore.Images.Media.DATE_ADDED, now);
214                 values.put(MediaStore.Images.Media.DATE_TAKEN, now);
215                 values.put(MediaStore.Images.Media.DATE_MODIFIED, now);
216                 Uri mediaValue = mimeType.contains("video") ? MediaStore.Video.Media.EXTERNAL_CONTENT_URI : MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
217                 final Uri content = resolver.insert(mediaValue, values);
218                 try
219                 {
220                     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
221                     if (preferences.getBoolean(IPreferencePropertyAccessor.SHARE_AFTER_SAVE, false))
222                     {
223                         activity.runOnUiThread(new Runnable()
224                         {
225                             @Override
226                             public void run()
227                             {
228                                 shareContent(content, mimeType);
229                             }
230                         });
231                     }
232                 }
233                 catch (Exception e)
234                 {
235                     e.printStackTrace();
236                 }
237
238             }
239             activity.runOnUiThread(new Runnable() {
240                 @Override
241                 public void run()
242                 {
243                     if (downloadDialog != null)
244                     {
245                         downloadDialog.dismiss();
246                     }
247                     View view = activity.findViewById(R.id.fragment1);
248                     Snackbar.make(view, activity.getString(R.string.download_control_save_success) + " " + targetFileName, Snackbar.LENGTH_SHORT).show();
249                     //Toast.makeText(activity, activity.getString(R.string.download_control_save_success) + " " + targetFileName, Toast.LENGTH_SHORT).show();
250                     System.gc();
251                 }
252             });
253         }
254         catch (Exception e)
255         {
256             final String message = e.getMessage();
257             activity.runOnUiThread(new Runnable() {
258                 @Override
259                 public void run() {
260                     if (downloadDialog != null)
261                     {
262                         downloadDialog.dismiss();
263                     }
264                     presentMessage(activity.getString(R.string.download_control_save_failed), message);
265                 }
266             });
267         }
268         System.gc();
269     }
270
271     @Override
272     public void onErrorOccurred(Exception e)
273     {
274         final String message = e.getMessage();
275         try
276         {
277             if (outputStream != null)
278             {
279                 outputStream.flush();
280                 outputStream.close();
281                 outputStream = null;
282             }
283         }
284         catch (Exception ex)
285         {
286             e.printStackTrace();
287             ex.printStackTrace();
288         }
289         activity.runOnUiThread(new Runnable()
290         {
291             @Override
292             public void run()
293             {
294                 if (downloadDialog != null)
295                 {
296                     downloadDialog.dismiss();
297                 }
298                 presentMessage(activity.getString(R.string.download_control_download_failed), message);
299                 System.gc();
300             }
301         });
302         System.gc();
303     }
304
305     /**
306      *   共有の呼び出し
307      *
308      * @param fileUri  ファイルUri
309      */
310     private void shareContent(final Uri fileUri, final String contentType)
311     {
312         Intent intent = new Intent();
313         intent.setAction(Intent.ACTION_SEND);
314         try
315         {
316             intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
317             intent.setType(contentType);   // "video/mp4"  or "image/jpeg"  or "image/x-adobe-dng"
318             intent.putExtra(Intent.EXTRA_STREAM, fileUri);
319             activity.startActivityForResult(intent, 0);
320         }
321         catch (Exception e)
322         {
323             e.printStackTrace();
324         }
325     }
326
327     private void presentMessage(final String title, final String message)
328     {
329         activity.runOnUiThread(new Runnable() {
330             @Override
331             public void run() {
332                 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
333                 builder.setTitle(title).setMessage(message);
334                 builder.show();
335             }
336         });
337     }
338 }