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