FileDisplayActivity.java 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  1. /* ownCloud Android client application
  2. * Copyright (C) 2011 Bartek Przybylski
  3. * Copyright (C) 2012-2014 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.activity;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import org.apache.commons.httpclient.methods.PostMethod;
  22. import android.accounts.Account;
  23. import android.accounts.AccountManager;
  24. import android.accounts.AuthenticatorException;
  25. import android.accounts.OperationCanceledException;
  26. import android.app.AlertDialog;
  27. import android.app.Dialog;
  28. import android.app.ProgressDialog;
  29. import android.content.BroadcastReceiver;
  30. import android.content.ComponentName;
  31. import android.content.ContentResolver;
  32. import android.content.Context;
  33. import android.content.DialogInterface;
  34. import android.content.Intent;
  35. import android.content.IntentFilter;
  36. import android.content.ServiceConnection;
  37. import android.content.SharedPreferences;
  38. import android.content.SyncRequest;
  39. import android.content.res.Resources.NotFoundException;
  40. import android.database.Cursor;
  41. import android.net.Uri;
  42. import android.os.Bundle;
  43. import android.os.IBinder;
  44. import android.preference.PreferenceManager;
  45. import android.provider.MediaStore;
  46. import android.support.v4.app.Fragment;
  47. import android.support.v4.app.FragmentManager;
  48. import android.support.v4.app.FragmentTransaction;
  49. import android.support.v4.widget.SwipeRefreshLayout;
  50. import android.util.Log;
  51. import android.view.View;
  52. import android.view.ViewGroup;
  53. import android.widget.ArrayAdapter;
  54. import android.widget.TextView;
  55. import android.widget.Toast;
  56. import com.actionbarsherlock.app.ActionBar;
  57. import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
  58. import com.actionbarsherlock.view.Menu;
  59. import com.actionbarsherlock.view.MenuInflater;
  60. import com.actionbarsherlock.view.MenuItem;
  61. import com.actionbarsherlock.view.Window;
  62. import com.owncloud.android.MainApp;
  63. import com.owncloud.android.R;
  64. import com.owncloud.android.datamodel.OCFile;
  65. import com.owncloud.android.files.services.FileDownloader;
  66. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  67. import com.owncloud.android.files.services.FileUploader;
  68. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  69. import com.owncloud.android.lib.common.OwnCloudAccount;
  70. import com.owncloud.android.lib.common.OwnCloudClient;
  71. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  72. import com.owncloud.android.lib.common.OwnCloudCredentials;
  73. import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
  74. import com.owncloud.android.lib.common.network.CertificateCombinedException;
  75. import com.owncloud.android.lib.common.operations.RemoteOperation;
  76. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  77. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  78. import com.owncloud.android.operations.CreateFolderOperation;
  79. import com.owncloud.android.operations.CreateShareOperation;
  80. import com.owncloud.android.operations.MoveFileOperation;
  81. import com.owncloud.android.operations.RemoveFileOperation;
  82. import com.owncloud.android.operations.RenameFileOperation;
  83. import com.owncloud.android.operations.SynchronizeFileOperation;
  84. import com.owncloud.android.operations.SynchronizeFolderOperation;
  85. import com.owncloud.android.operations.UnshareLinkOperation;
  86. import com.owncloud.android.services.observer.FileObserverService;
  87. import com.owncloud.android.syncadapter.FileSyncAdapter;
  88. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  89. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
  90. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
  91. import com.owncloud.android.ui.fragment.FileDetailFragment;
  92. import com.owncloud.android.ui.fragment.FileFragment;
  93. import com.owncloud.android.ui.fragment.OCFileListFragment;
  94. import com.owncloud.android.ui.preview.PreviewImageActivity;
  95. import com.owncloud.android.ui.preview.PreviewImageFragment;
  96. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  97. import com.owncloud.android.ui.preview.PreviewVideoActivity;
  98. import com.owncloud.android.utils.DisplayUtils;
  99. import com.owncloud.android.utils.ErrorMessageAdapter;
  100. import com.owncloud.android.utils.Log_OC;
  101. /**
  102. * Displays, what files the user has available in his ownCloud.
  103. *
  104. * @author Bartek Przybylski
  105. * @author David A. Velasco
  106. */
  107. public class FileDisplayActivity extends HookActivity implements
  108. FileFragment.ContainerActivity, OnNavigationListener,
  109. OnSslUntrustedCertListener, SwipeRefreshLayout.OnRefreshListener {
  110. private ArrayAdapter<String> mDirectories;
  111. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  112. private UploadFinishReceiver mUploadFinishReceiver;
  113. private DownloadFinishReceiver mDownloadFinishReceiver;
  114. private RemoteOperationResult mLastSslUntrustedServerResult = null;
  115. private boolean mDualPane;
  116. private View mLeftFragmentContainer;
  117. private View mRightFragmentContainer;
  118. private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  119. private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
  120. private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
  121. public static final int DIALOG_SHORT_WAIT = 0;
  122. private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
  123. private static final int DIALOG_CERT_NOT_SAVED = 2;
  124. public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
  125. private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
  126. private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
  127. public static final int ACTION_MOVE_FILES = 3;
  128. private static final String TAG = FileDisplayActivity.class.getSimpleName();
  129. private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
  130. private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
  131. private OCFile mWaitingToPreview;
  132. private boolean mSyncInProgress = false;
  133. private String DIALOG_UNTRUSTED_CERT;
  134. private OCFile mWaitingToSend;
  135. @Override
  136. protected void onCreate(Bundle savedInstanceState) {
  137. Log_OC.d(TAG, "onCreate() start");
  138. requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
  139. super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
  140. // PIN CODE request ; best location is to decide, let's try this first
  141. if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
  142. requestPinCode();
  143. } else if (getIntent().getAction() == null && savedInstanceState == null) {
  144. requestPinCode();
  145. }
  146. /// grant that FileObserverService is watching favourite files
  147. if (savedInstanceState == null) {
  148. Intent initObserversIntent = FileObserverService.makeInitIntent(this);
  149. startService(initObserversIntent);
  150. }
  151. /// Load of saved instance state
  152. if(savedInstanceState != null) {
  153. mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
  154. mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
  155. mWaitingToSend = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND);
  156. } else {
  157. mWaitingToPreview = null;
  158. mSyncInProgress = false;
  159. mWaitingToSend = null;
  160. }
  161. /// USER INTERFACE
  162. // Inflate and set the layout view
  163. setContentView(R.layout.files);
  164. mDualPane = getResources().getBoolean(R.bool.large_land_layout);
  165. mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
  166. mRightFragmentContainer = findViewById(R.id.right_fragment_container);
  167. if (savedInstanceState == null) {
  168. createMinFragments();
  169. }
  170. // Action bar setup
  171. mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
  172. getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
  173. setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
  174. setBackgroundText();
  175. Log_OC.d(TAG, "onCreate() end");
  176. }
  177. @Override
  178. protected void onStart() {
  179. super.onStart();
  180. getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
  181. }
  182. @Override
  183. protected void onDestroy() {
  184. super.onDestroy();
  185. }
  186. /**
  187. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  188. */
  189. @Override
  190. protected void onAccountSet(boolean stateWasRecovered) {
  191. super.onAccountSet(stateWasRecovered);
  192. if (getAccount() != null) {
  193. /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
  194. OCFile file = getFile();
  195. // get parent from path
  196. String parentPath = "";
  197. if (file != null) {
  198. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  199. // upload in progress - right now, files are not inserted in the local cache until the upload is successful
  200. // get parent from path
  201. parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
  202. if (getStorageManager().getFileByPath(parentPath) == null)
  203. file = null; // not able to know the directory where the file is uploading
  204. } else {
  205. file = getStorageManager().getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
  206. }
  207. }
  208. if (file == null) {
  209. // fall back to root folder
  210. file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
  211. }
  212. setFile(file);
  213. setNavigationListWithFolder(file);
  214. if (!stateWasRecovered) {
  215. Log_OC.e(TAG, "Initializing Fragments in onAccountChanged..");
  216. initFragmentsWithFile();
  217. if (file.isFolder()) {
  218. startSyncFolderOperation(file, false);
  219. }
  220. } else {
  221. updateFragmentsVisibility(!file.isFolder());
  222. updateNavigationElementsInActionBar(file.isFolder() ? null : file);
  223. }
  224. }
  225. }
  226. private void setNavigationListWithFolder(OCFile file) {
  227. mDirectories.clear();
  228. OCFile fileIt = file;
  229. String parentPath;
  230. while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
  231. if (fileIt.isFolder()) {
  232. mDirectories.add(fileIt.getFileName());
  233. }
  234. // get parent from path
  235. parentPath = fileIt.getRemotePath().substring(0, fileIt.getRemotePath().lastIndexOf(fileIt.getFileName()));
  236. fileIt = getStorageManager().getFileByPath(parentPath);
  237. }
  238. mDirectories.add(OCFile.PATH_SEPARATOR);
  239. }
  240. private void createMinFragments() {
  241. OCFileListFragment listOfFiles = new OCFileListFragment();
  242. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  243. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  244. transaction.commit();
  245. }
  246. private void initFragmentsWithFile() {
  247. if (getAccount() != null && getFile() != null) {
  248. /// First fragment
  249. OCFileListFragment listOfFiles = getListOfFilesFragment();
  250. if (listOfFiles != null) {
  251. listOfFiles.listDirectory(getCurrentDir());
  252. } else {
  253. Log.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
  254. }
  255. /// Second fragment
  256. OCFile file = getFile();
  257. Fragment secondFragment = chooseInitialSecondFragment(file);
  258. if (secondFragment != null) {
  259. setSecondFragment(secondFragment);
  260. updateFragmentsVisibility(true);
  261. updateNavigationElementsInActionBar(file);
  262. } else {
  263. cleanSecondFragment();
  264. }
  265. } else {
  266. Log.wtf(TAG, "initFragments() called with invalid NULLs!");
  267. if (getAccount() == null) {
  268. Log.wtf(TAG, "\t account is NULL");
  269. }
  270. if (getFile() == null) {
  271. Log.wtf(TAG, "\t file is NULL");
  272. }
  273. }
  274. }
  275. private Fragment chooseInitialSecondFragment(OCFile file) {
  276. Fragment secondFragment = null;
  277. if (file != null && !file.isFolder()) {
  278. if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
  279. && file.getLastSyncDateForProperties() > 0 // temporal fix
  280. ) {
  281. int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
  282. boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
  283. secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
  284. } else {
  285. secondFragment = new FileDetailFragment(file, getAccount());
  286. }
  287. }
  288. return secondFragment;
  289. }
  290. /**
  291. * Replaces the second fragment managed by the activity with the received as
  292. * a parameter.
  293. *
  294. * Assumes never will be more than two fragments managed at the same time.
  295. *
  296. * @param fragment New second Fragment to set.
  297. */
  298. private void setSecondFragment(Fragment fragment) {
  299. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  300. transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
  301. transaction.commit();
  302. }
  303. private void updateFragmentsVisibility(boolean existsSecondFragment) {
  304. if (mDualPane) {
  305. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  306. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  307. }
  308. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  309. mRightFragmentContainer.setVisibility(View.VISIBLE);
  310. }
  311. } else if (existsSecondFragment) {
  312. if (mLeftFragmentContainer.getVisibility() != View.GONE) {
  313. mLeftFragmentContainer.setVisibility(View.GONE);
  314. }
  315. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  316. mRightFragmentContainer.setVisibility(View.VISIBLE);
  317. }
  318. } else {
  319. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  320. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  321. }
  322. if (mRightFragmentContainer.getVisibility() != View.GONE) {
  323. mRightFragmentContainer.setVisibility(View.GONE);
  324. }
  325. }
  326. }
  327. private OCFileListFragment getListOfFilesFragment() {
  328. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
  329. if (listOfFiles != null) {
  330. return (OCFileListFragment)listOfFiles;
  331. }
  332. Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
  333. return null;
  334. }
  335. public FileFragment getSecondFragment() {
  336. Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
  337. if (second != null) {
  338. return (FileFragment)second;
  339. }
  340. return null;
  341. }
  342. protected void cleanSecondFragment() {
  343. Fragment second = getSecondFragment();
  344. if (second != null) {
  345. FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
  346. tr.remove(second);
  347. tr.commit();
  348. }
  349. updateFragmentsVisibility(false);
  350. updateNavigationElementsInActionBar(null);
  351. }
  352. protected void refreshListOfFilesFragment() {
  353. OCFileListFragment fileListFragment = getListOfFilesFragment();
  354. if (fileListFragment != null) {
  355. fileListFragment.listDirectory();
  356. }
  357. }
  358. protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
  359. FileFragment secondFragment = getSecondFragment();
  360. boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
  361. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  362. FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
  363. OCFile fileInFragment = detailsFragment.getFile();
  364. if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  365. // the user browsed to other file ; forget the automatic preview
  366. mWaitingToPreview = null;
  367. } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
  368. // grant that the right panel updates the progress bar
  369. detailsFragment.listenForTransferProgress();
  370. detailsFragment.updateFileDetails(true, false);
  371. } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
  372. // update the right panel
  373. boolean detailsFragmentChanged = false;
  374. if (waitedPreview) {
  375. if (success) {
  376. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
  377. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  378. startMediaPreview(mWaitingToPreview, 0, true);
  379. detailsFragmentChanged = true;
  380. } else {
  381. getFileOperationsHelper().openFile(mWaitingToPreview);
  382. }
  383. }
  384. mWaitingToPreview = null;
  385. }
  386. if (!detailsFragmentChanged) {
  387. detailsFragment.updateFileDetails(false, (success));
  388. }
  389. }
  390. }
  391. }
  392. @Override
  393. public boolean onCreateOptionsMenu(Menu menu) {
  394. MenuInflater inflater = getSherlock().getMenuInflater();
  395. inflater.inflate(R.menu.main_menu, menu);
  396. return true;
  397. }
  398. @Override
  399. public boolean onOptionsItemSelected(MenuItem item) {
  400. boolean retval = true;
  401. switch (item.getItemId()) {
  402. case R.id.action_create_dir: {
  403. CreateFolderDialogFragment dialog =
  404. CreateFolderDialogFragment.newInstance(getCurrentDir());
  405. dialog.show(getSupportFragmentManager(), "createdirdialog");
  406. break;
  407. }
  408. case R.id.action_sync_account: {
  409. startSynchronization();
  410. break;
  411. }
  412. case R.id.action_upload: {
  413. showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
  414. break;
  415. }
  416. case R.id.action_settings: {
  417. Intent settingsIntent = new Intent(this, Preferences.class);
  418. startActivity(settingsIntent);
  419. break;
  420. }
  421. case android.R.id.home: {
  422. FileFragment second = getSecondFragment();
  423. OCFile currentDir = getCurrentDir();
  424. if((currentDir != null && currentDir.getParentId() != 0) ||
  425. (second != null && second.getFile() != null)) {
  426. onBackPressed();
  427. }
  428. break;
  429. }
  430. default:
  431. retval = super.onOptionsItemSelected(item);
  432. }
  433. return retval;
  434. }
  435. private void startSynchronization() {
  436. Log_OC.e(TAG, "Got to start sync");
  437. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  438. Log_OC.e(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  439. ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
  440. Bundle bundle = new Bundle();
  441. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  442. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  443. Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
  444. ContentResolver.requestSync(
  445. getAccount(),
  446. MainApp.getAuthority(), bundle);
  447. } else {
  448. Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
  449. SyncRequest.Builder builder = new SyncRequest.Builder();
  450. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  451. builder.setExpedited(true);
  452. builder.setManual(true);
  453. builder.syncOnce();
  454. SyncRequest request = builder.build();
  455. ContentResolver.requestSync(request);
  456. }
  457. }
  458. @Override
  459. public boolean onNavigationItemSelected(int itemPosition, long itemId) {
  460. if (itemPosition != 0) {
  461. String targetPath = "";
  462. for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
  463. targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
  464. }
  465. targetPath = OCFile.PATH_SEPARATOR + targetPath;
  466. OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
  467. if (targetFolder != null) {
  468. browseTo(targetFolder);
  469. }
  470. // the next operation triggers a new call to this method, but it's necessary to
  471. // ensure that the name exposed in the action bar is the current directory when the
  472. // user selected it in the navigation list
  473. if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
  474. getSupportActionBar().setSelectedNavigationItem(0);
  475. }
  476. return true;
  477. }
  478. /**
  479. * Called, when the user selected something for uploading
  480. */
  481. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  482. super.onActivityResult(requestCode, resultCode, data);
  483. if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  484. requestSimpleUpload(data, resultCode);
  485. } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  486. requestMultipleUpload(data, resultCode);
  487. } else if (requestCode == ACTION_MOVE_FILES && (resultCode == RESULT_OK ||
  488. resultCode == MoveActivity.RESULT_OK_AND_MOVE)){
  489. final Intent fData = data;
  490. final int fResultCode = resultCode;
  491. getHandler().postDelayed(
  492. new Runnable() {
  493. @Override
  494. public void run() {
  495. requestMoveOperation(fData, fResultCode);
  496. }
  497. },
  498. DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
  499. );
  500. }
  501. }
  502. private void requestMultipleUpload(Intent data, int resultCode) {
  503. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  504. if (filePaths != null) {
  505. String[] remotePaths = new String[filePaths.length];
  506. String remotePathBase = "";
  507. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  508. remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  509. }
  510. if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
  511. remotePathBase += OCFile.PATH_SEPARATOR;
  512. for (int j = 0; j< remotePaths.length; j++) {
  513. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  514. }
  515. Intent i = new Intent(this, FileUploader.class);
  516. i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
  517. i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
  518. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
  519. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
  520. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  521. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  522. startService(i);
  523. } else {
  524. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  525. Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
  526. t.show();
  527. return;
  528. }
  529. }
  530. private void requestSimpleUpload(Intent data, int resultCode) {
  531. String filepath = null;
  532. try {
  533. Uri selectedImageUri = data.getData();
  534. String filemanagerstring = selectedImageUri.getPath();
  535. String selectedImagePath = getPath(selectedImageUri);
  536. if (selectedImagePath != null)
  537. filepath = selectedImagePath;
  538. else
  539. filepath = filemanagerstring;
  540. } catch (Exception e) {
  541. Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
  542. e.printStackTrace();
  543. } finally {
  544. if (filepath == null) {
  545. Log_OC.e(TAG, "Couldnt resolve path to file");
  546. Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
  547. t.show();
  548. return;
  549. }
  550. }
  551. Intent i = new Intent(this, FileUploader.class);
  552. i.putExtra(FileUploader.KEY_ACCOUNT,
  553. getAccount());
  554. String remotepath = new String();
  555. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  556. remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  557. }
  558. if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
  559. remotepath += OCFile.PATH_SEPARATOR;
  560. remotepath += new File(filepath).getName();
  561. i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
  562. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
  563. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
  564. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  565. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  566. startService(i);
  567. }
  568. /**
  569. * Request the operation for moving the file/folder from one path to another
  570. *
  571. * @param data Intent received
  572. * @param resultCode Result code received
  573. */
  574. private void requestMoveOperation(Intent data, int resultCode) {
  575. OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_CURRENT_FOLDER);
  576. OCFile targetFile = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_TARGET_FILE);
  577. getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
  578. }
  579. @Override
  580. public void onBackPressed() {
  581. OCFileListFragment listOfFiles = getListOfFilesFragment();
  582. if (mDualPane || getSecondFragment() == null) {
  583. if (listOfFiles != null) { // should never be null, indeed
  584. if (mDirectories.getCount() <= 1) {
  585. finish();
  586. return;
  587. }
  588. int levelsUp = listOfFiles.onBrowseUp();
  589. for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
  590. popDirname();
  591. }
  592. }
  593. }
  594. if (listOfFiles != null) { // should never be null, indeed
  595. setFile(listOfFiles.getCurrentFile());
  596. }
  597. cleanSecondFragment();
  598. }
  599. @Override
  600. protected void onSaveInstanceState(Bundle outState) {
  601. // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
  602. Log_OC.e(TAG, "onSaveInstanceState() start");
  603. super.onSaveInstanceState(outState);
  604. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  605. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  606. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
  607. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  608. Log_OC.d(TAG, "onSaveInstanceState() end");
  609. }
  610. @Override
  611. protected void onResume() {
  612. super.onResume();
  613. Log_OC.e(TAG, "onResume() start");
  614. // refresh list of files
  615. refreshListOfFilesFragment();
  616. // Listen for sync messages
  617. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  618. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  619. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  620. syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  621. syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  622. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  623. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  624. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  625. // Listen for upload messages
  626. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  627. mUploadFinishReceiver = new UploadFinishReceiver();
  628. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  629. // Listen for download messages
  630. IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
  631. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  632. mDownloadFinishReceiver = new DownloadFinishReceiver();
  633. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  634. Log_OC.d(TAG, "onResume() end");
  635. }
  636. @Override
  637. protected void onPause() {
  638. Log_OC.e(TAG, "onPause() start");
  639. if (mSyncBroadcastReceiver != null) {
  640. unregisterReceiver(mSyncBroadcastReceiver);
  641. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  642. mSyncBroadcastReceiver = null;
  643. }
  644. if (mUploadFinishReceiver != null) {
  645. unregisterReceiver(mUploadFinishReceiver);
  646. mUploadFinishReceiver = null;
  647. }
  648. if (mDownloadFinishReceiver != null) {
  649. unregisterReceiver(mDownloadFinishReceiver);
  650. mDownloadFinishReceiver = null;
  651. }
  652. Log_OC.d(TAG, "onPause() end");
  653. super.onPause();
  654. }
  655. @Override
  656. protected Dialog onCreateDialog(int id) {
  657. Dialog dialog = null;
  658. AlertDialog.Builder builder;
  659. switch (id) {
  660. case DIALOG_SHORT_WAIT: {
  661. ProgressDialog working_dialog = new ProgressDialog(this);
  662. working_dialog.setMessage(getResources().getString(
  663. R.string.wait_a_moment));
  664. working_dialog.setIndeterminate(true);
  665. working_dialog.setCancelable(false);
  666. dialog = working_dialog;
  667. break;
  668. }
  669. case DIALOG_CHOOSE_UPLOAD_SOURCE: {
  670. String[] allTheItems = { getString(R.string.actionbar_upload_files),
  671. getString(R.string.actionbar_upload_from_apps) };
  672. builder = new AlertDialog.Builder(this);
  673. builder.setTitle(R.string.actionbar_upload);
  674. builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
  675. public void onClick(DialogInterface dialog, int item) {
  676. if (item == 0) {
  677. // if (!mDualPane) {
  678. Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
  679. action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
  680. startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
  681. // } else {
  682. // TODO create and handle new fragment
  683. // LocalFileListFragment
  684. // }
  685. } else if (item == 1) {
  686. Intent action = new Intent(Intent.ACTION_GET_CONTENT);
  687. action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
  688. startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
  689. ACTION_SELECT_CONTENT_FROM_APPS);
  690. }
  691. }
  692. });
  693. dialog = builder.create();
  694. break;
  695. }
  696. case DIALOG_CERT_NOT_SAVED: {
  697. builder = new AlertDialog.Builder(this);
  698. builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
  699. builder.setCancelable(false);
  700. builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
  701. @Override
  702. public void onClick(DialogInterface dialog, int which) {
  703. dialog.dismiss();
  704. };
  705. });
  706. dialog = builder.create();
  707. break;
  708. }
  709. default:
  710. dialog = null;
  711. }
  712. return dialog;
  713. }
  714. /**
  715. * Translates a content URI of an image to a physical path
  716. * on the disk
  717. * @param uri The URI to resolve
  718. * @return The path to the image or null if it could not be found
  719. */
  720. public String getPath(Uri uri) {
  721. String[] projection = { MediaStore.Images.Media.DATA };
  722. Cursor cursor = managedQuery(uri, projection, null, null, null);
  723. if (cursor != null) {
  724. int column_index = cursor
  725. .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  726. cursor.moveToFirst();
  727. return cursor.getString(column_index);
  728. }
  729. return null;
  730. }
  731. /**
  732. * Pushes a directory to the drop down list
  733. * @param directory to push
  734. * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
  735. */
  736. public void pushDirname(OCFile directory) {
  737. if(!directory.isFolder()){
  738. throw new IllegalArgumentException("Only directories may be pushed!");
  739. }
  740. mDirectories.insert(directory.getFileName(), 0);
  741. setFile(directory);
  742. }
  743. /**
  744. * Pops a directory name from the drop down list
  745. * @return True, unless the stack is empty
  746. */
  747. public boolean popDirname() {
  748. mDirectories.remove(mDirectories.getItem(0));
  749. return !mDirectories.isEmpty();
  750. }
  751. // Custom array adapter to override text colors
  752. private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
  753. public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
  754. super(ctx, view);
  755. }
  756. public View getView(int position, View convertView, ViewGroup parent) {
  757. View v = super.getView(position, convertView, parent);
  758. ((TextView) v).setTextColor(getResources().getColorStateList(
  759. android.R.color.white));
  760. fixRoot((TextView) v );
  761. return v;
  762. }
  763. public View getDropDownView(int position, View convertView,
  764. ViewGroup parent) {
  765. View v = super.getDropDownView(position, convertView, parent);
  766. ((TextView) v).setTextColor(getResources().getColorStateList(
  767. android.R.color.white));
  768. fixRoot((TextView) v );
  769. return v;
  770. }
  771. private void fixRoot(TextView v) {
  772. if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
  773. v.setText(R.string.default_display_name_for_root_folder);
  774. }
  775. }
  776. }
  777. private class SyncBroadcastReceiver extends BroadcastReceiver {
  778. /**
  779. * {@link BroadcastReceiver} to enable syncing feedback in UI
  780. */
  781. @Override
  782. public void onReceive(Context context, Intent intent) {
  783. try {
  784. String event = intent.getAction();
  785. Log_OC.d(TAG, "Received broadcast " + event);
  786. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  787. String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  788. RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
  789. boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
  790. if (sameAccount) {
  791. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  792. mSyncInProgress = true;
  793. } else {
  794. OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
  795. OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  796. if (currentDir == null) {
  797. // current folder was removed from the server
  798. Toast.makeText( FileDisplayActivity.this,
  799. String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
  800. Toast.LENGTH_LONG)
  801. .show();
  802. browseToRoot();
  803. } else {
  804. if (currentFile == null && !getFile().isFolder()) {
  805. // currently selected file was removed in the server, and now we know it
  806. cleanSecondFragment();
  807. currentFile = currentDir;
  808. }
  809. if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  810. OCFileListFragment fileListFragment = getListOfFilesFragment();
  811. if (fileListFragment != null) {
  812. fileListFragment.listDirectory(currentDir);
  813. }
  814. }
  815. setFile(currentFile);
  816. }
  817. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
  818. if (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
  819. equals(event) &&
  820. /// TODO refactor and make common
  821. synchResult != null && !synchResult.isSuccess() &&
  822. (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
  823. synchResult.isIdPRedirection() ||
  824. (synchResult.isException() && synchResult.getException()
  825. instanceof AuthenticatorException))) {
  826. OwnCloudClient client = null;
  827. try {
  828. OwnCloudAccount ocAccount =
  829. new OwnCloudAccount(getAccount(), context);
  830. client = (OwnCloudClientManagerFactory.getDefaultSingleton().
  831. removeClientFor(ocAccount));
  832. // TODO get rid of these exceptions
  833. } catch (AccountNotFoundException e) {
  834. e.printStackTrace();
  835. } catch (AuthenticatorException e) {
  836. e.printStackTrace();
  837. } catch (OperationCanceledException e) {
  838. e.printStackTrace();
  839. } catch (IOException e) {
  840. e.printStackTrace();
  841. }
  842. if (client != null) {
  843. OwnCloudCredentials cred = client.getCredentials();
  844. if (cred != null) {
  845. AccountManager am = AccountManager.get(context);
  846. if (cred.authTokenExpires()) {
  847. am.invalidateAuthToken(
  848. getAccount().type,
  849. cred.getAuthToken()
  850. );
  851. } else {
  852. am.clearPassword(getAccount());
  853. }
  854. }
  855. }
  856. requestCredentialsUpdate();
  857. }
  858. }
  859. removeStickyBroadcast(intent);
  860. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  861. setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
  862. setBackgroundText();
  863. }
  864. if (synchResult != null) {
  865. if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  866. mLastSslUntrustedServerResult = synchResult;
  867. }
  868. }
  869. } catch (RuntimeException e) {
  870. // avoid app crashes after changing the serial id of RemoteOperationResult
  871. // in owncloud library with broadcast notifications pending to process
  872. removeStickyBroadcast(intent);
  873. }
  874. }
  875. }
  876. /**
  877. * Show a text message on screen view for notifying user if content is
  878. * loading or folder is empty
  879. */
  880. private void setBackgroundText() {
  881. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  882. if (ocFileListFragment != null) {
  883. int message = R.string.file_list_loading;
  884. if (!mSyncInProgress) {
  885. // In case file list is empty
  886. message = R.string.file_list_empty;
  887. }
  888. ocFileListFragment.setMessageForEmptyList(getString(message));
  889. } else {
  890. Log.e(TAG, "OCFileListFragment is null");
  891. }
  892. }
  893. /**
  894. * Once the file upload has finished -> update view
  895. */
  896. private class UploadFinishReceiver extends BroadcastReceiver {
  897. /**
  898. * Once the file upload has finished -> update view
  899. * @author David A. Velasco
  900. * {@link BroadcastReceiver} to enable upload feedback in UI
  901. */
  902. @Override
  903. public void onReceive(Context context, Intent intent) {
  904. try {
  905. String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  906. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  907. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  908. OCFile currentDir = getCurrentDir();
  909. boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
  910. (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
  911. if (sameAccount && isDescendant) {
  912. refreshListOfFilesFragment();
  913. }
  914. boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
  915. boolean renamedInUpload = getFile().getRemotePath().
  916. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  917. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  918. renamedInUpload;
  919. FileFragment details = getSecondFragment();
  920. boolean detailFragmentIsShown = (details != null &&
  921. details instanceof FileDetailFragment);
  922. if (sameAccount && sameFile && detailFragmentIsShown) {
  923. if (uploadWasFine) {
  924. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  925. }
  926. if (renamedInUpload) {
  927. String newName = (new File(uploadedRemotePath)).getName();
  928. Toast msg = Toast.makeText(
  929. context,
  930. String.format(
  931. getString(R.string.filedetails_renamed_in_upload_msg),
  932. newName),
  933. Toast.LENGTH_LONG);
  934. msg.show();
  935. }
  936. if (uploadWasFine || getFile().fileExists()) {
  937. ((FileDetailFragment)details).updateFileDetails(false, true);
  938. } else {
  939. cleanSecondFragment();
  940. }
  941. // Force the preview if the file is an image
  942. if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
  943. startImagePreview(getFile());
  944. } // TODO what about other kind of previews?
  945. }
  946. } finally {
  947. if (intent != null) {
  948. removeStickyBroadcast(intent);
  949. }
  950. }
  951. }
  952. }
  953. /**
  954. * Class waiting for broadcast events from the {@link FielDownloader} service.
  955. *
  956. * Updates the UI when a download is started or finished, provided that it is relevant for the
  957. * current folder.
  958. */
  959. private class DownloadFinishReceiver extends BroadcastReceiver {
  960. @Override
  961. public void onReceive(Context context, Intent intent) {
  962. try {
  963. boolean sameAccount = isSameAccount(context, intent);
  964. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  965. boolean isDescendant = isDescendant(downloadedRemotePath);
  966. if (sameAccount && isDescendant) {
  967. refreshListOfFilesFragment();
  968. refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
  969. }
  970. if (mWaitingToSend != null) {
  971. mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
  972. if (mWaitingToSend.isDown()) {
  973. sendDownloadedFile();
  974. }
  975. }
  976. } finally {
  977. if (intent != null) {
  978. removeStickyBroadcast(intent);
  979. }
  980. }
  981. }
  982. private boolean isDescendant(String downloadedRemotePath) {
  983. OCFile currentDir = getCurrentDir();
  984. return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
  985. }
  986. private boolean isSameAccount(Context context, Intent intent) {
  987. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  988. return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
  989. }
  990. }
  991. public void browseToRoot() {
  992. OCFileListFragment listOfFiles = getListOfFilesFragment();
  993. if (listOfFiles != null) { // should never be null, indeed
  994. while (mDirectories.getCount() > 1) {
  995. popDirname();
  996. }
  997. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  998. listOfFiles.listDirectory(root);
  999. setFile(listOfFiles.getCurrentFile());
  1000. startSyncFolderOperation(root, false);
  1001. }
  1002. cleanSecondFragment();
  1003. }
  1004. public void browseTo(OCFile folder) {
  1005. if (folder == null || !folder.isFolder()) {
  1006. throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
  1007. }
  1008. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1009. if (listOfFiles != null) {
  1010. setNavigationListWithFolder(folder);
  1011. listOfFiles.listDirectory(folder);
  1012. setFile(listOfFiles.getCurrentFile());
  1013. startSyncFolderOperation(folder, false);
  1014. } else {
  1015. Log_OC.e(TAG, "Unexpected null when accessing list fragment");
  1016. }
  1017. cleanSecondFragment();
  1018. }
  1019. /**
  1020. * {@inheritDoc}
  1021. *
  1022. * Updates action bar and second fragment, if in dual pane mode.
  1023. */
  1024. @Override
  1025. public void onBrowsedDownTo(OCFile directory) {
  1026. pushDirname(directory);
  1027. cleanSecondFragment();
  1028. // Sync Folder
  1029. startSyncFolderOperation(directory, false);
  1030. }
  1031. /**
  1032. * Shows the information of the {@link OCFile} received as a
  1033. * parameter in the second fragment.
  1034. *
  1035. * @param file {@link OCFile} whose details will be shown
  1036. */
  1037. @Override
  1038. public void showDetails(OCFile file) {
  1039. Fragment detailFragment = new FileDetailFragment(file, getAccount());
  1040. setSecondFragment(detailFragment);
  1041. updateFragmentsVisibility(true);
  1042. updateNavigationElementsInActionBar(file);
  1043. setFile(file);
  1044. }
  1045. /**
  1046. * TODO
  1047. */
  1048. private void updateNavigationElementsInActionBar(OCFile chosenFile) {
  1049. ActionBar actionBar = getSupportActionBar();
  1050. if (chosenFile == null || mDualPane) {
  1051. // only list of files - set for browsing through folders
  1052. OCFile currentDir = getCurrentDir();
  1053. boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
  1054. actionBar.setDisplayHomeAsUpEnabled(noRoot);
  1055. actionBar.setDisplayShowTitleEnabled(!noRoot);
  1056. if (!noRoot) {
  1057. actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
  1058. }
  1059. actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
  1060. actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
  1061. } else {
  1062. actionBar.setDisplayHomeAsUpEnabled(true);
  1063. actionBar.setDisplayShowTitleEnabled(true);
  1064. actionBar.setTitle(chosenFile.getFileName());
  1065. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
  1066. }
  1067. }
  1068. @Override
  1069. protected ServiceConnection newTransferenceServiceConnection() {
  1070. return new ListServiceConnection();
  1071. }
  1072. /** Defines callbacks for service binding, passed to bindService() */
  1073. private class ListServiceConnection implements ServiceConnection {
  1074. @Override
  1075. public void onServiceConnected(ComponentName component, IBinder service) {
  1076. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1077. Log_OC.d(TAG, "Download service connected");
  1078. mDownloaderBinder = (FileDownloaderBinder) service;
  1079. if (mWaitingToPreview != null)
  1080. if (getStorageManager() != null) {
  1081. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
  1082. if (!mWaitingToPreview.isDown()) {
  1083. requestForDownload();
  1084. }
  1085. }
  1086. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1087. Log_OC.d(TAG, "Upload service connected");
  1088. mUploaderBinder = (FileUploaderBinder) service;
  1089. } else {
  1090. return;
  1091. }
  1092. // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
  1093. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1094. if (listOfFiles != null) {
  1095. listOfFiles.listDirectory();
  1096. }
  1097. FileFragment secondFragment = getSecondFragment();
  1098. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  1099. FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
  1100. detailFragment.listenForTransferProgress();
  1101. detailFragment.updateFileDetails(false, false);
  1102. }
  1103. }
  1104. @Override
  1105. public void onServiceDisconnected(ComponentName component) {
  1106. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1107. Log_OC.d(TAG, "Download service disconnected");
  1108. mDownloaderBinder = null;
  1109. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1110. Log_OC.d(TAG, "Upload service disconnected");
  1111. mUploaderBinder = null;
  1112. }
  1113. }
  1114. };
  1115. /**
  1116. * Launch an intent to request the PIN code to the user before letting him use the app
  1117. */
  1118. private void requestPinCode() {
  1119. boolean pinStart = false;
  1120. SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  1121. pinStart = appPrefs.getBoolean("set_pincode", false);
  1122. if (pinStart) {
  1123. Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
  1124. i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
  1125. startActivity(i);
  1126. }
  1127. }
  1128. @Override
  1129. public void onSavedCertificate() {
  1130. startSyncFolderOperation(getCurrentDir(), false);
  1131. }
  1132. @Override
  1133. public void onFailedSavingCertificate() {
  1134. showDialog(DIALOG_CERT_NOT_SAVED);
  1135. }
  1136. @Override
  1137. public void onCancelCertificate() {
  1138. // nothing to do
  1139. }
  1140. /**
  1141. * Updates the view associated to the activity after the finish of some operation over files
  1142. * in the current account.
  1143. *
  1144. * @param operation Removal operation performed.
  1145. * @param result Result of the removal.
  1146. */
  1147. @Override
  1148. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1149. super.onRemoteOperationFinish(operation, result);
  1150. if (operation instanceof RemoveFileOperation) {
  1151. onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
  1152. } else if (operation instanceof RenameFileOperation) {
  1153. onRenameFileOperationFinish((RenameFileOperation)operation, result);
  1154. } else if (operation instanceof SynchronizeFileOperation) {
  1155. onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
  1156. } else if (operation instanceof CreateFolderOperation) {
  1157. onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
  1158. } else if (operation instanceof CreateShareOperation) {
  1159. onCreateShareOperationFinish((CreateShareOperation) operation, result);
  1160. } else if (operation instanceof UnshareLinkOperation) {
  1161. onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
  1162. } else if (operation instanceof MoveFileOperation) {
  1163. onMoveFileOperationFinish((MoveFileOperation)operation, result);
  1164. }
  1165. }
  1166. private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
  1167. if (result.isSuccess()) {
  1168. refreshShowDetails();
  1169. refreshListOfFilesFragment();
  1170. }
  1171. }
  1172. private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
  1173. if (result.isSuccess()) {
  1174. refreshShowDetails();
  1175. refreshListOfFilesFragment();
  1176. } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
  1177. cleanSecondFragment();
  1178. refreshListOfFilesFragment();
  1179. }
  1180. }
  1181. private void refreshShowDetails() {
  1182. FileFragment details = getSecondFragment();
  1183. if (details != null) {
  1184. OCFile file = details.getFile();
  1185. if (file != null) {
  1186. file = getStorageManager().getFileByPath(file.getRemotePath());
  1187. if (details instanceof PreviewMediaFragment) {
  1188. // Refresh OCFile of the fragment
  1189. ((PreviewMediaFragment) details).updateFile(file);
  1190. } else {
  1191. showDetails(file);
  1192. }
  1193. }
  1194. invalidateOptionsMenu();
  1195. }
  1196. }
  1197. /**
  1198. * Updates the view associated to the activity after the finish of an operation trying to remove a
  1199. * file.
  1200. *
  1201. * @param operation Removal operation performed.
  1202. * @param result Result of the removal.
  1203. */
  1204. private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
  1205. dismissLoadingDialog();
  1206. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1207. Toast.LENGTH_LONG);
  1208. msg.show();
  1209. if (result.isSuccess()) {
  1210. OCFile removedFile = operation.getFile();
  1211. FileFragment second = getSecondFragment();
  1212. if (second != null && removedFile.equals(second.getFile())) {
  1213. if (second instanceof PreviewMediaFragment) {
  1214. ((PreviewMediaFragment)second).stopPreview(true);
  1215. }
  1216. setFile(getStorageManager().getFileById(removedFile.getParentId()));
  1217. cleanSecondFragment();
  1218. }
  1219. if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
  1220. refreshListOfFilesFragment();
  1221. }
  1222. invalidateOptionsMenu();
  1223. } else {
  1224. if (result.isSslRecoverableException()) {
  1225. mLastSslUntrustedServerResult = result;
  1226. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1227. }
  1228. }
  1229. }
  1230. /**
  1231. * Updates the view associated to the activity after the finish of an operation trying to move a
  1232. * file.
  1233. *
  1234. * @param operation Move operation performed.
  1235. * @param result Result of the move operation.
  1236. */
  1237. private void onMoveFileOperationFinish(MoveFileOperation operation, RemoteOperationResult result) {
  1238. if (result.isSuccess()) {
  1239. dismissLoadingDialog();
  1240. refreshListOfFilesFragment();
  1241. } else {
  1242. dismissLoadingDialog();
  1243. try {
  1244. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1245. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1246. Toast.LENGTH_LONG);
  1247. msg.show();
  1248. } catch (NotFoundException e) {
  1249. Log_OC.e(TAG, "Error while trying to show fail message " , e);
  1250. }
  1251. }
  1252. }
  1253. /**
  1254. * Updates the view associated to the activity after the finish of an operation trying to rename a
  1255. * file.
  1256. *
  1257. * @param operation Renaming operation performed.
  1258. * @param result Result of the renaming.
  1259. */
  1260. private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
  1261. dismissLoadingDialog();
  1262. OCFile renamedFile = operation.getFile();
  1263. if (result.isSuccess()) {
  1264. FileFragment details = getSecondFragment();
  1265. if (details != null) {
  1266. if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
  1267. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1268. showDetails(renamedFile);
  1269. } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
  1270. ((PreviewMediaFragment) details).updateFile(renamedFile);
  1271. if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
  1272. int position = ((PreviewMediaFragment)details).getPosition();
  1273. startMediaPreview(renamedFile, position, true);
  1274. } else {
  1275. getFileOperationsHelper().openFile(renamedFile);
  1276. }
  1277. }
  1278. }
  1279. if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
  1280. refreshListOfFilesFragment();
  1281. }
  1282. } else {
  1283. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1284. Toast.LENGTH_LONG);
  1285. msg.show();
  1286. if (result.isSslRecoverableException()) {
  1287. mLastSslUntrustedServerResult = result;
  1288. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1289. }
  1290. }
  1291. }
  1292. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
  1293. dismissLoadingDialog();
  1294. OCFile syncedFile = operation.getLocalFile();
  1295. if (!result.isSuccess()) {
  1296. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  1297. Intent i = new Intent(this, ConflictsResolveActivity.class);
  1298. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
  1299. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
  1300. startActivity(i);
  1301. }
  1302. } else {
  1303. if (operation.transferWasRequested()) {
  1304. onTransferStateChanged(syncedFile, true, true);
  1305. } else {
  1306. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1307. Toast.LENGTH_LONG);
  1308. msg.show();
  1309. }
  1310. }
  1311. }
  1312. /**
  1313. * Updates the view associated to the activity after the finish of an operation trying create a new folder
  1314. *
  1315. * @param operation Creation operation performed.
  1316. * @param result Result of the creation.
  1317. */
  1318. private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
  1319. if (result.isSuccess()) {
  1320. dismissLoadingDialog();
  1321. refreshListOfFilesFragment();
  1322. } else {
  1323. dismissLoadingDialog();
  1324. try {
  1325. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1326. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1327. Toast.LENGTH_LONG);
  1328. msg.show();
  1329. } catch (NotFoundException e) {
  1330. Log_OC.e(TAG, "Error while trying to show fail message " , e);
  1331. }
  1332. }
  1333. }
  1334. /**
  1335. * {@inheritDoc}
  1336. */
  1337. @Override
  1338. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1339. refreshListOfFilesFragment();
  1340. FileFragment details = getSecondFragment();
  1341. if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
  1342. if (downloading || uploading) {
  1343. ((FileDetailFragment)details).updateFileDetails(file, getAccount());
  1344. } else {
  1345. if (!file.fileExists()) {
  1346. cleanSecondFragment();
  1347. } else {
  1348. ((FileDetailFragment)details).updateFileDetails(false, true);
  1349. }
  1350. }
  1351. }
  1352. }
  1353. private void requestForDownload() {
  1354. Account account = getAccount();
  1355. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1356. Intent i = new Intent(this, FileDownloader.class);
  1357. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1358. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1359. startService(i);
  1360. }
  1361. }
  1362. private OCFile getCurrentDir() {
  1363. OCFile file = getFile();
  1364. if (file != null) {
  1365. if (file.isFolder()) {
  1366. return file;
  1367. } else if (getStorageManager() != null) {
  1368. String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
  1369. return getStorageManager().getFileByPath(parentPath);
  1370. }
  1371. }
  1372. return null;
  1373. }
  1374. public void startSyncFolderOperation(OCFile folder, boolean ignoreTag) {
  1375. long currentSyncTime = System.currentTimeMillis();
  1376. mSyncInProgress = true;
  1377. // perform folder synchronization
  1378. RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
  1379. currentSyncTime,
  1380. false,
  1381. getFileOperationsHelper().isSharedSupported(),
  1382. ignoreTag,
  1383. getStorageManager(),
  1384. getAccount(),
  1385. getApplicationContext()
  1386. );
  1387. synchFolderOp.execute(getAccount(), this, null, null);
  1388. setSupportProgressBarIndeterminateVisibility(true);
  1389. setBackgroundText();
  1390. }
  1391. /**
  1392. * Show untrusted cert dialog
  1393. */
  1394. public void showUntrustedCertDialog(RemoteOperationResult result) {
  1395. // Show a dialog with the certificate info
  1396. SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
  1397. FragmentManager fm = getSupportFragmentManager();
  1398. FragmentTransaction ft = fm.beginTransaction();
  1399. dialog.show(ft, DIALOG_UNTRUSTED_CERT);
  1400. }
  1401. private void requestForDownload(OCFile file) {
  1402. Account account = getAccount();
  1403. if (!mDownloaderBinder.isDownloading(account, file)) {
  1404. Intent i = new Intent(this, FileDownloader.class);
  1405. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1406. i.putExtra(FileDownloader.EXTRA_FILE, file);
  1407. startService(i);
  1408. }
  1409. }
  1410. private void sendDownloadedFile(){
  1411. getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
  1412. mWaitingToSend = null;
  1413. }
  1414. /**
  1415. * Requests the download of the received {@link OCFile} , updates the UI
  1416. * to monitor the download progress and prepares the activity to send the file
  1417. * when the download finishes.
  1418. *
  1419. * @param file {@link OCFile} to download and preview.
  1420. */
  1421. public void startDownloadForSending(OCFile file) {
  1422. mWaitingToSend = file;
  1423. requestForDownload(mWaitingToSend);
  1424. boolean hasSecondFragment = (getSecondFragment()!= null);
  1425. updateFragmentsVisibility(hasSecondFragment);
  1426. }
  1427. /**
  1428. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1429. *
  1430. * @param file Image {@link OCFile} to show.
  1431. */
  1432. public void startImagePreview(OCFile file) {
  1433. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1434. showDetailsIntent.putExtra(EXTRA_FILE, file);
  1435. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1436. startActivity(showDetailsIntent);
  1437. }
  1438. /**
  1439. * Stars the preview of an already down media {@link OCFile}.
  1440. *
  1441. * @param file Media {@link OCFile} to preview.
  1442. * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
  1443. * @param autoplay When 'true', the playback will start without user interactions.
  1444. */
  1445. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
  1446. Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
  1447. setSecondFragment(mediaFragment);
  1448. updateFragmentsVisibility(true);
  1449. updateNavigationElementsInActionBar(file);
  1450. setFile(file);
  1451. }
  1452. /**
  1453. * Requests the download of the received {@link OCFile} , updates the UI
  1454. * to monitor the download progress and prepares the activity to preview
  1455. * or open the file when the download finishes.
  1456. *
  1457. * @param file {@link OCFile} to download and preview.
  1458. */
  1459. public void startDownloadForPreview(OCFile file) {
  1460. Fragment detailFragment = new FileDetailFragment(file, getAccount());
  1461. setSecondFragment(detailFragment);
  1462. mWaitingToPreview = file;
  1463. requestForDownload();
  1464. updateFragmentsVisibility(true);
  1465. updateNavigationElementsInActionBar(file);
  1466. setFile(file);
  1467. }
  1468. public void cancelTransference(OCFile file) {
  1469. getFileOperationsHelper().cancelTransference(file);
  1470. if (mWaitingToPreview != null &&
  1471. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  1472. mWaitingToPreview = null;
  1473. }
  1474. if (mWaitingToSend != null &&
  1475. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  1476. mWaitingToSend = null;
  1477. }
  1478. onTransferStateChanged(file, false, false);
  1479. }
  1480. @Override
  1481. public void onRefresh() {
  1482. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1483. if (listOfFiles != null) {
  1484. OCFile folder = listOfFiles.getCurrentFile();
  1485. if (folder != null) {
  1486. /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
  1487. listDirectory(mFile);*/
  1488. startSyncFolderOperation(folder, true);
  1489. }
  1490. }
  1491. }
  1492. }