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