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