FileDisplayActivity.java 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775
  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);
  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. case R.id.action_sort: {
  431. SharedPreferences appPreferences = PreferenceManager
  432. .getDefaultSharedPreferences(getApplicationContext());
  433. // Read sorting order, default to sort by name ascending
  434. Integer sortOrder = appPreferences
  435. .getInt("sortOrder", 0);
  436. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  437. builder.setTitle(R.string.actionbar_sort_title)
  438. .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder , new DialogInterface.OnClickListener() {
  439. public void onClick(DialogInterface dialog, int which) {
  440. switch (which){
  441. case 0:
  442. sortByName(true);
  443. break;
  444. case 1:
  445. sortByDate(false);
  446. break;
  447. // TODO re-enable when server-side folder size calculation is available
  448. // case 2:
  449. // sortBySize(false);
  450. // break;
  451. }
  452. dialog.dismiss();
  453. }
  454. });
  455. builder.create().show();
  456. break;
  457. }
  458. default:
  459. retval = super.onOptionsItemSelected(item);
  460. }
  461. return retval;
  462. }
  463. private void startSynchronization() {
  464. Log_OC.e(TAG, "Got to start sync");
  465. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  466. Log_OC.e(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  467. ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
  468. Bundle bundle = new Bundle();
  469. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  470. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  471. Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
  472. ContentResolver.requestSync(
  473. getAccount(),
  474. MainApp.getAuthority(), bundle);
  475. } else {
  476. Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
  477. SyncRequest.Builder builder = new SyncRequest.Builder();
  478. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  479. builder.setExpedited(true);
  480. builder.setManual(true);
  481. builder.syncOnce();
  482. SyncRequest request = builder.build();
  483. ContentResolver.requestSync(request);
  484. }
  485. }
  486. @Override
  487. public boolean onNavigationItemSelected(int itemPosition, long itemId) {
  488. if (itemPosition != 0) {
  489. String targetPath = "";
  490. for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
  491. targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
  492. }
  493. targetPath = OCFile.PATH_SEPARATOR + targetPath;
  494. OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
  495. if (targetFolder != null) {
  496. browseTo(targetFolder);
  497. }
  498. // the next operation triggers a new call to this method, but it's necessary to
  499. // ensure that the name exposed in the action bar is the current directory when the
  500. // user selected it in the navigation list
  501. if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
  502. getSupportActionBar().setSelectedNavigationItem(0);
  503. }
  504. return true;
  505. }
  506. /**
  507. * Called, when the user selected something for uploading
  508. */
  509. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  510. super.onActivityResult(requestCode, resultCode, data);
  511. if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  512. requestSimpleUpload(data, resultCode);
  513. } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  514. requestMultipleUpload(data, resultCode);
  515. } else if (requestCode == ACTION_MOVE_FILES && (resultCode == RESULT_OK ||
  516. resultCode == MoveActivity.RESULT_OK_AND_MOVE)){
  517. final Intent fData = data;
  518. final int fResultCode = resultCode;
  519. getHandler().postDelayed(
  520. new Runnable() {
  521. @Override
  522. public void run() {
  523. requestMoveOperation(fData, fResultCode);
  524. }
  525. },
  526. DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
  527. );
  528. }
  529. }
  530. private void requestMultipleUpload(Intent data, int resultCode) {
  531. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  532. if (filePaths != null) {
  533. String[] remotePaths = new String[filePaths.length];
  534. String remotePathBase = "";
  535. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  536. remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  537. }
  538. if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
  539. remotePathBase += OCFile.PATH_SEPARATOR;
  540. for (int j = 0; j< remotePaths.length; j++) {
  541. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  542. }
  543. Intent i = new Intent(this, FileUploader.class);
  544. i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
  545. i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
  546. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
  547. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
  548. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  549. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  550. startService(i);
  551. } else {
  552. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  553. Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
  554. t.show();
  555. return;
  556. }
  557. }
  558. private void requestSimpleUpload(Intent data, int resultCode) {
  559. String filepath = null;
  560. try {
  561. Uri selectedImageUri = data.getData();
  562. String filemanagerstring = selectedImageUri.getPath();
  563. String selectedImagePath = getPath(selectedImageUri);
  564. if (selectedImagePath != null)
  565. filepath = selectedImagePath;
  566. else
  567. filepath = filemanagerstring;
  568. } catch (Exception e) {
  569. Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
  570. e.printStackTrace();
  571. } finally {
  572. if (filepath == null) {
  573. Log_OC.e(TAG, "Couldnt resolve path to file");
  574. Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
  575. t.show();
  576. return;
  577. }
  578. }
  579. Intent i = new Intent(this, FileUploader.class);
  580. i.putExtra(FileUploader.KEY_ACCOUNT,
  581. getAccount());
  582. String remotepath = new String();
  583. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  584. remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  585. }
  586. if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
  587. remotepath += OCFile.PATH_SEPARATOR;
  588. remotepath += new File(filepath).getName();
  589. i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
  590. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
  591. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
  592. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  593. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  594. startService(i);
  595. }
  596. /**
  597. * Request the operation for moving the file/folder from one path to another
  598. *
  599. * @param data Intent received
  600. * @param resultCode Result code received
  601. */
  602. private void requestMoveOperation(Intent data, int resultCode) {
  603. OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_CURRENT_FOLDER);
  604. OCFile targetFile = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_TARGET_FILE);
  605. getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
  606. }
  607. @Override
  608. public void onBackPressed() {
  609. OCFileListFragment listOfFiles = getListOfFilesFragment();
  610. if (mDualPane || getSecondFragment() == null) {
  611. if (listOfFiles != null) { // should never be null, indeed
  612. if (mDirectories.getCount() <= 1) {
  613. finish();
  614. return;
  615. }
  616. int levelsUp = listOfFiles.onBrowseUp();
  617. for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
  618. popDirname();
  619. }
  620. }
  621. }
  622. if (listOfFiles != null) { // should never be null, indeed
  623. setFile(listOfFiles.getCurrentFile());
  624. }
  625. cleanSecondFragment();
  626. }
  627. @Override
  628. protected void onSaveInstanceState(Bundle outState) {
  629. // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
  630. Log_OC.e(TAG, "onSaveInstanceState() start");
  631. super.onSaveInstanceState(outState);
  632. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  633. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  634. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
  635. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  636. Log_OC.d(TAG, "onSaveInstanceState() end");
  637. }
  638. @Override
  639. protected void onResume() {
  640. super.onResume();
  641. Log_OC.e(TAG, "onResume() start");
  642. // refresh list of files
  643. refreshListOfFilesFragment();
  644. // Listen for sync messages
  645. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  646. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  647. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  648. syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  649. syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  650. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  651. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  652. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  653. // Listen for upload messages
  654. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  655. mUploadFinishReceiver = new UploadFinishReceiver();
  656. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  657. // Listen for download messages
  658. IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
  659. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  660. mDownloadFinishReceiver = new DownloadFinishReceiver();
  661. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  662. Log_OC.d(TAG, "onResume() end");
  663. }
  664. @Override
  665. protected void onPause() {
  666. Log_OC.e(TAG, "onPause() start");
  667. if (mSyncBroadcastReceiver != null) {
  668. unregisterReceiver(mSyncBroadcastReceiver);
  669. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  670. mSyncBroadcastReceiver = null;
  671. }
  672. if (mUploadFinishReceiver != null) {
  673. unregisterReceiver(mUploadFinishReceiver);
  674. mUploadFinishReceiver = null;
  675. }
  676. if (mDownloadFinishReceiver != null) {
  677. unregisterReceiver(mDownloadFinishReceiver);
  678. mDownloadFinishReceiver = null;
  679. }
  680. Log_OC.d(TAG, "onPause() end");
  681. super.onPause();
  682. }
  683. @Override
  684. protected Dialog onCreateDialog(int id) {
  685. Dialog dialog = null;
  686. AlertDialog.Builder builder;
  687. switch (id) {
  688. case DIALOG_SHORT_WAIT: {
  689. ProgressDialog working_dialog = new ProgressDialog(this);
  690. working_dialog.setMessage(getResources().getString(
  691. R.string.wait_a_moment));
  692. working_dialog.setIndeterminate(true);
  693. working_dialog.setCancelable(false);
  694. dialog = working_dialog;
  695. break;
  696. }
  697. case DIALOG_CHOOSE_UPLOAD_SOURCE: {
  698. String[] allTheItems = { getString(R.string.actionbar_upload_files),
  699. getString(R.string.actionbar_upload_from_apps) };
  700. builder = new AlertDialog.Builder(this);
  701. builder.setTitle(R.string.actionbar_upload);
  702. builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
  703. public void onClick(DialogInterface dialog, int item) {
  704. if (item == 0) {
  705. // if (!mDualPane) {
  706. Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
  707. action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
  708. startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
  709. // } else {
  710. // TODO create and handle new fragment
  711. // LocalFileListFragment
  712. // }
  713. } else if (item == 1) {
  714. Intent action = new Intent(Intent.ACTION_GET_CONTENT);
  715. action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
  716. startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
  717. ACTION_SELECT_CONTENT_FROM_APPS);
  718. }
  719. }
  720. });
  721. dialog = builder.create();
  722. break;
  723. }
  724. case DIALOG_CERT_NOT_SAVED: {
  725. builder = new AlertDialog.Builder(this);
  726. builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
  727. builder.setCancelable(false);
  728. builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
  729. @Override
  730. public void onClick(DialogInterface dialog, int which) {
  731. dialog.dismiss();
  732. };
  733. });
  734. dialog = builder.create();
  735. break;
  736. }
  737. default:
  738. dialog = null;
  739. }
  740. return dialog;
  741. }
  742. /**
  743. * Translates a content URI of an image to a physical path
  744. * on the disk
  745. * @param uri The URI to resolve
  746. * @return The path to the image or null if it could not be found
  747. */
  748. public String getPath(Uri uri) {
  749. String[] projection = { MediaStore.Images.Media.DATA };
  750. Cursor cursor = managedQuery(uri, projection, null, null, null);
  751. if (cursor != null) {
  752. int column_index = cursor
  753. .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  754. cursor.moveToFirst();
  755. return cursor.getString(column_index);
  756. }
  757. return null;
  758. }
  759. /**
  760. * Pushes a directory to the drop down list
  761. * @param directory to push
  762. * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
  763. */
  764. public void pushDirname(OCFile directory) {
  765. if(!directory.isFolder()){
  766. throw new IllegalArgumentException("Only directories may be pushed!");
  767. }
  768. mDirectories.insert(directory.getFileName(), 0);
  769. setFile(directory);
  770. }
  771. /**
  772. * Pops a directory name from the drop down list
  773. * @return True, unless the stack is empty
  774. */
  775. public boolean popDirname() {
  776. mDirectories.remove(mDirectories.getItem(0));
  777. return !mDirectories.isEmpty();
  778. }
  779. // Custom array adapter to override text colors
  780. private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
  781. public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
  782. super(ctx, view);
  783. }
  784. public View getView(int position, View convertView, ViewGroup parent) {
  785. View v = super.getView(position, convertView, parent);
  786. ((TextView) v).setTextColor(getResources().getColorStateList(
  787. android.R.color.white));
  788. fixRoot((TextView) v );
  789. return v;
  790. }
  791. public View getDropDownView(int position, View convertView,
  792. ViewGroup parent) {
  793. View v = super.getDropDownView(position, convertView, parent);
  794. ((TextView) v).setTextColor(getResources().getColorStateList(
  795. android.R.color.white));
  796. fixRoot((TextView) v );
  797. return v;
  798. }
  799. private void fixRoot(TextView v) {
  800. if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
  801. v.setText(R.string.default_display_name_for_root_folder);
  802. }
  803. }
  804. }
  805. private class SyncBroadcastReceiver extends BroadcastReceiver {
  806. /**
  807. * {@link BroadcastReceiver} to enable syncing feedback in UI
  808. */
  809. @Override
  810. public void onReceive(Context context, Intent intent) {
  811. try {
  812. String event = intent.getAction();
  813. Log_OC.d(TAG, "Received broadcast " + event);
  814. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  815. String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  816. RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
  817. boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
  818. if (sameAccount) {
  819. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  820. mSyncInProgress = true;
  821. } else {
  822. OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
  823. OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  824. if (currentDir == null) {
  825. // current folder was removed from the server
  826. Toast.makeText( FileDisplayActivity.this,
  827. String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
  828. Toast.LENGTH_LONG)
  829. .show();
  830. browseToRoot();
  831. } else {
  832. if (currentFile == null && !getFile().isFolder()) {
  833. // currently selected file was removed in the server, and now we know it
  834. cleanSecondFragment();
  835. currentFile = currentDir;
  836. }
  837. if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  838. OCFileListFragment fileListFragment = getListOfFilesFragment();
  839. if (fileListFragment != null) {
  840. fileListFragment.listDirectory(currentDir);
  841. }
  842. }
  843. setFile(currentFile);
  844. }
  845. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
  846. if (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
  847. equals(event) &&
  848. /// TODO refactor and make common
  849. synchResult != null && !synchResult.isSuccess() &&
  850. (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
  851. synchResult.isIdPRedirection() ||
  852. (synchResult.isException() && synchResult.getException()
  853. instanceof AuthenticatorException))) {
  854. OwnCloudClient client = null;
  855. try {
  856. OwnCloudAccount ocAccount =
  857. new OwnCloudAccount(getAccount(), context);
  858. client = (OwnCloudClientManagerFactory.getDefaultSingleton().
  859. removeClientFor(ocAccount));
  860. // TODO get rid of these exceptions
  861. } catch (AccountNotFoundException e) {
  862. e.printStackTrace();
  863. } catch (AuthenticatorException e) {
  864. e.printStackTrace();
  865. } catch (OperationCanceledException e) {
  866. e.printStackTrace();
  867. } catch (IOException e) {
  868. e.printStackTrace();
  869. }
  870. if (client != null) {
  871. OwnCloudCredentials cred = client.getCredentials();
  872. if (cred != null) {
  873. AccountManager am = AccountManager.get(context);
  874. if (cred.authTokenExpires()) {
  875. am.invalidateAuthToken(
  876. getAccount().type,
  877. cred.getAuthToken()
  878. );
  879. } else {
  880. am.clearPassword(getAccount());
  881. }
  882. }
  883. }
  884. requestCredentialsUpdate();
  885. }
  886. }
  887. removeStickyBroadcast(intent);
  888. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  889. setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
  890. setBackgroundText();
  891. }
  892. if (synchResult != null) {
  893. if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  894. mLastSslUntrustedServerResult = synchResult;
  895. }
  896. }
  897. } catch (RuntimeException e) {
  898. // avoid app crashes after changing the serial id of RemoteOperationResult
  899. // in owncloud library with broadcast notifications pending to process
  900. removeStickyBroadcast(intent);
  901. }
  902. }
  903. }
  904. /**
  905. * Show a text message on screen view for notifying user if content is
  906. * loading or folder is empty
  907. */
  908. private void setBackgroundText() {
  909. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  910. if (ocFileListFragment != null) {
  911. int message = R.string.file_list_loading;
  912. if (!mSyncInProgress) {
  913. // In case file list is empty
  914. message = R.string.file_list_empty;
  915. }
  916. ocFileListFragment.setMessageForEmptyList(getString(message));
  917. } else {
  918. Log.e(TAG, "OCFileListFragment is null");
  919. }
  920. }
  921. /**
  922. * Once the file upload has finished -> update view
  923. */
  924. private class UploadFinishReceiver extends BroadcastReceiver {
  925. /**
  926. * Once the file upload has finished -> update view
  927. * @author David A. Velasco
  928. * {@link BroadcastReceiver} to enable upload feedback in UI
  929. */
  930. @Override
  931. public void onReceive(Context context, Intent intent) {
  932. try {
  933. String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  934. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  935. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  936. OCFile currentDir = getCurrentDir();
  937. boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
  938. (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
  939. if (sameAccount && isDescendant) {
  940. refreshListOfFilesFragment();
  941. }
  942. boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
  943. boolean renamedInUpload = getFile().getRemotePath().
  944. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  945. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  946. renamedInUpload;
  947. FileFragment details = getSecondFragment();
  948. boolean detailFragmentIsShown = (details != null &&
  949. details instanceof FileDetailFragment);
  950. if (sameAccount && sameFile && detailFragmentIsShown) {
  951. if (uploadWasFine) {
  952. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  953. }
  954. if (renamedInUpload) {
  955. String newName = (new File(uploadedRemotePath)).getName();
  956. Toast msg = Toast.makeText(
  957. context,
  958. String.format(
  959. getString(R.string.filedetails_renamed_in_upload_msg),
  960. newName),
  961. Toast.LENGTH_LONG);
  962. msg.show();
  963. }
  964. if (uploadWasFine || getFile().fileExists()) {
  965. ((FileDetailFragment)details).updateFileDetails(false, true);
  966. } else {
  967. cleanSecondFragment();
  968. }
  969. // Force the preview if the file is an image
  970. if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
  971. startImagePreview(getFile());
  972. } // TODO what about other kind of previews?
  973. }
  974. } finally {
  975. if (intent != null) {
  976. removeStickyBroadcast(intent);
  977. }
  978. }
  979. }
  980. }
  981. /**
  982. * Class waiting for broadcast events from the {@link FielDownloader} service.
  983. *
  984. * Updates the UI when a download is started or finished, provided that it is relevant for the
  985. * current folder.
  986. */
  987. private class DownloadFinishReceiver extends BroadcastReceiver {
  988. @Override
  989. public void onReceive(Context context, Intent intent) {
  990. try {
  991. boolean sameAccount = isSameAccount(context, intent);
  992. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  993. boolean isDescendant = isDescendant(downloadedRemotePath);
  994. if (sameAccount && isDescendant) {
  995. refreshListOfFilesFragment();
  996. refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
  997. }
  998. if (mWaitingToSend != null) {
  999. mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
  1000. if (mWaitingToSend.isDown()) {
  1001. sendDownloadedFile();
  1002. }
  1003. }
  1004. } finally {
  1005. if (intent != null) {
  1006. removeStickyBroadcast(intent);
  1007. }
  1008. }
  1009. }
  1010. private boolean isDescendant(String downloadedRemotePath) {
  1011. OCFile currentDir = getCurrentDir();
  1012. return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
  1013. }
  1014. private boolean isSameAccount(Context context, Intent intent) {
  1015. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  1016. return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
  1017. }
  1018. }
  1019. public void browseToRoot() {
  1020. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1021. if (listOfFiles != null) { // should never be null, indeed
  1022. while (mDirectories.getCount() > 1) {
  1023. popDirname();
  1024. }
  1025. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  1026. listOfFiles.listDirectory(root);
  1027. setFile(listOfFiles.getCurrentFile());
  1028. startSyncFolderOperation(root);
  1029. }
  1030. cleanSecondFragment();
  1031. }
  1032. public void browseTo(OCFile folder) {
  1033. if (folder == null || !folder.isFolder()) {
  1034. throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
  1035. }
  1036. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1037. if (listOfFiles != null) {
  1038. setNavigationListWithFolder(folder);
  1039. listOfFiles.listDirectory(folder);
  1040. setFile(listOfFiles.getCurrentFile());
  1041. startSyncFolderOperation(folder);
  1042. } else {
  1043. Log_OC.e(TAG, "Unexpected null when accessing list fragment");
  1044. }
  1045. cleanSecondFragment();
  1046. }
  1047. /**
  1048. * {@inheritDoc}
  1049. *
  1050. * Updates action bar and second fragment, if in dual pane mode.
  1051. */
  1052. @Override
  1053. public void onBrowsedDownTo(OCFile directory) {
  1054. pushDirname(directory);
  1055. cleanSecondFragment();
  1056. // Sync Folder
  1057. startSyncFolderOperation(directory);
  1058. }
  1059. /**
  1060. * Shows the information of the {@link OCFile} received as a
  1061. * parameter in the second fragment.
  1062. *
  1063. * @param file {@link OCFile} whose details will be shown
  1064. */
  1065. @Override
  1066. public void showDetails(OCFile file) {
  1067. Fragment detailFragment = new FileDetailFragment(file, getAccount());
  1068. setSecondFragment(detailFragment);
  1069. updateFragmentsVisibility(true);
  1070. updateNavigationElementsInActionBar(file);
  1071. setFile(file);
  1072. }
  1073. /**
  1074. * TODO
  1075. */
  1076. private void updateNavigationElementsInActionBar(OCFile chosenFile) {
  1077. ActionBar actionBar = getSupportActionBar();
  1078. if (chosenFile == null || mDualPane) {
  1079. // only list of files - set for browsing through folders
  1080. OCFile currentDir = getCurrentDir();
  1081. boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
  1082. actionBar.setDisplayHomeAsUpEnabled(noRoot);
  1083. actionBar.setDisplayShowTitleEnabled(!noRoot);
  1084. if (!noRoot) {
  1085. actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
  1086. }
  1087. actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
  1088. actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
  1089. } else {
  1090. actionBar.setDisplayHomeAsUpEnabled(true);
  1091. actionBar.setDisplayShowTitleEnabled(true);
  1092. actionBar.setTitle(chosenFile.getFileName());
  1093. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
  1094. }
  1095. }
  1096. @Override
  1097. protected ServiceConnection newTransferenceServiceConnection() {
  1098. return new ListServiceConnection();
  1099. }
  1100. /** Defines callbacks for service binding, passed to bindService() */
  1101. private class ListServiceConnection implements ServiceConnection {
  1102. @Override
  1103. public void onServiceConnected(ComponentName component, IBinder service) {
  1104. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1105. Log_OC.d(TAG, "Download service connected");
  1106. mDownloaderBinder = (FileDownloaderBinder) service;
  1107. if (mWaitingToPreview != null)
  1108. if (getStorageManager() != null) {
  1109. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
  1110. if (!mWaitingToPreview.isDown()) {
  1111. requestForDownload();
  1112. }
  1113. }
  1114. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1115. Log_OC.d(TAG, "Upload service connected");
  1116. mUploaderBinder = (FileUploaderBinder) service;
  1117. } else {
  1118. return;
  1119. }
  1120. // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
  1121. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1122. if (listOfFiles != null) {
  1123. listOfFiles.listDirectory();
  1124. }
  1125. FileFragment secondFragment = getSecondFragment();
  1126. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  1127. FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
  1128. detailFragment.listenForTransferProgress();
  1129. detailFragment.updateFileDetails(false, false);
  1130. }
  1131. }
  1132. @Override
  1133. public void onServiceDisconnected(ComponentName component) {
  1134. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1135. Log_OC.d(TAG, "Download service disconnected");
  1136. mDownloaderBinder = null;
  1137. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1138. Log_OC.d(TAG, "Upload service disconnected");
  1139. mUploaderBinder = null;
  1140. }
  1141. }
  1142. };
  1143. /**
  1144. * Launch an intent to request the PIN code to the user before letting him use the app
  1145. */
  1146. private void requestPinCode() {
  1147. boolean pinStart = false;
  1148. SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  1149. pinStart = appPrefs.getBoolean("set_pincode", false);
  1150. if (pinStart) {
  1151. Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
  1152. i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
  1153. startActivity(i);
  1154. }
  1155. }
  1156. @Override
  1157. public void onSavedCertificate() {
  1158. startSyncFolderOperation(getCurrentDir());
  1159. }
  1160. @Override
  1161. public void onFailedSavingCertificate() {
  1162. showDialog(DIALOG_CERT_NOT_SAVED);
  1163. }
  1164. @Override
  1165. public void onCancelCertificate() {
  1166. // nothing to do
  1167. }
  1168. /**
  1169. * Updates the view associated to the activity after the finish of some operation over files
  1170. * in the current account.
  1171. *
  1172. * @param operation Removal operation performed.
  1173. * @param result Result of the removal.
  1174. */
  1175. @Override
  1176. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1177. super.onRemoteOperationFinish(operation, result);
  1178. if (operation instanceof RemoveFileOperation) {
  1179. onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
  1180. } else if (operation instanceof RenameFileOperation) {
  1181. onRenameFileOperationFinish((RenameFileOperation)operation, result);
  1182. } else if (operation instanceof SynchronizeFileOperation) {
  1183. onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
  1184. } else if (operation instanceof CreateFolderOperation) {
  1185. onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
  1186. } else if (operation instanceof CreateShareOperation) {
  1187. onCreateShareOperationFinish((CreateShareOperation) operation, result);
  1188. } else if (operation instanceof UnshareLinkOperation) {
  1189. onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
  1190. } else if (operation instanceof MoveFileOperation) {
  1191. onMoveFileOperationFinish((MoveFileOperation)operation, result);
  1192. }
  1193. }
  1194. private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
  1195. if (result.isSuccess()) {
  1196. refreshShowDetails();
  1197. refreshListOfFilesFragment();
  1198. }
  1199. }
  1200. private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
  1201. if (result.isSuccess()) {
  1202. refreshShowDetails();
  1203. refreshListOfFilesFragment();
  1204. } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
  1205. cleanSecondFragment();
  1206. refreshListOfFilesFragment();
  1207. }
  1208. }
  1209. private void refreshShowDetails() {
  1210. FileFragment details = getSecondFragment();
  1211. if (details != null) {
  1212. OCFile file = details.getFile();
  1213. if (file != null) {
  1214. file = getStorageManager().getFileByPath(file.getRemotePath());
  1215. if (details instanceof PreviewMediaFragment) {
  1216. // Refresh OCFile of the fragment
  1217. ((PreviewMediaFragment) details).updateFile(file);
  1218. } else {
  1219. showDetails(file);
  1220. }
  1221. }
  1222. invalidateOptionsMenu();
  1223. }
  1224. }
  1225. /**
  1226. * Updates the view associated to the activity after the finish of an operation trying to remove a
  1227. * file.
  1228. *
  1229. * @param operation Removal operation performed.
  1230. * @param result Result of the removal.
  1231. */
  1232. private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
  1233. dismissLoadingDialog();
  1234. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1235. Toast.LENGTH_LONG);
  1236. msg.show();
  1237. if (result.isSuccess()) {
  1238. OCFile removedFile = operation.getFile();
  1239. FileFragment second = getSecondFragment();
  1240. if (second != null && removedFile.equals(second.getFile())) {
  1241. if (second instanceof PreviewMediaFragment) {
  1242. ((PreviewMediaFragment)second).stopPreview(true);
  1243. }
  1244. setFile(getStorageManager().getFileById(removedFile.getParentId()));
  1245. cleanSecondFragment();
  1246. }
  1247. if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
  1248. refreshListOfFilesFragment();
  1249. }
  1250. invalidateOptionsMenu();
  1251. } else {
  1252. if (result.isSslRecoverableException()) {
  1253. mLastSslUntrustedServerResult = result;
  1254. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1255. }
  1256. }
  1257. }
  1258. /**
  1259. * Updates the view associated to the activity after the finish of an operation trying to move a
  1260. * file.
  1261. *
  1262. * @param operation Move operation performed.
  1263. * @param result Result of the move operation.
  1264. */
  1265. private void onMoveFileOperationFinish(MoveFileOperation operation, RemoteOperationResult result) {
  1266. if (result.isSuccess()) {
  1267. dismissLoadingDialog();
  1268. refreshListOfFilesFragment();
  1269. } else {
  1270. dismissLoadingDialog();
  1271. try {
  1272. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1273. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1274. Toast.LENGTH_LONG);
  1275. msg.show();
  1276. } catch (NotFoundException e) {
  1277. Log_OC.e(TAG, "Error while trying to show fail message " , e);
  1278. }
  1279. }
  1280. }
  1281. /**
  1282. * Updates the view associated to the activity after the finish of an operation trying to rename a
  1283. * file.
  1284. *
  1285. * @param operation Renaming operation performed.
  1286. * @param result Result of the renaming.
  1287. */
  1288. private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
  1289. dismissLoadingDialog();
  1290. OCFile renamedFile = operation.getFile();
  1291. if (result.isSuccess()) {
  1292. FileFragment details = getSecondFragment();
  1293. if (details != null) {
  1294. if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
  1295. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1296. showDetails(renamedFile);
  1297. } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
  1298. ((PreviewMediaFragment) details).updateFile(renamedFile);
  1299. if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
  1300. int position = ((PreviewMediaFragment)details).getPosition();
  1301. startMediaPreview(renamedFile, position, true);
  1302. } else {
  1303. getFileOperationsHelper().openFile(renamedFile);
  1304. }
  1305. }
  1306. }
  1307. if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
  1308. refreshListOfFilesFragment();
  1309. }
  1310. } else {
  1311. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1312. Toast.LENGTH_LONG);
  1313. msg.show();
  1314. if (result.isSslRecoverableException()) {
  1315. mLastSslUntrustedServerResult = result;
  1316. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1317. }
  1318. }
  1319. }
  1320. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
  1321. dismissLoadingDialog();
  1322. OCFile syncedFile = operation.getLocalFile();
  1323. if (!result.isSuccess()) {
  1324. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  1325. Intent i = new Intent(this, ConflictsResolveActivity.class);
  1326. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
  1327. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
  1328. startActivity(i);
  1329. }
  1330. } else {
  1331. if (operation.transferWasRequested()) {
  1332. onTransferStateChanged(syncedFile, true, true);
  1333. } else {
  1334. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1335. Toast.LENGTH_LONG);
  1336. msg.show();
  1337. }
  1338. }
  1339. }
  1340. /**
  1341. * Updates the view associated to the activity after the finish of an operation trying create a new folder
  1342. *
  1343. * @param operation Creation operation performed.
  1344. * @param result Result of the creation.
  1345. */
  1346. private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
  1347. if (result.isSuccess()) {
  1348. dismissLoadingDialog();
  1349. refreshListOfFilesFragment();
  1350. } else {
  1351. dismissLoadingDialog();
  1352. try {
  1353. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1354. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1355. Toast.LENGTH_LONG);
  1356. msg.show();
  1357. } catch (NotFoundException e) {
  1358. Log_OC.e(TAG, "Error while trying to show fail message " , e);
  1359. }
  1360. }
  1361. }
  1362. /**
  1363. * {@inheritDoc}
  1364. */
  1365. @Override
  1366. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1367. refreshListOfFilesFragment();
  1368. FileFragment details = getSecondFragment();
  1369. if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
  1370. if (downloading || uploading) {
  1371. ((FileDetailFragment)details).updateFileDetails(file, getAccount());
  1372. } else {
  1373. if (!file.fileExists()) {
  1374. cleanSecondFragment();
  1375. } else {
  1376. ((FileDetailFragment)details).updateFileDetails(false, true);
  1377. }
  1378. }
  1379. }
  1380. }
  1381. private void requestForDownload() {
  1382. Account account = getAccount();
  1383. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1384. Intent i = new Intent(this, FileDownloader.class);
  1385. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1386. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1387. startService(i);
  1388. }
  1389. }
  1390. private OCFile getCurrentDir() {
  1391. OCFile file = getFile();
  1392. if (file != null) {
  1393. if (file.isFolder()) {
  1394. return file;
  1395. } else if (getStorageManager() != null) {
  1396. String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
  1397. return getStorageManager().getFileByPath(parentPath);
  1398. }
  1399. }
  1400. return null;
  1401. }
  1402. public void startSyncFolderOperation(OCFile folder) {
  1403. long currentSyncTime = System.currentTimeMillis();
  1404. mSyncInProgress = true;
  1405. // perform folder synchronization
  1406. RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
  1407. currentSyncTime,
  1408. false,
  1409. getFileOperationsHelper().isSharedSupported(),
  1410. getStorageManager(),
  1411. getAccount(),
  1412. getApplicationContext()
  1413. );
  1414. synchFolderOp.execute(getAccount(), this, null, null);
  1415. setSupportProgressBarIndeterminateVisibility(true);
  1416. setBackgroundText();
  1417. }
  1418. /**
  1419. * Show untrusted cert dialog
  1420. */
  1421. public void showUntrustedCertDialog(RemoteOperationResult result) {
  1422. // Show a dialog with the certificate info
  1423. SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
  1424. FragmentManager fm = getSupportFragmentManager();
  1425. FragmentTransaction ft = fm.beginTransaction();
  1426. dialog.show(ft, DIALOG_UNTRUSTED_CERT);
  1427. }
  1428. private void requestForDownload(OCFile file) {
  1429. Account account = getAccount();
  1430. if (!mDownloaderBinder.isDownloading(account, file)) {
  1431. Intent i = new Intent(this, FileDownloader.class);
  1432. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1433. i.putExtra(FileDownloader.EXTRA_FILE, file);
  1434. startService(i);
  1435. }
  1436. }
  1437. private void sendDownloadedFile(){
  1438. getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
  1439. mWaitingToSend = null;
  1440. }
  1441. /**
  1442. * Requests the download of the received {@link OCFile} , updates the UI
  1443. * to monitor the download progress and prepares the activity to send the file
  1444. * when the download finishes.
  1445. *
  1446. * @param file {@link OCFile} to download and preview.
  1447. */
  1448. public void startDownloadForSending(OCFile file) {
  1449. mWaitingToSend = file;
  1450. requestForDownload(mWaitingToSend);
  1451. boolean hasSecondFragment = (getSecondFragment()!= null);
  1452. updateFragmentsVisibility(hasSecondFragment);
  1453. }
  1454. /**
  1455. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1456. *
  1457. * @param file Image {@link OCFile} to show.
  1458. */
  1459. public void startImagePreview(OCFile file) {
  1460. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1461. showDetailsIntent.putExtra(EXTRA_FILE, file);
  1462. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1463. startActivity(showDetailsIntent);
  1464. }
  1465. /**
  1466. * Stars the preview of an already down media {@link OCFile}.
  1467. *
  1468. * @param file Media {@link OCFile} to preview.
  1469. * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
  1470. * @param autoplay When 'true', the playback will start without user interactions.
  1471. */
  1472. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
  1473. Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
  1474. setSecondFragment(mediaFragment);
  1475. updateFragmentsVisibility(true);
  1476. updateNavigationElementsInActionBar(file);
  1477. setFile(file);
  1478. }
  1479. /**
  1480. * Requests the download of the received {@link OCFile} , updates the UI
  1481. * to monitor the download progress and prepares the activity to preview
  1482. * or open the file when the download finishes.
  1483. *
  1484. * @param file {@link OCFile} to download and preview.
  1485. */
  1486. public void startDownloadForPreview(OCFile file) {
  1487. Fragment detailFragment = new FileDetailFragment(file, getAccount());
  1488. setSecondFragment(detailFragment);
  1489. mWaitingToPreview = file;
  1490. requestForDownload();
  1491. updateFragmentsVisibility(true);
  1492. updateNavigationElementsInActionBar(file);
  1493. setFile(file);
  1494. }
  1495. public void cancelTransference(OCFile file) {
  1496. getFileOperationsHelper().cancelTransference(file);
  1497. if (mWaitingToPreview != null &&
  1498. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  1499. mWaitingToPreview = null;
  1500. }
  1501. if (mWaitingToSend != null &&
  1502. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  1503. mWaitingToSend = null;
  1504. }
  1505. onTransferStateChanged(file, false, false);
  1506. }
  1507. @Override
  1508. public void onRefresh() {
  1509. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1510. if (listOfFiles != null) {
  1511. OCFile folder = listOfFiles.getCurrentFile();
  1512. if (folder != null) {
  1513. /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
  1514. listDirectory(mFile);*/
  1515. startSyncFolderOperation(folder);
  1516. }
  1517. }
  1518. }
  1519. private void sortByDate(boolean ascending){
  1520. getListOfFilesFragment().sortByDate(ascending);
  1521. }
  1522. private void sortBySize(boolean ascending){
  1523. getListOfFilesFragment().sortBySize(ascending);
  1524. }
  1525. private void sortByName(boolean ascending){
  1526. getListOfFilesFragment().sortByName(ascending);
  1527. }
  1528. }