ce1ede9178ca364a0d4c451eac21edfa8f0d404c
[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(R.string.confirmation_remove_alert, new String[]{mFile.getFileName()});
277 confDialog.setOnConfirmationListener(this);
278 confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
279 break;
280 }
281 case R.id.fdOpenBtn: {
282 String storagePath = mFile.getStoragePath();
283 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
284 try {
285 Intent i = new Intent(Intent.ACTION_VIEW);
286 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
287 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
288 startActivity(i);
289
290 } catch (Throwable t) {
291 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
292 boolean toastIt = true;
293 String mimeType = "";
294 try {
295 Intent i = new Intent(Intent.ACTION_VIEW);
296 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
297 if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {
298 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
299 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
300 startActivity(i);
301 toastIt = false;
302 }
303
304 } catch (IndexOutOfBoundsException e) {
305 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
306
307 } catch (ActivityNotFoundException e) {
308 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
309
310 } catch (Throwable th) {
311 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
312
313 } finally {
314 if (toastIt) {
315 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
316 }
317 }
318
319 }
320 break;
321 }
322 default:
323 Log.e(TAG, "Incorrect view clicked!");
324 }
325
326 /* else if (v.getId() == R.id.fdShareBtn) {
327 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
328 t.start();
329 }*/
330 }
331
332
333 @Override
334 public void onConfirmation(boolean confirmation, String callerTag) {
335 if (confirmation && callerTag.equals(FTAG_CONFIRMATION)) {
336 Log.e("ASD","onConfirmation");
337 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
338 if (fdsm.getFileById(mFile.getFileId()) != null) {
339 new Thread(new RemoveRunnable(mFile, mAccount, new Handler())).start();
340 }
341 } else if (!confirmation) Log.d(TAG, "REMOVAL CANCELED");
342 }
343
344
345 /**
346 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
347 *
348 * @return True when the fragment was created with the empty layout.
349 */
350 public boolean isEmpty() {
351 return mLayout == R.layout.file_details_empty;
352 }
353
354
355 /**
356 * Can be used to get the file that is currently being displayed.
357 * @return The file on the screen.
358 */
359 public OCFile getDisplayedFile(){
360 return mFile;
361 }
362
363 /**
364 * Use this method to signal this Activity that it shall update its view.
365 *
366 * @param file : An {@link OCFile}
367 */
368 public void updateFileDetails(OCFile file, Account ocAccount) {
369 mFile = file;
370 mAccount = ocAccount;
371 updateFileDetails();
372 }
373
374
375 /**
376 * Updates the view with all relevant details about that file.
377 */
378 public void updateFileDetails() {
379
380 if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {
381
382 // set file details
383 setFilename(mFile.getFileName());
384 setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile
385 .getMimetype()));
386 setFilesize(mFile.getFileLength());
387 if(ocVersionSupportsTimeCreated()){
388 setTimeCreated(mFile.getCreationTimestamp());
389 }
390
391 setTimeModified(mFile.getModificationTimestamp());
392
393 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
394 cb.setChecked(mFile.keepInSync());
395
396 // configure UI for depending upon local state of the file
397 if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
398 setButtonsForTransferring();
399
400 } else if (mFile.isDown()) {
401 // Update preview
402 if (mFile.getMimetype().startsWith("image/")) {
403 BitmapLoader bl = new BitmapLoader();
404 bl.execute(new String[]{mFile.getStoragePath()});
405 }
406
407 setButtonsForDown();
408
409 // Change download button to open button
410 /*downloadButton.setText(R.string.filedetails_open);
411 downloadButton.setOnClickListener(new OnClickListener() {
412 @Override
413 public void onClick(View v) {
414 String storagePath = mFile.getStoragePath();
415 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
416 try {
417 Intent i = new Intent(Intent.ACTION_VIEW);
418 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
419 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
420 startActivity(i);
421
422 } catch (Throwable t) {
423 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
424 boolean toastIt = true;
425 String mimeType = "";
426 try {
427 Intent i = new Intent(Intent.ACTION_VIEW);
428 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
429 if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {
430 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
431 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
432 startActivity(i);
433 toastIt = false;
434 }
435
436 } catch (IndexOutOfBoundsException e) {
437 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
438
439 } catch (ActivityNotFoundException e) {
440 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
441
442 } catch (Throwable th) {
443 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
444
445 } finally {
446 if (toastIt) {
447 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
448 }
449 }
450
451 }
452 }
453 });*/
454 } else {
455 setButtonsForRemote();
456 }
457 }
458 }
459
460
461 /**
462 * Updates the filename in view
463 * @param filename to set
464 */
465 private void setFilename(String filename) {
466 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
467 if (tv != null)
468 tv.setText(filename);
469 }
470
471 /**
472 * Updates the MIME type in view
473 * @param mimetype to set
474 */
475 private void setFiletype(String mimetype) {
476 TextView tv = (TextView) getView().findViewById(R.id.fdType);
477 if (tv != null)
478 tv.setText(mimetype);
479 }
480
481 /**
482 * Updates the file size in view
483 * @param filesize in bytes to set
484 */
485 private void setFilesize(long filesize) {
486 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
487 if (tv != null)
488 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
489 }
490
491 /**
492 * Updates the time that the file was created in view
493 * @param milliseconds Unix time to set
494 */
495 private void setTimeCreated(long milliseconds){
496 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
497 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
498 if(tv != null){
499 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
500 tv.setVisibility(View.VISIBLE);
501 tvLabel.setVisibility(View.VISIBLE);
502 }
503 }
504
505 /**
506 * Updates the time that the file was last modified
507 * @param milliseconds Unix time to set
508 */
509 private void setTimeModified(long milliseconds){
510 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
511 if(tv != null){
512 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
513 }
514 }
515
516 /**
517 * Enables or disables buttons for a file being downloaded
518 */
519 private void setButtonsForTransferring() {
520 if (!isEmpty()) {
521 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
522 //downloadButton.setText(R.string.filedetails_download_in_progress); // ugly
523 downloadButton.setEnabled(false); // TODO replace it with a 'cancel download' button
524
525 // let's protect the user from himself ;)
526 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
527 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(false);
528 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(false);
529 }
530 }
531
532 /**
533 * Enables or disables buttons for a file locally available
534 */
535 private void setButtonsForDown() {
536 if (!isEmpty()) {
537 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
538 //downloadButton.setText(R.string.filedetails_redownload); // ugly
539 downloadButton.setEnabled(true);
540
541 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(true);
542 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
543 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
544 }
545 }
546
547 /**
548 * Enables or disables buttons for a file not locally available
549 */
550 private void setButtonsForRemote() {
551 if (!isEmpty()) {
552 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
553 //downloadButton.setText(R.string.filedetails_download); // unnecessary
554 downloadButton.setEnabled(true);
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 private class ShareRunnable implements Runnable {
662 private String mPath;
663
664 public ShareRunnable(String path) {
665 mPath = path;
666 }
667
668 public void run() {
669 AccountManager am = AccountManager.get(getActivity());
670 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
671 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
672 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
673
674 Log.d("share", "sharing for version " + ocv.toString());
675
676 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
677 String APPS_PATH = "/apps/files_sharing/";
678 String SHARE_PATH = "ajax/share.php";
679
680 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
681
682 final String WEBDAV_SCRIPT = "webdav.php";
683 final String WEBDAV_FILES_LOCATION = "/files/";
684
685 WebdavClient wc = new WebdavClient();
686 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
687 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
688
689 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
690 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
691
692 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
693
694 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
695 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
696 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
697 Log.d("share", mPath+"");
698 formparams.add(new BasicNameValuePair("sources",mPath));
699 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
700 formparams.add(new BasicNameValuePair("permissions", "0"));
701 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
702
703 int status;
704 try {
705 PropFindMethod find = new PropFindMethod(url+"/");
706 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
707 Log.d("sharer", ""+ url+"/");
708 wc.setCredentials(account.name.substring(0, account.name.lastIndexOf('@')), am.getPassword(account));
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 (HttpException e) {
755 // TODO Auto-generated catch block
756 e.printStackTrace();
757 } catch (IOException e) {
758 // TODO Auto-generated catch block
759 e.printStackTrace();
760 } catch (JSONException e) {
761 // TODO Auto-generated catch block
762 e.printStackTrace();
763 } catch (Exception e) {
764 // TODO Auto-generated catch block
765 e.printStackTrace();
766 }
767
768 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
769
770 }
771 }
772 }
773
774 public void onDismiss(EditNameFragment dialog) {
775 if (dialog instanceof EditNameFragment) {
776 if (((EditNameFragment)dialog).getResult()) {
777 String newFilename = ((EditNameFragment)dialog).getNewFilename();
778 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
779 if (!newFilename.equals(mFile.getFileName())) {
780 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
781 if (fdsm.getFileById(mFile.getFileId()) != null) {
782 OCFile newFile = new OCFile(fdsm.getFileById(mFile.getParentId()).getRemotePath() + newFilename);
783 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
784 newFile.setFileId(mFile.getFileId());
785 newFile.setFileLength(mFile.getFileLength());
786 newFile.setKeepInSync(mFile.keepInSync());
787 newFile.setLastSyncDate(mFile.getLastSyncDate());
788 newFile.setMimetype(mFile.getMimetype());
789 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
790 newFile.setParentId(mFile.getParentId());
791 if (mFile.isDown()) {
792 File f = new File(mFile.getStoragePath());
793 Log.e(TAG, f.getAbsolutePath());
794 f.renameTo(new File(f.getParent() + File.separator + newFilename)); // TODO check if fails
795 Log.e(TAG, f.getParent() + File.separator + newFilename);
796 newFile.setStoragePath(f.getParent() + File.separator + newFilename);
797 }
798
799 new Thread(new RenameRunnable(mFile, newFile, mAccount, new Handler())).start();
800
801 }
802 }
803 }
804 } else {
805 Log.e(TAG, "Unknown dialog instance passed to onDismissDalog: " + dialog.getClass().getCanonicalName());
806 }
807
808 }
809
810 private class RenameRunnable implements Runnable {
811
812 Account mAccount;
813 OCFile mOld, mNew;
814 Handler mHandler;
815
816 public RenameRunnable(OCFile oldFile, OCFile newFile, Account account, Handler handler) {
817 mOld = oldFile;
818 mNew = newFile;
819 mAccount = account;
820 mHandler = handler;
821 }
822
823 public void run() {
824 WebdavClient wc = new WebdavClient(mAccount, getSherlockActivity().getApplicationContext());
825 wc.allowSelfsignedCertificates();
826 AccountManager am = AccountManager.get(getSherlockActivity());
827 String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
828 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
829 String webdav_path = AccountUtils.getWebdavPath(ocv);
830 Log.d("ASD", ""+baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()));
831
832 Log.e("ASD", Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath()));
833 LocalMoveMethod move = new LocalMoveMethod(baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()),
834 Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath()));
835
836 try {
837 int status = wc.executeMethod(move);
838 if (move.succeeded()) {
839 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
840 fdsm.removeFile(mOld);
841 fdsm.saveFile(mNew);
842 mFile = mNew;
843 mHandler.post(new Runnable() {
844 @Override
845 public void run() {
846 updateFileDetails(mFile, mAccount);
847 mContainerActivity.onFileStateChanged();
848 }
849 });
850 }
851 Log.e("ASD", ""+move.getQueryString());
852 Log.d("move", "returned status " + status);
853 } catch (HttpException e) {
854 // TODO Auto-generated catch block
855 e.printStackTrace();
856 } catch (IOException e) {
857 // TODO Auto-generated catch block
858 e.printStackTrace();
859 }
860 }
861 private class LocalMoveMethod extends DavMethodBase {
862
863 public LocalMoveMethod(String uri, String dest) {
864 super(uri);
865 addRequestHeader(new org.apache.commons.httpclient.Header("Destination", dest));
866 }
867
868 @Override
869 public String getName() {
870 return "MOVE";
871 }
872
873 @Override
874 protected boolean isSuccess(int status) {
875 return status == 201 || status == 204;
876 }
877
878 }
879 }
880
881 private static class EditNameFragment extends SherlockDialogFragment implements OnClickListener {
882
883 private String mNewFilename;
884 private boolean mResult;
885 private FileDetailFragment mListener;
886
887 static public EditNameFragment newInstance(String filename) {
888 EditNameFragment f = new EditNameFragment();
889 Bundle args = new Bundle();
890 args.putString("filename", filename);
891 f.setArguments(args);
892 return f;
893 }
894
895 @Override
896 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
897 View v = inflater.inflate(R.layout.edit_box_dialog, container, false);
898
899 String currentName = getArguments().getString("filename");
900 if (currentName == null)
901 currentName = "";
902
903 ((Button)v.findViewById(R.id.cancel)).setOnClickListener(this);
904 ((Button)v.findViewById(R.id.ok)).setOnClickListener(this);
905 ((TextView)v.findViewById(R.id.user_input)).setText(currentName);
906 ((TextView)v.findViewById(R.id.user_input)).requestFocus();
907 getDialog().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
908
909 mResult = false;
910 return v;
911 }
912
913 @Override
914 public void onClick(View view) {
915 switch (view.getId()) {
916 case R.id.ok: {
917 mNewFilename = ((TextView)getView().findViewById(R.id.user_input)).getText().toString();
918 mResult = true;
919 }
920 case R.id.cancel: { // fallthought
921 dismiss();
922 mListener.onDismiss(this);
923 }
924 }
925 }
926
927 void setOnDismissListener(FileDetailFragment listener) {
928 mListener = listener;
929 }
930
931 public String getNewFilename() {
932 return mNewFilename;
933 }
934
935 // true if user click ok
936 public boolean getResult() {
937 return mResult;
938 }
939
940 }
941
942 private class RemoveRunnable implements Runnable {
943
944 /** Arbitrary timeout for deletion */
945 public final static int DELETION_TIMEOUT = 5000;
946
947 Account mAccount;
948 OCFile mFileToRemove;
949 Handler mHandler;
950
951 public RemoveRunnable(OCFile fileToRemove, Account account, Handler handler) {
952 mFileToRemove = fileToRemove;
953 mAccount = account;
954 mHandler = handler;
955 }
956
957 public void run() {
958 WebdavClient wc = new WebdavClient(mAccount, getSherlockActivity().getApplicationContext());
959 wc.allowSelfsignedCertificates();
960 AccountManager am = AccountManager.get(getSherlockActivity());
961 String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
962 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
963 String webdav_path = AccountUtils.getWebdavPath(ocv);
964 Log.d("ASD", ""+baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));
965
966 DeleteMethod delete = new DeleteMethod(baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));
967
968 boolean success = false;
969 try {
970 int status = wc.executeMethod(delete, DELETION_TIMEOUT);
971 if (delete.succeeded()) {
972 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
973 fdsm.removeFile(mFileToRemove);
974 mHandler.post(new Runnable() {
975 @Override
976 public void run() {
977 try {
978 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
979 msg.show();
980 if (getActivity() instanceof FileDisplayActivity) {
981 // double pane
982 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
983 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
984 transaction.commit();
985 mContainerActivity.onFileStateChanged();
986
987 } else {
988 getActivity().finish();
989 }
990
991 } catch (NotFoundException e) {
992 e.printStackTrace();
993 }
994 }
995 });
996 success = true;
997 }
998 Log.e("ASD", ""+ delete.getQueryString());
999 Log.d("delete", "returned status " + status);
1000
1001 } catch (HttpException e) {
1002 e.printStackTrace();
1003
1004 } catch (IOException e) {
1005 e.printStackTrace();
1006
1007 } finally {
1008 if (!success) {
1009 mHandler.post(new Runnable() {
1010 @Override
1011 public void run() {
1012 try {
1013 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
1014 msg.show();
1015
1016 } catch (NotFoundException e) {
1017 e.printStackTrace();
1018 }
1019 }
1020 });
1021 }
1022 }
1023 }
1024
1025 }
1026
1027 class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
1028 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1029 @Override
1030 protected Bitmap doInBackground(String... params) {
1031 Bitmap result = null;
1032 if (params.length != 1) return result;
1033 String storagePath = params[0];
1034 try {
1035
1036 BitmapFactory.Options options = new Options();
1037 options.inScaled = true;
1038 options.inPurgeable = true;
1039 options.inJustDecodeBounds = true;
1040 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
1041 options.inPreferQualityOverSpeed = false;
1042 }
1043 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1044 options.inMutable = false;
1045 }
1046
1047 result = BitmapFactory.decodeFile(storagePath, options);
1048 options.inJustDecodeBounds = false;
1049
1050 int width = options.outWidth;
1051 int height = options.outHeight;
1052 int scale = 1;
1053 if (width >= 2048 || height >= 2048) {
1054 scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));
1055 options.inSampleSize = scale;
1056 }
1057 Display display = getActivity().getWindowManager().getDefaultDisplay();
1058 Point size = new Point();
1059 int screenwidth;
1060 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
1061 display.getSize(size);
1062 screenwidth = size.x;
1063 } else {
1064 screenwidth = display.getWidth();
1065 }
1066
1067 Log.e("ASD", "W " + width + " SW " + screenwidth);
1068
1069 if (width > screenwidth) {
1070 scale = (int) Math.ceil((float)width / screenwidth);
1071 options.inSampleSize = scale;
1072 }
1073
1074 result = BitmapFactory.decodeFile(storagePath, options);
1075
1076 Log.e("ASD", "W " + options.outWidth + " SW " + options.outHeight);
1077
1078 } catch (OutOfMemoryError e) {
1079 result = null;
1080 Log.e(TAG, "Out of memory occured for file with size " + storagePath);
1081
1082 } catch (NoSuchFieldError e) {
1083 result = null;
1084 Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath);
1085
1086 } catch (Throwable t) {
1087 result = null;
1088 Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t);
1089 }
1090 return result;
1091 }
1092 @Override
1093 protected void onPostExecute(Bitmap result) {
1094 if (result != null && mPreview != null) {
1095 mPreview.setImageBitmap(result);
1096 }
1097 }
1098
1099 }
1100
1101
1102 }