FileDisplayActivity.java 74 KB

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