FileDetailFragment.java 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. /* ownCloud Android client application
  2. * Copyright (C) 2011 Bartek Przybylski
  3. * Copyright (C) 2012-2013 ownCloud Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2,
  7. * as published by the Free Software Foundation.
  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 com.owncloud.android.ui.fragment;
  19. import java.io.File;
  20. import java.lang.ref.WeakReference;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. import android.accounts.Account;
  24. import android.app.Activity;
  25. import android.content.ActivityNotFoundException;
  26. import android.content.BroadcastReceiver;
  27. import android.content.Context;
  28. import android.content.Intent;
  29. import android.content.IntentFilter;
  30. import android.net.Uri;
  31. import android.os.Bundle;
  32. import android.os.Handler;
  33. import android.support.v4.app.FragmentTransaction;
  34. import android.view.LayoutInflater;
  35. import android.view.View;
  36. import android.view.View.OnClickListener;
  37. import android.view.ViewGroup;
  38. import android.webkit.MimeTypeMap;
  39. import android.widget.CheckBox;
  40. import android.widget.ImageView;
  41. import android.widget.ProgressBar;
  42. import android.widget.TextView;
  43. import android.widget.Toast;
  44. import com.actionbarsherlock.app.SherlockFragment;
  45. import com.actionbarsherlock.view.Menu;
  46. import com.actionbarsherlock.view.MenuInflater;
  47. import com.actionbarsherlock.view.MenuItem;
  48. import com.owncloud.android.DisplayUtils;
  49. import com.owncloud.android.Log_OC;
  50. import com.owncloud.android.datamodel.FileDataStorageManager;
  51. import com.owncloud.android.datamodel.OCFile;
  52. import com.owncloud.android.files.services.FileObserverService;
  53. import com.owncloud.android.files.services.FileUploader;
  54. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  55. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  56. import com.owncloud.android.operations.OnRemoteOperationListener;
  57. import com.owncloud.android.operations.RemoteOperation;
  58. import com.owncloud.android.operations.RemoteOperationResult;
  59. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  60. import com.owncloud.android.operations.RemoveFileOperation;
  61. import com.owncloud.android.operations.RenameFileOperation;
  62. import com.owncloud.android.operations.SynchronizeFileOperation;
  63. import com.owncloud.android.ui.activity.ConflictsResolveActivity;
  64. import com.owncloud.android.ui.activity.FileActivity;
  65. import com.owncloud.android.ui.activity.FileDetailActivity;
  66. import com.owncloud.android.ui.activity.FileDisplayActivity;
  67. import com.owncloud.android.ui.dialog.EditNameDialog;
  68. import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
  69. import com.owncloud.android.R;
  70. import eu.alefzero.webdav.OnDatatransferProgressListener;
  71. import eu.alefzero.webdav.WebdavUtils;
  72. /**
  73. * This Fragment is used to display the details about a file.
  74. *
  75. * @author Bartek Przybylski
  76. * @author David A. Velasco
  77. */
  78. public class FileDetailFragment extends SherlockFragment implements
  79. OnClickListener,
  80. ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener,
  81. FileFragment {
  82. private FileFragment.ContainerActivity mContainerActivity;
  83. private int mLayout;
  84. private View mView;
  85. private OCFile mFile;
  86. private Account mAccount;
  87. private FileDataStorageManager mStorageManager;
  88. private UploadFinishReceiver mUploadFinishReceiver;
  89. public ProgressListener mProgressListener;
  90. private Handler mHandler;
  91. private RemoteOperation mLastRemoteOperation;
  92. private static final String TAG = FileDetailFragment.class.getSimpleName();
  93. public static final String FTAG = "FileDetails";
  94. public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
  95. /**
  96. * Creates an empty details fragment.
  97. *
  98. * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
  99. */
  100. public FileDetailFragment() {
  101. mFile = null;
  102. mAccount = null;
  103. mStorageManager = null;
  104. mLayout = R.layout.file_details_empty;
  105. mProgressListener = null;
  106. }
  107. /**
  108. * Creates a details fragment.
  109. *
  110. * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
  111. *
  112. * @param fileToDetail An {@link OCFile} to show in the fragment
  113. * @param ocAccount An ownCloud account; needed to start downloads
  114. */
  115. public FileDetailFragment(OCFile fileToDetail, Account ocAccount) {
  116. mFile = fileToDetail;
  117. mAccount = ocAccount;
  118. mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
  119. mLayout = R.layout.file_details_empty;
  120. mProgressListener = null;
  121. }
  122. @Override
  123. public void onCreate(Bundle savedInstanceState) {
  124. super.onCreate(savedInstanceState);
  125. mHandler = new Handler();
  126. setHasOptionsMenu(true);
  127. }
  128. @Override
  129. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  130. Bundle savedInstanceState) {
  131. super.onCreateView(inflater, container, savedInstanceState);
  132. if (savedInstanceState != null) {
  133. mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
  134. mAccount = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
  135. }
  136. if(mFile != null && mAccount != null) {
  137. mLayout = R.layout.file_details_fragment;
  138. }
  139. View view = null;
  140. view = inflater.inflate(mLayout, container, false);
  141. mView = view;
  142. if (mLayout == R.layout.file_details_fragment) {
  143. mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
  144. ProgressBar progressBar = (ProgressBar)mView.findViewById(R.id.fdProgressBar);
  145. mProgressListener = new ProgressListener(progressBar);
  146. mView.findViewById(R.id.fdCancelBtn).setOnClickListener(this);
  147. }
  148. updateFileDetails(false, false);
  149. return view;
  150. }
  151. /**
  152. * {@inheritDoc}
  153. */
  154. @Override
  155. public void onAttach(Activity activity) {
  156. super.onAttach(activity);
  157. try {
  158. mContainerActivity = (ContainerActivity) activity;
  159. } catch (ClassCastException e) {
  160. throw new ClassCastException(activity.toString() + " must implement " + FileDetailFragment.ContainerActivity.class.getSimpleName());
  161. }
  162. }
  163. /**
  164. * {@inheritDoc}
  165. */
  166. @Override
  167. public void onActivityCreated(Bundle savedInstanceState) {
  168. super.onActivityCreated(savedInstanceState);
  169. if (mAccount != null) {
  170. mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
  171. }
  172. }
  173. @Override
  174. public void onSaveInstanceState(Bundle outState) {
  175. super.onSaveInstanceState(outState);
  176. outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
  177. outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
  178. }
  179. @Override
  180. public void onStart() {
  181. super.onStart();
  182. listenForTransferProgress();
  183. }
  184. @Override
  185. public void onResume() {
  186. super.onResume();
  187. mUploadFinishReceiver = new UploadFinishReceiver();
  188. IntentFilter filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
  189. getActivity().registerReceiver(mUploadFinishReceiver, filter);
  190. }
  191. @Override
  192. public void onPause() {
  193. super.onPause();
  194. if (mUploadFinishReceiver != null) {
  195. getActivity().unregisterReceiver(mUploadFinishReceiver);
  196. mUploadFinishReceiver = null;
  197. }
  198. }
  199. @Override
  200. public void onStop() {
  201. super.onStop();
  202. leaveTransferProgress();
  203. }
  204. @Override
  205. public View getView() {
  206. return super.getView() == null ? mView : super.getView();
  207. }
  208. /**
  209. * {@inheritDoc}
  210. */
  211. @Override
  212. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  213. super.onCreateOptionsMenu(menu, inflater);
  214. inflater.inflate(R.menu.file_actions_menu, menu);
  215. MenuItem item = menu.findItem(R.id.action_see_details);
  216. if (item != null) {
  217. item.setVisible(false);
  218. item.setEnabled(false);
  219. }
  220. }
  221. /**
  222. * {@inheritDoc}
  223. */
  224. @Override
  225. public void onPrepareOptionsMenu (Menu menu) {
  226. super.onPrepareOptionsMenu(menu);
  227. List<Integer> toHide = new ArrayList<Integer>();
  228. List<Integer> toShow = new ArrayList<Integer>();
  229. FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
  230. boolean downloading = downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile);
  231. FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
  232. boolean uploading = uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile);
  233. if (downloading || uploading) {
  234. toHide.add(R.id.action_download_file);
  235. toHide.add(R.id.action_rename_file);
  236. toHide.add(R.id.action_remove_file);
  237. toHide.add(R.id.action_open_file_with);
  238. if (!downloading) {
  239. toHide.add(R.id.action_cancel_download);
  240. toShow.add(R.id.action_cancel_upload);
  241. } else {
  242. toHide.add(R.id.action_cancel_upload);
  243. toShow.add(R.id.action_cancel_download);
  244. }
  245. } else if (mFile != null && mFile.isDown()) {
  246. toHide.add(R.id.action_download_file);
  247. toHide.add(R.id.action_cancel_download);
  248. toHide.add(R.id.action_cancel_upload);
  249. toShow.add(R.id.action_rename_file);
  250. toShow.add(R.id.action_remove_file);
  251. toShow.add(R.id.action_open_file_with);
  252. toShow.add(R.id.action_sync_file);
  253. } else if (mFile != null) {
  254. toHide.add(R.id.action_open_file_with);
  255. toHide.add(R.id.action_cancel_download);
  256. toHide.add(R.id.action_cancel_upload);
  257. toHide.add(R.id.action_sync_file);
  258. toShow.add(R.id.action_rename_file);
  259. toShow.add(R.id.action_remove_file);
  260. toShow.add(R.id.action_download_file);
  261. } else {
  262. toHide.add(R.id.action_open_file_with);
  263. toHide.add(R.id.action_cancel_download);
  264. toHide.add(R.id.action_cancel_upload);
  265. toHide.add(R.id.action_sync_file);
  266. toHide.add(R.id.action_download_file);
  267. toHide.add(R.id.action_rename_file);
  268. toHide.add(R.id.action_remove_file);
  269. }
  270. MenuItem item = null;
  271. for (int i : toHide) {
  272. item = menu.findItem(i);
  273. if (item != null) {
  274. item.setVisible(false);
  275. item.setEnabled(false);
  276. }
  277. }
  278. for (int i : toShow) {
  279. item = menu.findItem(i);
  280. if (item != null) {
  281. item.setVisible(true);
  282. item.setEnabled(true);
  283. }
  284. }
  285. }
  286. /**
  287. * {@inheritDoc}
  288. */
  289. @Override
  290. public boolean onOptionsItemSelected(MenuItem item) {
  291. switch (item.getItemId()) {
  292. case R.id.action_open_file_with: {
  293. openFile();
  294. return true;
  295. }
  296. case R.id.action_remove_file: {
  297. removeFile();
  298. return true;
  299. }
  300. case R.id.action_rename_file: {
  301. renameFile();
  302. return true;
  303. }
  304. case R.id.action_download_file:
  305. case R.id.action_cancel_download:
  306. case R.id.action_cancel_upload:
  307. case R.id.action_sync_file: {
  308. synchronizeFile();
  309. return true;
  310. }
  311. default:
  312. return false;
  313. }
  314. }
  315. @Override
  316. public void onClick(View v) {
  317. switch (v.getId()) {
  318. case R.id.fdKeepInSync: {
  319. toggleKeepInSync();
  320. break;
  321. }
  322. case R.id.fdCancelBtn: {
  323. synchronizeFile();
  324. break;
  325. }
  326. default:
  327. Log_OC.e(TAG, "Incorrect view clicked!");
  328. }
  329. }
  330. private void toggleKeepInSync() {
  331. CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
  332. mFile.setKeepInSync(cb.isChecked());
  333. mStorageManager.saveFile(mFile);
  334. /// register the OCFile instance in the observer service to monitor local updates;
  335. /// if necessary, the file is download
  336. Intent intent = new Intent(getActivity().getApplicationContext(),
  337. FileObserverService.class);
  338. intent.putExtra(FileObserverService.KEY_FILE_CMD,
  339. (cb.isChecked()?
  340. FileObserverService.CMD_ADD_OBSERVED_FILE:
  341. FileObserverService.CMD_DEL_OBSERVED_FILE));
  342. intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
  343. intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
  344. getActivity().startService(intent);
  345. if (mFile.keepInSync()) {
  346. synchronizeFile(); // force an immediate synchronization
  347. }
  348. }
  349. private void removeFile() {
  350. ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
  351. R.string.confirmation_remove_alert,
  352. new String[]{mFile.getFileName()},
  353. mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
  354. mFile.isDown() ? R.string.confirmation_remove_local : -1,
  355. R.string.common_cancel);
  356. confDialog.setOnConfirmationListener(this);
  357. confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
  358. }
  359. private void renameFile() {
  360. String fileName = mFile.getFileName();
  361. int extensionStart = mFile.isDirectory() ? -1 : fileName.lastIndexOf(".");
  362. int selectionEnd = (extensionStart >= 0) ? extensionStart : fileName.length();
  363. EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), fileName, 0, selectionEnd, this);
  364. dialog.show(getFragmentManager(), "nameeditdialog");
  365. }
  366. private void synchronizeFile() {
  367. FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
  368. FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
  369. if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
  370. downloaderBinder.cancel(mAccount, mFile);
  371. if (mFile.isDown()) {
  372. setButtonsForDown();
  373. } else {
  374. setButtonsForRemote();
  375. }
  376. } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
  377. uploaderBinder.cancel(mAccount, mFile);
  378. if (!mFile.fileExists()) {
  379. // TODO make something better
  380. if (getActivity() instanceof FileDisplayActivity) {
  381. // double pane
  382. FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
  383. transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FTAG); // empty FileDetailFragment
  384. transaction.commit();
  385. mContainerActivity.onFileStateChanged();
  386. } else {
  387. getActivity().finish();
  388. }
  389. } else if (mFile.isDown()) {
  390. setButtonsForDown();
  391. } else {
  392. setButtonsForRemote();
  393. }
  394. } else {
  395. mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
  396. mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
  397. // update ui
  398. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  399. getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  400. }
  401. }
  402. /**
  403. * Opens mFile.
  404. */
  405. private void openFile() {
  406. String storagePath = mFile.getStoragePath();
  407. String encodedStoragePath = WebdavUtils.encodePath(storagePath);
  408. try {
  409. Intent i = new Intent(Intent.ACTION_VIEW);
  410. i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
  411. i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  412. startActivity(i);
  413. } catch (Throwable t) {
  414. Log_OC.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
  415. boolean toastIt = true;
  416. String mimeType = "";
  417. try {
  418. Intent i = new Intent(Intent.ACTION_VIEW);
  419. mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
  420. if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
  421. if (mimeType != null) {
  422. i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
  423. } else {
  424. // desperate try
  425. i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*/*");
  426. }
  427. i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  428. startActivity(i);
  429. toastIt = false;
  430. }
  431. } catch (IndexOutOfBoundsException e) {
  432. Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
  433. } catch (ActivityNotFoundException e) {
  434. Log_OC.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
  435. } catch (Throwable th) {
  436. Log_OC.e(TAG, "Unexpected problem when opening: " + storagePath, th);
  437. } finally {
  438. if (toastIt) {
  439. Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
  440. }
  441. }
  442. }
  443. }
  444. @Override
  445. public void onConfirmation(String callerTag) {
  446. if (callerTag.equals(FTAG_CONFIRMATION)) {
  447. if (mStorageManager.getFileById(mFile.getFileId()) != null) {
  448. mLastRemoteOperation = new RemoveFileOperation( mFile,
  449. true,
  450. mStorageManager);
  451. mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
  452. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  453. getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  454. }
  455. }
  456. }
  457. @Override
  458. public void onNeutral(String callerTag) {
  459. File f = null;
  460. if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
  461. f.delete();
  462. mFile.setStoragePath(null);
  463. mStorageManager.saveFile(mFile);
  464. updateFileDetails(mFile, mAccount);
  465. }
  466. }
  467. @Override
  468. public void onCancel(String callerTag) {
  469. Log_OC.d(TAG, "REMOVAL CANCELED");
  470. }
  471. /**
  472. * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
  473. *
  474. * @return True when the fragment was created with the empty layout.
  475. */
  476. public boolean isEmpty() {
  477. return (mLayout == R.layout.file_details_empty || mFile == null || mAccount == null);
  478. }
  479. /**
  480. * {@inheritDoc}
  481. */
  482. public OCFile getFile(){
  483. return mFile;
  484. }
  485. /**
  486. * Use this method to signal this Activity that it shall update its view.
  487. *
  488. * @param file : An {@link OCFile}
  489. */
  490. public void updateFileDetails(OCFile file, Account ocAccount) {
  491. mFile = file;
  492. if (ocAccount != null && (
  493. mStorageManager == null ||
  494. (mAccount != null && !mAccount.equals(ocAccount))
  495. )) {
  496. mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
  497. }
  498. mAccount = ocAccount;
  499. updateFileDetails(false, false);
  500. }
  501. /**
  502. * Updates the view with all relevant details about that file.
  503. *
  504. * TODO Remove parameter when the transferring state of files is kept in database.
  505. *
  506. * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
  507. *
  508. * @param transferring Flag signaling if the file should be considered as downloading or uploading,
  509. * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
  510. * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
  511. *
  512. * @param refresh If 'true', try to refresh the hold file from the database
  513. */
  514. public void updateFileDetails(boolean transferring, boolean refresh) {
  515. if (readyToShow()) {
  516. if (refresh && mStorageManager != null) {
  517. mFile = mStorageManager.getFileByPath(mFile.getRemotePath());
  518. }
  519. // set file details
  520. setFilename(mFile.getFileName());
  521. setFiletype(mFile.getMimetype());
  522. setFilesize(mFile.getFileLength());
  523. if(ocVersionSupportsTimeCreated()){
  524. setTimeCreated(mFile.getCreationTimestamp());
  525. }
  526. setTimeModified(mFile.getModificationTimestamp());
  527. CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
  528. cb.setChecked(mFile.keepInSync());
  529. // configure UI for depending upon local state of the file
  530. //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
  531. FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
  532. FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
  533. if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {
  534. setButtonsForTransferring();
  535. } else if (mFile.isDown()) {
  536. setButtonsForDown();
  537. } else {
  538. // TODO load default preview image; when the local file is removed, the preview remains there
  539. setButtonsForRemote();
  540. }
  541. }
  542. getView().invalidate();
  543. }
  544. /**
  545. * Checks if the fragment is ready to show details of a OCFile
  546. *
  547. * @return 'True' when the fragment is ready to show details of a file
  548. */
  549. private boolean readyToShow() {
  550. return (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment);
  551. }
  552. /**
  553. * Updates the filename in view
  554. * @param filename to set
  555. */
  556. private void setFilename(String filename) {
  557. TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
  558. if (tv != null)
  559. tv.setText(filename);
  560. }
  561. /**
  562. * Updates the MIME type in view
  563. * @param mimetype to set
  564. */
  565. private void setFiletype(String mimetype) {
  566. TextView tv = (TextView) getView().findViewById(R.id.fdType);
  567. if (tv != null) {
  568. String printableMimetype = DisplayUtils.convertMIMEtoPrettyPrint(mimetype);;
  569. tv.setText(printableMimetype);
  570. }
  571. ImageView iv = (ImageView) getView().findViewById(R.id.fdIcon);
  572. if (iv != null) {
  573. iv.setImageResource(DisplayUtils.getResourceId(mimetype));
  574. }
  575. }
  576. /**
  577. * Updates the file size in view
  578. * @param filesize in bytes to set
  579. */
  580. private void setFilesize(long filesize) {
  581. TextView tv = (TextView) getView().findViewById(R.id.fdSize);
  582. if (tv != null)
  583. tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
  584. }
  585. /**
  586. * Updates the time that the file was created in view
  587. * @param milliseconds Unix time to set
  588. */
  589. private void setTimeCreated(long milliseconds){
  590. TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
  591. TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
  592. if(tv != null){
  593. tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
  594. tv.setVisibility(View.VISIBLE);
  595. tvLabel.setVisibility(View.VISIBLE);
  596. }
  597. }
  598. /**
  599. * Updates the time that the file was last modified
  600. * @param milliseconds Unix time to set
  601. */
  602. private void setTimeModified(long milliseconds){
  603. TextView tv = (TextView) getView().findViewById(R.id.fdModified);
  604. if(tv != null){
  605. tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
  606. }
  607. }
  608. /**
  609. * Enables or disables buttons for a file being downloaded
  610. */
  611. private void setButtonsForTransferring() {
  612. if (!isEmpty()) {
  613. // let's protect the user from himself ;)
  614. getView().findViewById(R.id.fdKeepInSync).setEnabled(false);
  615. // show the progress bar for the transfer
  616. getView().findViewById(R.id.fdProgressBlock).setVisibility(View.VISIBLE);
  617. TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
  618. progressText.setVisibility(View.VISIBLE);
  619. FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
  620. FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
  621. if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
  622. progressText.setText(R.string.downloader_download_in_progress_ticker);
  623. } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
  624. progressText.setText(R.string.uploader_upload_in_progress_ticker);
  625. }
  626. }
  627. }
  628. /**
  629. * Enables or disables buttons for a file locally available
  630. */
  631. private void setButtonsForDown() {
  632. if (!isEmpty()) {
  633. getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
  634. // hides the progress bar
  635. getView().findViewById(R.id.fdProgressBlock).setVisibility(View.GONE);
  636. TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
  637. progressText.setVisibility(View.GONE);
  638. }
  639. }
  640. /**
  641. * Enables or disables buttons for a file not locally available
  642. */
  643. private void setButtonsForRemote() {
  644. if (!isEmpty()) {
  645. getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
  646. // hides the progress bar
  647. getView().findViewById(R.id.fdProgressBlock).setVisibility(View.GONE);
  648. TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
  649. progressText.setVisibility(View.GONE);
  650. }
  651. }
  652. /**
  653. * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
  654. * the time that the file was created. There is a chance that this will
  655. * be fixed in future versions. Use this method to check if this version of
  656. * ownCloud has this fix.
  657. * @return True, if ownCloud the ownCloud version is supporting creation time
  658. */
  659. private boolean ocVersionSupportsTimeCreated(){
  660. /*if(mAccount != null){
  661. AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
  662. OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
  663. .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
  664. if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
  665. return true;
  666. }
  667. }*/
  668. return false;
  669. }
  670. /**
  671. * Once the file upload has finished -> update view
  672. *
  673. * Being notified about the finish of an upload is necessary for the next sequence:
  674. * 1. Upload a big file.
  675. * 2. Force a synchronization; if it finished before the upload, the file in transfer will be included in the local database and in the file list
  676. * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
  677. * 3. Click the file in the list to see its details.
  678. * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
  679. */
  680. private class UploadFinishReceiver extends BroadcastReceiver {
  681. @Override
  682. public void onReceive(Context context, Intent intent) {
  683. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  684. if (!isEmpty() && accountName.equals(mAccount.name)) {
  685. boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
  686. String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
  687. boolean renamedInUpload = mFile.getRemotePath().equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  688. if (mFile.getRemotePath().equals(uploadRemotePath) ||
  689. renamedInUpload) {
  690. if (uploadWasFine) {
  691. mFile = mStorageManager.getFileByPath(uploadRemotePath);
  692. }
  693. if (renamedInUpload) {
  694. String newName = (new File(uploadRemotePath)).getName();
  695. Toast msg = Toast.makeText(getActivity().getApplicationContext(), String.format(getString(R.string.filedetails_renamed_in_upload_msg), newName), Toast.LENGTH_LONG);
  696. msg.show();
  697. }
  698. getSherlockActivity().removeStickyBroadcast(intent); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
  699. updateFileDetails(false, false); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
  700. }
  701. }
  702. }
  703. }
  704. public void onDismiss(EditNameDialog dialog) {
  705. if (dialog.getResult()) {
  706. String newFilename = dialog.getNewFilename();
  707. Log_OC.d(TAG, "name edit dialog dismissed with new name " + newFilename);
  708. mLastRemoteOperation = new RenameFileOperation( mFile,
  709. mAccount,
  710. newFilename,
  711. new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
  712. mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
  713. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  714. getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  715. }
  716. }
  717. /**
  718. * {@inheritDoc}
  719. */
  720. @Override
  721. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  722. if (operation.equals(mLastRemoteOperation)) {
  723. if (operation instanceof RemoveFileOperation) {
  724. onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
  725. } else if (operation instanceof RenameFileOperation) {
  726. onRenameFileOperationFinish((RenameFileOperation)operation, result);
  727. } else if (operation instanceof SynchronizeFileOperation) {
  728. onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
  729. }
  730. }
  731. }
  732. private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
  733. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  734. getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  735. if (result.isSuccess()) {
  736. Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
  737. msg.show();
  738. if (inDisplayActivity) {
  739. // double pane
  740. FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
  741. transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
  742. transaction.commit();
  743. mContainerActivity.onFileStateChanged();
  744. } else {
  745. getActivity().finish();
  746. }
  747. } else {
  748. Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
  749. msg.show();
  750. if (result.isSslRecoverableException()) {
  751. // TODO show the SSL warning dialog
  752. }
  753. }
  754. }
  755. private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
  756. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  757. getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  758. if (result.isSuccess()) {
  759. updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
  760. mContainerActivity.onFileStateChanged();
  761. } else {
  762. if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
  763. Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
  764. msg.show();
  765. // TODO throw again the new rename dialog
  766. } else {
  767. Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
  768. msg.show();
  769. if (result.isSslRecoverableException()) {
  770. // TODO show the SSL warning dialog
  771. }
  772. }
  773. }
  774. }
  775. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
  776. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  777. getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  778. if (!result.isSuccess()) {
  779. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  780. Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
  781. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);
  782. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
  783. startActivity(i);
  784. } else {
  785. Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
  786. msg.show();
  787. }
  788. if (mFile.isDown()) {
  789. setButtonsForDown();
  790. } else {
  791. setButtonsForRemote();
  792. }
  793. } else {
  794. if (operation.transferWasRequested()) {
  795. setButtonsForTransferring();
  796. mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
  797. // checking the service to see if the file is downloading results in FALSE
  798. } else {
  799. Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
  800. msg.show();
  801. if (mFile.isDown()) {
  802. setButtonsForDown();
  803. } else {
  804. setButtonsForRemote();
  805. }
  806. }
  807. }
  808. }
  809. public void listenForTransferProgress() {
  810. if (mProgressListener != null) {
  811. if (mContainerActivity.getFileDownloaderBinder() != null) {
  812. mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
  813. }
  814. if (mContainerActivity.getFileUploaderBinder() != null) {
  815. mContainerActivity.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
  816. }
  817. }
  818. }
  819. public void leaveTransferProgress() {
  820. if (mProgressListener != null) {
  821. if (mContainerActivity.getFileDownloaderBinder() != null) {
  822. mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
  823. }
  824. if (mContainerActivity.getFileUploaderBinder() != null) {
  825. mContainerActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
  826. }
  827. }
  828. }
  829. /**
  830. * Helper class responsible for updating the progress bar shown for file uploading or downloading
  831. *
  832. * @author David A. Velasco
  833. */
  834. private class ProgressListener implements OnDatatransferProgressListener {
  835. int mLastPercent = 0;
  836. WeakReference<ProgressBar> mProgressBar = null;
  837. ProgressListener(ProgressBar progressBar) {
  838. mProgressBar = new WeakReference<ProgressBar>(progressBar);
  839. }
  840. @Override
  841. public void onTransferProgress(long progressRate) {
  842. // old method, nothing here
  843. };
  844. @Override
  845. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename) {
  846. int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
  847. if (percent != mLastPercent) {
  848. ProgressBar pb = mProgressBar.get();
  849. if (pb != null) {
  850. pb.setProgress(percent);
  851. pb.postInvalidate();
  852. }
  853. }
  854. mLastPercent = percent;
  855. }
  856. };
  857. /*
  858. // this is a temporary class for sharing purposes, it need to be replaced in transfer service
  859. @SuppressWarnings("unused")
  860. private class ShareRunnable implements Runnable {
  861. private String mPath;
  862. public ShareRunnable(String path) {
  863. mPath = path;
  864. }
  865. public void run() {
  866. AccountManager am = AccountManager.get(getActivity());
  867. Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
  868. OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
  869. String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
  870. Log_OC.d("share", "sharing for version " + ocv.toString());
  871. if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
  872. String APPS_PATH = "/apps/files_sharing/";
  873. String SHARE_PATH = "ajax/share.php";
  874. String SHARED_PATH = "/apps/files_sharing/get.php?token=";
  875. final String WEBDAV_SCRIPT = "webdav.php";
  876. final String WEBDAV_FILES_LOCATION = "/files/";
  877. WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
  878. HttpConnectionManagerParams params = new HttpConnectionManagerParams();
  879. params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
  880. //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
  881. //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
  882. PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
  883. post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
  884. post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
  885. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  886. Log_OC.d("share", mPath+"");
  887. formparams.add(new BasicNameValuePair("sources",mPath));
  888. formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
  889. formparams.add(new BasicNameValuePair("permissions", "0"));
  890. post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
  891. int status;
  892. try {
  893. PropFindMethod find = new PropFindMethod(url+"/");
  894. find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
  895. Log_OC.d("sharer", ""+ url+"/");
  896. for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
  897. Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
  898. }
  899. int status2 = wc.executeMethod(find);
  900. Log_OC.d("sharer", "propstatus "+status2);
  901. GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
  902. get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
  903. status2 = wc.executeMethod(get);
  904. Log_OC.d("sharer", "getstatus "+status2);
  905. Log_OC.d("sharer", "" + get.getResponseBodyAsString());
  906. for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
  907. Log_OC.d("sharer", a.getName() + ":"+a.getValue());
  908. }
  909. status = wc.executeMethod(post);
  910. for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
  911. Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
  912. }
  913. for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
  914. Log_OC.d("sharer", a.getName() + ":"+a.getValue());
  915. }
  916. String resp = post.getResponseBodyAsString();
  917. Log_OC.d("share", ""+post.getURI().toString());
  918. Log_OC.d("share", "returned status " + status);
  919. Log_OC.d("share", " " +resp);
  920. if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
  921. return;
  922. }
  923. JSONObject jsonObject = new JSONObject (resp);
  924. String jsonStatus = jsonObject.getString("status");
  925. if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
  926. String token = jsonObject.getString("data");
  927. String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
  928. Log_OC.d("Actions:shareFile ok", "url: " + uri);
  929. } catch (Exception e) {
  930. e.printStackTrace();
  931. }
  932. } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
  933. }
  934. }
  935. }
  936. */
  937. }