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