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