OSDN Git Service

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