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