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