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