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