OSDN Git Service

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