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