Fix: Download is started over and over when rotating the device
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / fragment / FileDetailFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18 package com.owncloud.android.ui.fragment;
19
20 import java.lang.ref.WeakReference;
21
22 import android.accounts.Account;
23 import android.content.Intent;
24 import android.os.Bundle;
25 import android.view.LayoutInflater;
26 import android.view.View;
27 import android.view.View.OnClickListener;
28 import android.view.ViewGroup;
29 import android.widget.CheckBox;
30 import android.widget.ImageView;
31 import android.widget.ProgressBar;
32 import android.widget.TextView;
33
34 import com.actionbarsherlock.view.Menu;
35 import com.actionbarsherlock.view.MenuInflater;
36 import com.actionbarsherlock.view.MenuItem;
37 import com.owncloud.android.R;
38 import com.owncloud.android.datamodel.FileDataStorageManager;
39 import com.owncloud.android.datamodel.OCFile;
40 import com.owncloud.android.files.FileMenuFilter;
41 import com.owncloud.android.files.services.FileObserverService;
42 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
43 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
44 import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
45 import com.owncloud.android.ui.activity.FileActivity;
46 import com.owncloud.android.ui.activity.FileDisplayActivity;
47 import com.owncloud.android.ui.dialog.EditNameDialog;
48 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
49 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
50 import com.owncloud.android.utils.DisplayUtils;
51 import com.owncloud.android.utils.Log_OC;
52
53
54 /**
55 * This Fragment is used to display the details about a file.
56 *
57 * @author Bartek Przybylski
58 * @author David A. Velasco
59 */
60 public class FileDetailFragment extends FileFragment implements
61 OnClickListener, EditNameDialogListener {
62
63 private int mLayout;
64 private View mView;
65 private Account mAccount;
66
67 public ProgressListener mProgressListener;
68
69 private static final String TAG = FileDetailFragment.class.getSimpleName();
70 public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
71 public static final String FTAG_RENAME_FILE = "RENAME_FILE_FRAGMENT";
72
73
74 /**
75 * Creates an empty details fragment.
76 *
77 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
78 */
79 public FileDetailFragment() {
80 super();
81 mAccount = null;
82 mLayout = R.layout.file_details_empty;
83 mProgressListener = null;
84 }
85
86 /**
87 * Creates a details fragment.
88 *
89 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
90 *
91 * @param fileToDetail An {@link OCFile} to show in the fragment
92 * @param ocAccount An ownCloud account; needed to start downloads
93 */
94 public FileDetailFragment(OCFile fileToDetail, Account ocAccount) {
95 super(fileToDetail);
96 mAccount = ocAccount;
97 mLayout = R.layout.file_details_empty;
98 mProgressListener = null;
99 }
100
101
102 @Override
103 public void onActivityCreated(Bundle savedInstanceState) {
104 super.onCreate(savedInstanceState);
105 setHasOptionsMenu(true);
106 }
107
108
109 @Override
110 public View onCreateView(LayoutInflater inflater, ViewGroup container,
111 Bundle savedInstanceState) {
112
113 if (savedInstanceState != null) {
114 setFile((OCFile)savedInstanceState.getParcelable(FileActivity.EXTRA_FILE));
115 mAccount = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
116 }
117
118 if(getFile() != null && mAccount != null) {
119 mLayout = R.layout.file_details_fragment;
120 }
121
122 View view = null;
123 view = inflater.inflate(mLayout, null);
124 mView = view;
125
126 if (mLayout == R.layout.file_details_fragment) {
127 mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
128 ProgressBar progressBar = (ProgressBar)mView.findViewById(R.id.fdProgressBar);
129 mProgressListener = new ProgressListener(progressBar);
130 mView.findViewById(R.id.fdCancelBtn).setOnClickListener(this);
131 }
132
133 updateFileDetails(false, false);
134 return view;
135 }
136
137 @Override
138 public void onSaveInstanceState(Bundle outState) {
139 super.onSaveInstanceState(outState);
140 outState.putParcelable(FileActivity.EXTRA_FILE, getFile());
141 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
142 }
143
144 @Override
145 public void onStart() {
146 super.onStart();
147 listenForTransferProgress();
148 }
149
150 @Override
151 public void onStop() {
152 super.onStop();
153 leaveTransferProgress();
154 }
155
156
157 @Override
158 public View getView() {
159 return super.getView() == null ? mView : super.getView();
160 }
161
162
163 /**
164 * {@inheritDoc}
165 */
166 @Override
167 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
168 super.onCreateOptionsMenu(menu, inflater);
169 inflater.inflate(R.menu.file_actions_menu, menu);
170 }
171
172
173 /**
174 * {@inheritDoc}
175 */
176 @Override
177 public void onPrepareOptionsMenu (Menu menu) {
178 super.onPrepareOptionsMenu(menu);
179
180 if (mContainerActivity.getStorageManager() != null) {
181 FileMenuFilter mf = new FileMenuFilter(
182 getFile(),
183 mContainerActivity.getStorageManager().getAccount(),
184 mContainerActivity,
185 getSherlockActivity()
186 );
187 mf.filter(menu);
188 }
189
190 // additional restriction for this fragment
191 MenuItem item = menu.findItem(R.id.action_see_details);
192 if (item != null) {
193 item.setVisible(false);
194 item.setEnabled(false);
195 }
196 }
197
198
199 /**
200 * {@inheritDoc}
201 */
202 @Override
203 public boolean onOptionsItemSelected(MenuItem item) {
204 switch (item.getItemId()) {
205 case R.id.action_share_file: {
206 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
207 return true;
208 }
209 case R.id.action_unshare_file: {
210 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
211 return true;
212 }
213 case R.id.action_open_file_with: {
214 mContainerActivity.getFileOperationsHelper().openFile(getFile());
215 return true;
216 }
217 case R.id.action_remove_file: {
218 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
219 dialog.show(getFragmentManager(), FTAG_CONFIRMATION);
220 return true;
221 }
222 case R.id.action_rename_file: {
223 showDialogToRenameFile();
224 return true;
225 }
226 case R.id.action_cancel_download:
227 case R.id.action_cancel_upload: {
228 ((FileDisplayActivity)mContainerActivity).cancelTransference(getFile());
229 return true;
230 }
231 case R.id.action_download_file:
232 case R.id.action_sync_file: {
233 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
234 return true;
235 }
236 case R.id.action_send_file: {
237 // Obtain the file
238 if (!getFile().isDown()) { // Download the file
239 Log_OC.d(TAG, getFile().getRemotePath() + " : File must be downloaded");
240 ((FileDisplayActivity)mContainerActivity).startDownloadForSending(getFile());
241
242 } else {
243 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
244 }
245 return true;
246 }
247 default:
248 return false;
249 }
250 }
251
252 @Override
253 public void onClick(View v) {
254 switch (v.getId()) {
255 case R.id.fdKeepInSync: {
256 toggleKeepInSync();
257 break;
258 }
259 case R.id.fdCancelBtn: {
260 ((FileDisplayActivity)mContainerActivity).cancelTransference(getFile());
261 break;
262 }
263 default:
264 Log_OC.e(TAG, "Incorrect view clicked!");
265 }
266 }
267
268
269 private void toggleKeepInSync() {
270 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
271 OCFile file = getFile();
272 file.setKeepInSync(cb.isChecked());
273 mContainerActivity.getStorageManager().saveFile(file);
274
275 /// register the OCFile instance in the observer service to monitor local updates;
276 /// if necessary, the file is download
277 Intent intent = new Intent(getActivity().getApplicationContext(),
278 FileObserverService.class);
279 intent.putExtra(FileObserverService.KEY_FILE_CMD,
280 (cb.isChecked()?
281 FileObserverService.CMD_ADD_OBSERVED_FILE:
282 FileObserverService.CMD_DEL_OBSERVED_FILE));
283 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, file);
284 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
285 getActivity().startService(intent);
286
287 if (file.keepInSync()) {
288 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
289 }
290 }
291
292 private void showDialogToRenameFile() {
293 OCFile file = getFile();
294 String fileName = file.getFileName();
295 int extensionStart = file.isFolder() ? -1 : fileName.lastIndexOf(".");
296 int selectionEnd = (extensionStart >= 0) ? extensionStart : fileName.length();
297 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), fileName, 0, selectionEnd, this);
298 dialog.show(getFragmentManager(), FTAG_RENAME_FILE);
299 }
300
301 /**
302 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
303 *
304 * @return True when the fragment was created with the empty layout.
305 */
306 public boolean isEmpty() {
307 return (mLayout == R.layout.file_details_empty || getFile() == null || mAccount == null);
308 }
309
310
311 /**
312 * Use this method to signal this Activity that it shall update its view.
313 *
314 * @param file : An {@link OCFile}
315 */
316 public void updateFileDetails(OCFile file, Account ocAccount) {
317 setFile(file);
318 mAccount = ocAccount;
319 updateFileDetails(false, false);
320 }
321
322 /**
323 * Updates the view with all relevant details about that file.
324 *
325 * TODO Remove parameter when the transferring state of files is kept in database.
326 *
327 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
328 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
329 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
330 *
331 * @param refresh If 'true', try to refresh the whole file from the database
332 */
333 public void updateFileDetails(boolean transferring, boolean refresh) {
334 if (readyToShow()) {
335 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
336 if (refresh && storageManager != null) {
337 setFile(storageManager.getFileByPath(getFile().getRemotePath()));
338 }
339 OCFile file = getFile();
340
341 // set file details
342 setFilename(file.getFileName());
343 setFiletype(file.getMimetype());
344 setFilesize(file.getFileLength());
345 if(ocVersionSupportsTimeCreated()){
346 setTimeCreated(file.getCreationTimestamp());
347 }
348
349 setTimeModified(file.getModificationTimestamp());
350
351 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
352 cb.setChecked(file.keepInSync());
353
354 // configure UI for depending upon local state of the file
355 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
356 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
357 if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file))) {
358 setButtonsForTransferring();
359
360 } else if (file.isDown()) {
361
362 setButtonsForDown();
363
364 } else {
365 // TODO load default preview image; when the local file is removed, the preview remains there
366 setButtonsForRemote();
367 }
368 }
369 getView().invalidate();
370 }
371
372 /**
373 * Checks if the fragment is ready to show details of a OCFile
374 *
375 * @return 'True' when the fragment is ready to show details of a file
376 */
377 private boolean readyToShow() {
378 return (getFile() != null && mAccount != null && mLayout == R.layout.file_details_fragment);
379 }
380
381
382 /**
383 * Updates the filename in view
384 * @param filename to set
385 */
386 private void setFilename(String filename) {
387 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
388 if (tv != null)
389 tv.setText(filename);
390 }
391
392 /**
393 * Updates the MIME type in view
394 * @param mimetype to set
395 */
396 private void setFiletype(String mimetype) {
397 TextView tv = (TextView) getView().findViewById(R.id.fdType);
398 if (tv != null) {
399 String printableMimetype = DisplayUtils.convertMIMEtoPrettyPrint(mimetype);;
400 tv.setText(printableMimetype);
401 }
402 ImageView iv = (ImageView) getView().findViewById(R.id.fdIcon);
403 if (iv != null) {
404 iv.setImageResource(DisplayUtils.getResourceId(mimetype));
405 }
406 }
407
408 /**
409 * Updates the file size in view
410 * @param filesize in bytes to set
411 */
412 private void setFilesize(long filesize) {
413 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
414 if (tv != null)
415 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
416 }
417
418 /**
419 * Updates the time that the file was created in view
420 * @param milliseconds Unix time to set
421 */
422 private void setTimeCreated(long milliseconds){
423 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
424 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
425 if(tv != null){
426 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
427 tv.setVisibility(View.VISIBLE);
428 tvLabel.setVisibility(View.VISIBLE);
429 }
430 }
431
432 /**
433 * Updates the time that the file was last modified
434 * @param milliseconds Unix time to set
435 */
436 private void setTimeModified(long milliseconds){
437 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
438 if(tv != null){
439 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
440 }
441 }
442
443 /**
444 * Enables or disables buttons for a file being downloaded
445 */
446 private void setButtonsForTransferring() {
447 if (!isEmpty()) {
448 // let's protect the user from himself ;)
449 getView().findViewById(R.id.fdKeepInSync).setEnabled(false);
450
451 // show the progress bar for the transfer
452 getView().findViewById(R.id.fdProgressBlock).setVisibility(View.VISIBLE);
453 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
454 progressText.setVisibility(View.VISIBLE);
455 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
456 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
457 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, getFile())) {
458 progressText.setText(R.string.downloader_download_in_progress_ticker);
459 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, getFile())) {
460 progressText.setText(R.string.uploader_upload_in_progress_ticker);
461 }
462 }
463 }
464
465 /**
466 * Enables or disables buttons for a file locally available
467 */
468 private void setButtonsForDown() {
469 if (!isEmpty()) {
470 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
471
472 // hides the progress bar
473 getView().findViewById(R.id.fdProgressBlock).setVisibility(View.GONE);
474 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
475 progressText.setVisibility(View.GONE);
476 }
477 }
478
479 /**
480 * Enables or disables buttons for a file not locally available
481 */
482 private void setButtonsForRemote() {
483 if (!isEmpty()) {
484 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
485
486 // hides the progress bar
487 getView().findViewById(R.id.fdProgressBlock).setVisibility(View.GONE);
488 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
489 progressText.setVisibility(View.GONE);
490 }
491 }
492
493
494 /**
495 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
496 * the time that the file was created. There is a chance that this will
497 * be fixed in future versions. Use this method to check if this version of
498 * ownCloud has this fix.
499 * @return True, if ownCloud the ownCloud version is supporting creation time
500 */
501 private boolean ocVersionSupportsTimeCreated(){
502 /*if(mAccount != null){
503 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
504 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
505 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
506 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
507 return true;
508 }
509 }*/
510 return false;
511 }
512
513
514 public void onDismiss(EditNameDialog dialog) {
515 if (dialog.getResult()) {
516 String newFilename = dialog.getNewFilename();
517 Log_OC.d(TAG, "name edit dialog dismissed with new name " + newFilename);
518 mContainerActivity.getFileOperationsHelper().renameFile(getFile(), newFilename);
519 }
520 }
521
522
523 public void listenForTransferProgress() {
524 if (mProgressListener != null) {
525 if (mContainerActivity.getFileDownloaderBinder() != null) {
526 mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, getFile());
527 }
528 if (mContainerActivity.getFileUploaderBinder() != null) {
529 mContainerActivity.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, getFile());
530 }
531 }
532 }
533
534
535 public void leaveTransferProgress() {
536 if (mProgressListener != null) {
537 if (mContainerActivity.getFileDownloaderBinder() != null) {
538 mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, getFile());
539 }
540 if (mContainerActivity.getFileUploaderBinder() != null) {
541 mContainerActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, getFile());
542 }
543 }
544 }
545
546
547
548 /**
549 * Helper class responsible for updating the progress bar shown for file uploading or downloading
550 *
551 * @author David A. Velasco
552 */
553 private class ProgressListener implements OnDatatransferProgressListener {
554 int mLastPercent = 0;
555 WeakReference<ProgressBar> mProgressBar = null;
556
557 ProgressListener(ProgressBar progressBar) {
558 mProgressBar = new WeakReference<ProgressBar>(progressBar);
559 }
560
561 @Override
562 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename) {
563 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
564 if (percent != mLastPercent) {
565 ProgressBar pb = mProgressBar.get();
566 if (pb != null) {
567 pb.setProgress(percent);
568 pb.postInvalidate();
569 }
570 }
571 mLastPercent = percent;
572 }
573
574 };
575
576 }