OSDN Git Service

Android SDK を 33 に更新。
[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     private boolean isDownloading = false;
55
56     /**
57      *   コンストラクタ
58      *
59      */
60     public MyContentDownloader(@NonNull Activity activity, @NonNull final IPlaybackControl playbackControl)
61     {
62         this.activity = activity;
63         this.playbackControl = playbackControl;
64     }
65
66     /**
67      *   ダウンロードの開始
68      *
69      */
70     public void startDownload(final ICameraFileInfo fileInfo, final String appendTitle, String replaceJpegSuffix, boolean isSmallSize)
71     {
72         if (fileInfo == null)
73         {
74             Log.v(TAG, "startDownload() ICameraFileInfo is NULL...");
75             return;
76         }
77         Log.v(TAG, "startDownload() " + fileInfo.getFilename());
78
79         // Download the image.
80         try
81         {
82             isDownloading = true;
83             Calendar calendar = Calendar.getInstance();
84             String extendName = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.getDefault()).format(calendar.getTime());
85             targetFileName = fileInfo.getOriginalFilename().toUpperCase();
86             if (replaceJpegSuffix != null)
87             {
88                 targetFileName = targetFileName.replace(JPEG_SUFFIX, replaceJpegSuffix);
89             }
90             if (targetFileName.toUpperCase().contains(RAW_SUFFIX_1))
91             {
92                 mimeType = "image/x-adobe-dng";
93                 isSmallSize = false;
94             }
95             else if (targetFileName.toUpperCase().contains(RAW_SUFFIX_2))
96             {
97                 mimeType = "image/x-olympus-orf";
98                 isSmallSize = false;
99             }
100             else if (targetFileName.toUpperCase().contains(RAW_SUFFIX_3))
101             {
102                 mimeType = "image/x-pentax-pef";
103                 isSmallSize = false;
104             }
105             else if (targetFileName.toUpperCase().contains(RAW_SUFFIX_4))
106             {
107                 mimeType = "image/x-fuji-raf";
108                 isSmallSize = false;
109             }
110             else if (targetFileName.toUpperCase().contains(MOVIE_SUFFIX))
111             {
112                 mimeType =  "video/mp4";
113                 isSmallSize = false;
114             }
115             else
116             {
117                 mimeType = "image/jpeg";
118             }
119
120             ////// ダイアログの表示
121             activity.runOnUiThread(new Runnable() {
122                 @Override
123                 public void run() {
124                     downloadDialog = new ProgressDialog(activity);
125                     downloadDialog.setTitle(activity.getString(R.string.dialog_download_file_title) + appendTitle);
126                     downloadDialog.setMessage(activity.getString(R.string.dialog_download_message) + " " + targetFileName);
127                     downloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
128                     downloadDialog.setCancelable(false);
129                     downloadDialog.show();
130                 }
131             });
132             String fileName = fileInfo.getDirectoryPath() + "/" + fileInfo.getFilename();
133
134             final String directoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/" + activity.getString(R.string.app_name2) + "/";
135             String suffix = targetFileName.substring(targetFileName.indexOf("."));
136             String picName = targetFileName.substring(0, targetFileName.indexOf("."));
137             String outputFileName = picName + "_" +  extendName + suffix;
138             filepath = new File(directoryPath.toLowerCase(), outputFileName.toLowerCase()).getPath();
139             try
140             {
141                 final File directory = new File(directoryPath);
142                 if (!directory.exists())
143                 {
144                     if (!directory.mkdirs())
145                     {
146                         Log.v(TAG, "MKDIR FAIL. : " + directoryPath);
147                     }
148                 }
149                 outputStream = new FileOutputStream(filepath);
150             }
151             catch (Exception e)
152             {
153                 final String message = e.getMessage();
154                 activity.runOnUiThread(new Runnable() {
155                     @Override
156                     public void run() {
157                         if (downloadDialog != null) {
158                             downloadDialog.dismiss();
159                         }
160                         downloadDialog = null;
161                         isDownloading = false;
162                         presentMessage(activity.getString(R.string.download_control_save_failed), message);
163                     }
164                 });
165             }
166             Log.v(TAG, "downloadContent : " + fileName + " (small: " + isSmallSize + ")");
167             playbackControl.downloadContent(null, fileName, isSmallSize, this);
168         }
169         catch (Exception ex)
170         {
171             ex.printStackTrace();
172             activity.runOnUiThread(new Runnable() {
173                 @Override
174                 public void run() {
175                     try
176                     {
177                         if (downloadDialog != null) {
178                             downloadDialog.dismiss();
179                         }
180                     }
181                     catch (Exception e)
182                     {
183                         e.printStackTrace();
184                     }
185                     downloadDialog = null;
186                     isDownloading = false;
187                 }
188             });
189         }
190     }
191
192     @Override
193     public void onProgress(byte[] bytes, int length, ProgressEvent progressEvent)
194     {
195         if (downloadDialog != null)
196         {
197             int percent = (int)(progressEvent.getProgress() * 100.0f);
198             downloadDialog.setProgress(percent);
199             //downloadDialog.setCancelable(progressEvent.isCancellable()); // キャンセルできるようにしないほうが良さそうなので
200             //Log.v(TAG, "DOWNLOAD (" + percent + "%) " + bytes.length);
201         }
202         try
203         {
204             if (outputStream != null)
205             {
206                 outputStream.write(bytes, 0, length);
207             }
208         }
209         catch (Exception e)
210         {
211             e.printStackTrace();
212         }
213     }
214
215     @Override
216     public void onCompleted()
217     {
218         try
219         {
220             if (outputStream != null)
221             {
222                 outputStream.flush();
223                 outputStream.close();
224                 outputStream = null;
225             }
226             //if ((!targetFileName.toUpperCase().endsWith(RAW_SUFFIX_1))&&(!targetFileName.toUpperCase().endsWith(RAW_SUFFIX_2))&&(!targetFileName.toUpperCase().endsWith(RAW_SUFFIX_3)))
227             {
228                 // ギャラリーに受信したファイルを登録する
229                 long now = System.currentTimeMillis();
230                 ContentValues values = new ContentValues();
231                 ContentResolver resolver = activity.getContentResolver();
232                 values.put(MediaStore.Images.Media.MIME_TYPE, mimeType);
233                 values.put(MediaStore.Images.Media.DATA, filepath);
234                 values.put(MediaStore.Images.Media.DATE_ADDED, now);
235                 values.put(MediaStore.Images.Media.DATE_TAKEN, now);
236                 values.put(MediaStore.Images.Media.DATE_MODIFIED, now);
237                 Uri mediaValue = mimeType.contains("video") ? MediaStore.Video.Media.EXTERNAL_CONTENT_URI : MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
238                 final Uri content = resolver.insert(mediaValue, values);
239                 try
240                 {
241                     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
242                     if (preferences.getBoolean(IPreferencePropertyAccessor.SHARE_AFTER_SAVE, false))
243                     {
244                         activity.runOnUiThread(new Runnable()
245                         {
246                             @Override
247                             public void run()
248                             {
249                                 shareContent(content, mimeType);
250                             }
251                         });
252                     }
253                 }
254                 catch (Exception e)
255                 {
256                     e.printStackTrace();
257                 }
258
259             }
260             activity.runOnUiThread(new Runnable() {
261                 @Override
262                 public void run()
263                 {
264                     if (downloadDialog != null)
265                     {
266                         downloadDialog.dismiss();
267                     }
268                     downloadDialog = null;
269                     isDownloading = false;
270                     View view = activity.findViewById(R.id.fragment1);
271                     Snackbar.make(view, activity.getString(R.string.download_control_save_success) + " " + targetFileName, Snackbar.LENGTH_SHORT).show();
272                     //Toast.makeText(activity, activity.getString(R.string.download_control_save_success) + " " + targetFileName, Toast.LENGTH_SHORT).show();
273                     System.gc();
274                 }
275             });
276         }
277         catch (Exception e)
278         {
279             final String message = e.getMessage();
280             activity.runOnUiThread(new Runnable() {
281                 @Override
282                 public void run() {
283                     if (downloadDialog != null)
284                     {
285                         downloadDialog.dismiss();
286                     }
287                     downloadDialog = null;
288                     isDownloading = false;
289                     presentMessage(activity.getString(R.string.download_control_save_failed), message);
290                 }
291             });
292         }
293         System.gc();
294     }
295
296     @Override
297     public void onErrorOccurred(Exception e)
298     {
299         isDownloading = false;
300         final String message = e.getMessage();
301         try
302         {
303             if (outputStream != null)
304             {
305                 outputStream.flush();
306                 outputStream.close();
307                 outputStream = null;
308             }
309         }
310         catch (Exception ex)
311         {
312             e.printStackTrace();
313             ex.printStackTrace();
314         }
315         activity.runOnUiThread(new Runnable()
316         {
317             @Override
318             public void run()
319             {
320                 if (downloadDialog != null)
321                 {
322                     downloadDialog.dismiss();
323                 }
324                 downloadDialog = null;
325                 isDownloading = false;
326                 presentMessage(activity.getString(R.string.download_control_download_failed), message);
327                 System.gc();
328             }
329         });
330         System.gc();
331     }
332
333     public boolean isDownloading()
334     {
335         return (isDownloading);
336     }
337
338     /**
339      *   共有の呼び出し
340      *
341      * @param fileUri  ファイルUri
342      */
343     private void shareContent(final Uri fileUri, final String contentType)
344     {
345         Intent intent = new Intent();
346         intent.setAction(Intent.ACTION_SEND);
347         try
348         {
349             intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
350             intent.setType(contentType);   // "video/mp4"  or "image/jpeg"  or "image/x-adobe-dng"
351             intent.putExtra(Intent.EXTRA_STREAM, fileUri);
352             activity.startActivityForResult(intent, 0);
353         }
354         catch (Exception e)
355         {
356             e.printStackTrace();
357         }
358     }
359
360     private void presentMessage(final String title, final String message)
361     {
362         activity.runOnUiThread(new Runnable() {
363             @Override
364             public void run() {
365                 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
366                 builder.setTitle(title).setMessage(message);
367                 builder.show();
368             }
369         });
370     }
371 }