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