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