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