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