OSDN Git Service

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