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