53e0630d2296ded6182322fdcab272cba3ceca01
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / fragment / FileDetailFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
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.io.File;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import org.apache.commons.httpclient.methods.GetMethod;
25 import org.apache.commons.httpclient.methods.PostMethod;
26 import org.apache.commons.httpclient.methods.StringRequestEntity;
27 import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
28 import org.apache.http.HttpStatus;
29 import org.apache.http.NameValuePair;
30 import org.apache.http.client.utils.URLEncodedUtils;
31 import org.apache.http.message.BasicNameValuePair;
32 import org.apache.http.protocol.HTTP;
33 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
34 import org.json.JSONObject;
35
36 import android.accounts.Account;
37 import android.accounts.AccountManager;
38 import android.annotation.SuppressLint;
39 import android.app.Activity;
40 import android.content.ActivityNotFoundException;
41 import android.content.BroadcastReceiver;
42 import android.content.Context;
43 import android.content.Intent;
44 import android.content.IntentFilter;
45 import android.graphics.Bitmap;
46 import android.graphics.BitmapFactory;
47 import android.graphics.BitmapFactory.Options;
48 import android.graphics.Point;
49 import android.net.Uri;
50 import android.os.AsyncTask;
51 import android.os.Bundle;
52 import android.os.Handler;
53 import android.support.v4.app.FragmentTransaction;
54 import android.util.Log;
55 import android.view.Display;
56 import android.view.LayoutInflater;
57 import android.view.View;
58 import android.view.View.OnClickListener;
59 import android.view.ViewGroup;
60 import android.webkit.MimeTypeMap;
61 import android.widget.Button;
62 import android.widget.CheckBox;
63 import android.widget.ImageView;
64 import android.widget.TextView;
65 import android.widget.Toast;
66
67 import com.actionbarsherlock.app.SherlockFragment;
68 import com.owncloud.android.AccountUtils;
69 import com.owncloud.android.DisplayUtils;
70 import com.owncloud.android.authenticator.AccountAuthenticator;
71 import com.owncloud.android.datamodel.FileDataStorageManager;
72 import com.owncloud.android.datamodel.OCFile;
73 import com.owncloud.android.files.services.FileDownloader;
74 import com.owncloud.android.files.services.FileObserverService;
75 import com.owncloud.android.files.services.FileUploader;
76 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
77 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
78 import com.owncloud.android.network.OwnCloudClientUtils;
79 import com.owncloud.android.operations.OnRemoteOperationListener;
80 import com.owncloud.android.operations.RemoteOperation;
81 import com.owncloud.android.operations.RemoteOperationResult;
82 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
83 import com.owncloud.android.operations.RemoveFileOperation;
84 import com.owncloud.android.operations.RenameFileOperation;
85 import com.owncloud.android.operations.SynchronizeFileOperation;
86 import com.owncloud.android.ui.activity.ConflictsResolveActivity;
87 import com.owncloud.android.ui.activity.FileDetailActivity;
88 import com.owncloud.android.ui.activity.FileDisplayActivity;
89 import com.owncloud.android.ui.activity.TransferServiceGetter;
90 import com.owncloud.android.ui.dialog.EditNameDialog;
91 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
92 import com.owncloud.android.utils.OwnCloudVersion;
93
94 import com.owncloud.android.R;
95 import eu.alefzero.webdav.WebdavClient;
96 import eu.alefzero.webdav.WebdavUtils;
97
98 /**
99 * This Fragment is used to display the details about a file.
100 *
101 * @author Bartek Przybylski
102 *
103 */
104 public class FileDetailFragment extends SherlockFragment implements
105 OnClickListener, ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener {
106
107 public static final String EXTRA_FILE = "FILE";
108 public static final String EXTRA_ACCOUNT = "ACCOUNT";
109
110 private FileDetailFragment.ContainerActivity mContainerActivity;
111
112 private int mLayout;
113 private View mView;
114 private OCFile mFile;
115 private Account mAccount;
116 private ImageView mPreview;
117
118 private DownloadFinishReceiver mDownloadFinishReceiver;
119 private UploadFinishReceiver mUploadFinishReceiver;
120
121 private Handler mHandler;
122 private RemoteOperation mLastRemoteOperation;
123
124 private static final String TAG = FileDetailFragment.class.getSimpleName();
125 public static final String FTAG = "FileDetails";
126 public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
127
128
129 /**
130 * Creates an empty details fragment.
131 *
132 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
133 */
134 public FileDetailFragment() {
135 mFile = null;
136 mAccount = null;
137 mLayout = R.layout.file_details_empty;
138 }
139
140
141 /**
142 * Creates a details fragment.
143 *
144 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
145 *
146 * @param fileToDetail An {@link OCFile} to show in the fragment
147 * @param ocAccount An ownCloud account; needed to start downloads
148 */
149 public FileDetailFragment(OCFile fileToDetail, Account ocAccount) {
150 mFile = fileToDetail;
151 mAccount = ocAccount;
152 mLayout = R.layout.file_details_empty;
153
154 if(fileToDetail != null && ocAccount != null) {
155 mLayout = R.layout.file_details_fragment;
156 }
157 }
158
159
160 @Override
161 public void onCreate(Bundle savedInstanceState) {
162 super.onCreate(savedInstanceState);
163 mHandler = new Handler();
164 }
165
166
167 @Override
168 public View onCreateView(LayoutInflater inflater, ViewGroup container,
169 Bundle savedInstanceState) {
170 super.onCreateView(inflater, container, savedInstanceState);
171
172 if (savedInstanceState != null) {
173 mFile = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
174 mAccount = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_ACCOUNT);
175 }
176
177 View view = null;
178 view = inflater.inflate(mLayout, container, false);
179 mView = view;
180
181 if (mLayout == R.layout.file_details_fragment) {
182 mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
183 mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);
184 mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);
185 mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
186 mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
187 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
188 mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
189 }
190
191 updateFileDetails();
192 return view;
193 }
194
195
196 /**
197 * {@inheritDoc}
198 */
199 @Override
200 public void onAttach(Activity activity) {
201 super.onAttach(activity);
202 try {
203 mContainerActivity = (ContainerActivity) activity;
204 } catch (ClassCastException e) {
205 throw new ClassCastException(activity.toString() + " must implement " + FileDetailFragment.ContainerActivity.class.getSimpleName());
206 }
207 }
208
209
210 @Override
211 public void onSaveInstanceState(Bundle outState) {
212 Log.i(getClass().toString(), "onSaveInstanceState() start");
213 super.onSaveInstanceState(outState);
214 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mFile);
215 outState.putParcelable(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
216 Log.i(getClass().toString(), "onSaveInstanceState() end");
217 }
218
219
220 @Override
221 public void onResume() {
222 super.onResume();
223
224 mDownloadFinishReceiver = new DownloadFinishReceiver();
225 IntentFilter filter = new IntentFilter(
226 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
227 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
228
229 mUploadFinishReceiver = new UploadFinishReceiver();
230 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
231 getActivity().registerReceiver(mUploadFinishReceiver, filter);
232
233 mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
234 }
235
236 @Override
237 public void onPause() {
238 super.onPause();
239
240 getActivity().unregisterReceiver(mDownloadFinishReceiver);
241 mDownloadFinishReceiver = null;
242
243 getActivity().unregisterReceiver(mUploadFinishReceiver);
244 mUploadFinishReceiver = null;
245
246 if (mPreview != null) {
247 mPreview = null;
248 }
249 }
250
251 @Override
252 public View getView() {
253 return super.getView() == null ? mView : super.getView();
254 }
255
256
257
258 @Override
259 public void onClick(View v) {
260 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
261 switch (v.getId()) {
262 case R.id.fdDownloadBtn: {
263 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())) {
264 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
265 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
266 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
267 downloaderBinder.cancel(mAccount, mFile);
268 if (mFile.isDown()) {
269 setButtonsForDown();
270 } else {
271 setButtonsForRemote();
272 }
273
274 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
275 uploaderBinder.cancel(mAccount, mFile);
276 if (!mFile.fileExists()) {
277 // TODO make something better
278 if (getActivity() instanceof FileDisplayActivity) {
279 // double pane
280 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
281 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FTAG); // empty FileDetailFragment
282 transaction.commit();
283 mContainerActivity.onFileStateChanged();
284 } else {
285 getActivity().finish();
286 }
287
288 } else if (mFile.isDown()) {
289 setButtonsForDown();
290 } else {
291 setButtonsForRemote();
292 }
293
294 } else {
295 mLastRemoteOperation = new SynchronizeFileOperation(mFile, fdsm, mAccount, true, false, getActivity());
296 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
297 mLastRemoteOperation.execute(wc, this, mHandler);
298
299 // update ui
300 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
301 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
302 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
303
304 }
305 break;
306 }
307 case R.id.fdKeepInSync: {
308 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
309 mFile.setKeepInSync(cb.isChecked());
310 fdsm.saveFile(mFile);
311
312 /// register the OCFile instance in the observer service to monitor local updates;
313 /// if necessary, the file is download
314 Intent intent = new Intent(getActivity().getApplicationContext(),
315 FileObserverService.class);
316 intent.putExtra(FileObserverService.KEY_FILE_CMD,
317 (cb.isChecked()?
318 FileObserverService.CMD_ADD_OBSERVED_FILE:
319 FileObserverService.CMD_DEL_OBSERVED_FILE));
320 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
321 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
322 Log.e(TAG, "starting observer service");
323 getActivity().startService(intent);
324
325 if (mFile.keepInSync()) {
326 onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
327 }
328 break;
329 }
330 case R.id.fdRenameBtn: {
331 EditNameDialog dialog = EditNameDialog.newInstance(mFile.getFileName());
332 dialog.setOnDismissListener(this);
333 dialog.show(getFragmentManager(), "nameeditdialog");
334 break;
335 }
336 case R.id.fdRemoveBtn: {
337 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
338 R.string.confirmation_remove_alert,
339 new String[]{mFile.getFileName()},
340 mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
341 mFile.isDown() ? R.string.confirmation_remove_local : -1,
342 R.string.common_cancel);
343 confDialog.setOnConfirmationListener(this);
344 confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
345 break;
346 }
347 case R.id.fdOpenBtn: {
348 String storagePath = mFile.getStoragePath();
349 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
350 try {
351 Intent i = new Intent(Intent.ACTION_VIEW);
352 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
353 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
354 startActivity(i);
355
356 } catch (Throwable t) {
357 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
358 boolean toastIt = true;
359 String mimeType = "";
360 try {
361 Intent i = new Intent(Intent.ACTION_VIEW);
362 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
363 if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {
364 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
365 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
366 startActivity(i);
367 toastIt = false;
368 }
369
370 } catch (IndexOutOfBoundsException e) {
371 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
372
373 } catch (ActivityNotFoundException e) {
374 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
375
376 } catch (Throwable th) {
377 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
378
379 } finally {
380 if (toastIt) {
381 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
382 }
383 }
384
385 }
386 break;
387 }
388 default:
389 Log.e(TAG, "Incorrect view clicked!");
390 }
391
392 /* else if (v.getId() == R.id.fdShareBtn) {
393 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
394 t.start();
395 }*/
396 }
397
398
399 @Override
400 public void onConfirmation(String callerTag) {
401 if (callerTag.equals(FTAG_CONFIRMATION)) {
402 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
403 if (fdsm.getFileById(mFile.getFileId()) != null) {
404 mLastRemoteOperation = new RemoveFileOperation( mFile,
405 true,
406 new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
407 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
408 mLastRemoteOperation.execute(wc, this, mHandler);
409
410 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
411 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
412 }
413 }
414 }
415
416 @Override
417 public void onNeutral(String callerTag) {
418 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
419 File f = null;
420 if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
421 f.delete();
422 mFile.setStoragePath(null);
423 fdsm.saveFile(mFile);
424 updateFileDetails(mFile, mAccount);
425 }
426 }
427
428 @Override
429 public void onCancel(String callerTag) {
430 Log.d(TAG, "REMOVAL CANCELED");
431 }
432
433
434 /**
435 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
436 *
437 * @return True when the fragment was created with the empty layout.
438 */
439 public boolean isEmpty() {
440 return mLayout == R.layout.file_details_empty;
441 }
442
443
444 /**
445 * Can be used to get the file that is currently being displayed.
446 * @return The file on the screen.
447 */
448 public OCFile getDisplayedFile(){
449 return mFile;
450 }
451
452 /**
453 * Use this method to signal this Activity that it shall update its view.
454 *
455 * @param file : An {@link OCFile}
456 */
457 public void updateFileDetails(OCFile file, Account ocAccount) {
458 mFile = file;
459 mAccount = ocAccount;
460 updateFileDetails();
461 }
462
463
464 /**
465 * Updates the view with all relevant details about that file.
466 */
467 public void updateFileDetails() {
468
469 if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {
470
471 // set file details
472 setFilename(mFile.getFileName());
473 setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile
474 .getMimetype()));
475 setFilesize(mFile.getFileLength());
476 if(ocVersionSupportsTimeCreated()){
477 setTimeCreated(mFile.getCreationTimestamp());
478 }
479
480 setTimeModified(mFile.getModificationTimestamp());
481
482 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
483 cb.setChecked(mFile.keepInSync());
484
485 // configure UI for depending upon local state of the file
486 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
487 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
488 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
489 if ((downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {
490 setButtonsForTransferring();
491
492 } else if (mFile.isDown()) {
493 // Update preview
494 if (mFile.getMimetype().startsWith("image/")) {
495 BitmapLoader bl = new BitmapLoader();
496 bl.execute(new String[]{mFile.getStoragePath()});
497 }
498
499 setButtonsForDown();
500
501 } else {
502 setButtonsForRemote();
503 }
504 }
505 }
506
507
508 /**
509 * Updates the filename in view
510 * @param filename to set
511 */
512 private void setFilename(String filename) {
513 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
514 if (tv != null)
515 tv.setText(filename);
516 }
517
518 /**
519 * Updates the MIME type in view
520 * @param mimetype to set
521 */
522 private void setFiletype(String mimetype) {
523 TextView tv = (TextView) getView().findViewById(R.id.fdType);
524 if (tv != null)
525 tv.setText(mimetype);
526 }
527
528 /**
529 * Updates the file size in view
530 * @param filesize in bytes to set
531 */
532 private void setFilesize(long filesize) {
533 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
534 if (tv != null)
535 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
536 }
537
538 /**
539 * Updates the time that the file was created in view
540 * @param milliseconds Unix time to set
541 */
542 private void setTimeCreated(long milliseconds){
543 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
544 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
545 if(tv != null){
546 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
547 tv.setVisibility(View.VISIBLE);
548 tvLabel.setVisibility(View.VISIBLE);
549 }
550 }
551
552 /**
553 * Updates the time that the file was last modified
554 * @param milliseconds Unix time to set
555 */
556 private void setTimeModified(long milliseconds){
557 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
558 if(tv != null){
559 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
560 }
561 }
562
563 /**
564 * Enables or disables buttons for a file being downloaded
565 */
566 private void setButtonsForTransferring() {
567 if (!isEmpty()) {
568 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
569 downloadButton.setText(R.string.common_cancel);
570 //downloadButton.setEnabled(false);
571
572 // let's protect the user from himself ;)
573 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
574 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(false);
575 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(false);
576 getView().findViewById(R.id.fdKeepInSync).setEnabled(false);
577 }
578 }
579
580 /**
581 * Enables or disables buttons for a file locally available
582 */
583 private void setButtonsForDown() {
584 if (!isEmpty()) {
585 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
586 downloadButton.setText(R.string.filedetails_redownload);
587 //downloadButton.setEnabled(true);
588
589 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(true);
590 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
591 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
592 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
593 }
594 }
595
596 /**
597 * Enables or disables buttons for a file not locally available
598 */
599 private void setButtonsForRemote() {
600 if (!isEmpty()) {
601 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
602 downloadButton.setText(R.string.filedetails_download);
603
604 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
605 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
606 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
607 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
608 }
609 }
610
611
612 /**
613 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
614 * the time that the file was created. There is a chance that this will
615 * be fixed in future versions. Use this method to check if this version of
616 * ownCloud has this fix.
617 * @return True, if ownCloud the ownCloud version is supporting creation time
618 */
619 private boolean ocVersionSupportsTimeCreated(){
620 /*if(mAccount != null){
621 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
622 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
623 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
624 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
625 return true;
626 }
627 }*/
628 return false;
629 }
630
631
632 /**
633 * Interface to implement by any Activity that includes some instance of FileDetailFragment
634 *
635 * @author David A. Velasco
636 */
637 public interface ContainerActivity extends TransferServiceGetter {
638
639 /**
640 * Callback method invoked when the detail fragment wants to notice its container
641 * activity about a relevant state the file shown by the fragment.
642 *
643 * Added to notify to FileDisplayActivity about the need of refresh the files list.
644 *
645 * Currently called when:
646 * - a download is started;
647 * - a rename is completed;
648 * - a deletion is completed;
649 * - the 'inSync' flag is changed;
650 */
651 public void onFileStateChanged();
652
653 }
654
655
656 /**
657 * Once the file download has finished -> update view
658 * @author Bartek Przybylski
659 */
660 private class DownloadFinishReceiver extends BroadcastReceiver {
661 @Override
662 public void onReceive(Context context, Intent intent) {
663 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
664
665 if (!isEmpty() && accountName.equals(mAccount.name)) {
666 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
667 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
668 if (mFile.getRemotePath().equals(downloadedRemotePath)) {
669 if (downloadWasFine) {
670 mFile.setStoragePath(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH)); // updates the local object without accessing the database again
671 }
672 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
673 }
674 }
675 }
676 }
677
678
679 /**
680 * Once the file upload has finished -> update view
681 *
682 * Being notified about the finish of an upload is necessary for the next sequence:
683 * 1. Upload a big file.
684 * 2. Force a synchronization; if it finished before the upload, the file in transfer will be included in the local database and in the file list
685 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
686 * 3. Click the file in the list to see its details.
687 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
688 */
689 private class UploadFinishReceiver extends BroadcastReceiver {
690 @Override
691 public void onReceive(Context context, Intent intent) {
692 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
693
694 if (!isEmpty() && accountName.equals(mAccount.name)) {
695 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
696 String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
697 if (mFile.getRemotePath().equals(uploadRemotePath)) {
698 if (uploadWasFine) {
699 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
700 mFile = fdsm.getFileByPath(mFile.getRemotePath());
701 }
702 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
703 }
704 }
705 }
706 }
707
708
709 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
710 @SuppressWarnings("unused")
711 private class ShareRunnable implements Runnable {
712 private String mPath;
713
714 public ShareRunnable(String path) {
715 mPath = path;
716 }
717
718 public void run() {
719 AccountManager am = AccountManager.get(getActivity());
720 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
721 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
722 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
723
724 Log.d("share", "sharing for version " + ocv.toString());
725
726 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
727 String APPS_PATH = "/apps/files_sharing/";
728 String SHARE_PATH = "ajax/share.php";
729
730 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
731
732 final String WEBDAV_SCRIPT = "webdav.php";
733 final String WEBDAV_FILES_LOCATION = "/files/";
734
735 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
736 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
737 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
738
739 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
740 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
741
742 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
743
744 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
745 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
746 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
747 Log.d("share", mPath+"");
748 formparams.add(new BasicNameValuePair("sources",mPath));
749 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
750 formparams.add(new BasicNameValuePair("permissions", "0"));
751 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
752
753 int status;
754 try {
755 PropFindMethod find = new PropFindMethod(url+"/");
756 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
757 Log.d("sharer", ""+ url+"/");
758
759 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
760 Log.d("sharer-h", a.getName() + ":"+a.getValue());
761 }
762
763 int status2 = wc.executeMethod(find);
764
765 Log.d("sharer", "propstatus "+status2);
766
767 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
768 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
769
770 status2 = wc.executeMethod(get);
771
772 Log.d("sharer", "getstatus "+status2);
773 Log.d("sharer", "" + get.getResponseBodyAsString());
774
775 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
776 Log.d("sharer", a.getName() + ":"+a.getValue());
777 }
778
779 status = wc.executeMethod(post);
780 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
781 Log.d("sharer-h", a.getName() + ":"+a.getValue());
782 }
783 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
784 Log.d("sharer", a.getName() + ":"+a.getValue());
785 }
786 String resp = post.getResponseBodyAsString();
787 Log.d("share", ""+post.getURI().toString());
788 Log.d("share", "returned status " + status);
789 Log.d("share", " " +resp);
790
791 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
792 return;
793 }
794
795 JSONObject jsonObject = new JSONObject (resp);
796 String jsonStatus = jsonObject.getString("status");
797 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
798
799 String token = jsonObject.getString("data");
800 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
801 Log.d("Actions:shareFile ok", "url: " + uri);
802
803 } catch (Exception e) {
804 e.printStackTrace();
805 }
806
807 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
808
809 }
810 }
811 }
812
813 public void onDismiss(EditNameDialog dialog) {
814 if (dialog.getResult()) {
815 String newFilename = dialog.getNewFilename();
816 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
817 mLastRemoteOperation = new RenameFileOperation( mFile,
818 newFilename,
819 new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
820 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
821 mLastRemoteOperation.execute(wc, this, mHandler);
822 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
823 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
824 }
825 }
826
827
828 class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
829 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
830 @Override
831 protected Bitmap doInBackground(String... params) {
832 Bitmap result = null;
833 if (params.length != 1) return result;
834 String storagePath = params[0];
835 try {
836
837 BitmapFactory.Options options = new Options();
838 options.inScaled = true;
839 options.inPurgeable = true;
840 options.inJustDecodeBounds = true;
841 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
842 options.inPreferQualityOverSpeed = false;
843 }
844 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
845 options.inMutable = false;
846 }
847
848 result = BitmapFactory.decodeFile(storagePath, options);
849 options.inJustDecodeBounds = false;
850
851 int width = options.outWidth;
852 int height = options.outHeight;
853 int scale = 1;
854 if (width >= 2048 || height >= 2048) {
855 scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));
856 options.inSampleSize = scale;
857 }
858 Display display = getActivity().getWindowManager().getDefaultDisplay();
859 Point size = new Point();
860 int screenwidth;
861 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
862 display.getSize(size);
863 screenwidth = size.x;
864 } else {
865 screenwidth = display.getWidth();
866 }
867
868 Log.e("ASD", "W " + width + " SW " + screenwidth);
869
870 if (width > screenwidth) {
871 scale = (int) Math.ceil((float)width / screenwidth);
872 options.inSampleSize = scale;
873 }
874
875 result = BitmapFactory.decodeFile(storagePath, options);
876
877 Log.e("ASD", "W " + options.outWidth + " SW " + options.outHeight);
878
879 } catch (OutOfMemoryError e) {
880 result = null;
881 Log.e(TAG, "Out of memory occured for file with size " + storagePath);
882
883 } catch (NoSuchFieldError e) {
884 result = null;
885 Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath);
886
887 } catch (Throwable t) {
888 result = null;
889 Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t);
890 }
891 return result;
892 }
893 @Override
894 protected void onPostExecute(Bitmap result) {
895 if (result != null && mPreview != null) {
896 mPreview.setImageBitmap(result);
897 }
898 }
899
900 }
901
902 /**
903 * {@inheritDoc}
904 */
905 @Override
906 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
907 if (operation.equals(mLastRemoteOperation)) {
908 if (operation instanceof RemoveFileOperation) {
909 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
910
911 } else if (operation instanceof RenameFileOperation) {
912 onRenameFileOperationFinish((RenameFileOperation)operation, result);
913
914 } else if (operation instanceof SynchronizeFileOperation) {
915 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
916 }
917 }
918 }
919
920
921 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
922 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
923 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
924
925 if (result.isSuccess()) {
926 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
927 msg.show();
928 if (inDisplayActivity) {
929 // double pane
930 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
931 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
932 transaction.commit();
933 mContainerActivity.onFileStateChanged();
934 } else {
935 getActivity().finish();
936 }
937
938 } else {
939 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
940 msg.show();
941 if (result.isSslRecoverableException()) {
942 // TODO show the SSL warning dialog
943 }
944 }
945 }
946
947 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
948 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
949 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
950
951 if (result.isSuccess()) {
952 updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
953 mContainerActivity.onFileStateChanged();
954
955 } else {
956 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
957 Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
958 msg.show();
959 // TODO throw again the new rename dialog
960 } else {
961 Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
962 msg.show();
963 if (result.isSslRecoverableException()) {
964 // TODO show the SSL warning dialog
965 }
966 }
967 }
968 }
969
970 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
971 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
972 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
973
974 if (!result.isSuccess()) {
975 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
976 Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
977 //i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
978 i.putExtra("remotepath", mFile.getRemotePath());
979 i.putExtra("localpath", mFile.getStoragePath());
980 i.putExtra("account", mAccount);
981 startActivity(i);
982
983 } else {
984 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
985 msg.show();
986 }
987
988 } else {
989 if (operation.transferWasRequested()) {
990 mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
991 // checking the service to see if the file is downloading results in FALSE
992 } else {
993 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
994 msg.show();
995 if (mFile.isDown()) {
996 setButtonsForDown();
997
998 } else {
999 setButtonsForRemote();
1000 }
1001 }
1002 }
1003 }
1004
1005 }