FileDisplayActivity.java 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author David A. Velasco
  6. * Copyright (C) 2011 Bartek Przybylski
  7. * Copyright (C) 2016 ownCloud Inc.
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. package com.owncloud.android.ui.activity;
  22. import android.Manifest;
  23. import android.accounts.Account;
  24. import android.accounts.AuthenticatorException;
  25. import android.annotation.TargetApi;
  26. import android.content.BroadcastReceiver;
  27. import android.content.ComponentName;
  28. import android.content.ContentResolver;
  29. import android.content.Context;
  30. import android.content.DialogInterface;
  31. import android.content.Intent;
  32. import android.content.IntentFilter;
  33. import android.content.ServiceConnection;
  34. import android.content.SharedPreferences;
  35. import android.content.SyncRequest;
  36. import android.content.pm.PackageManager;
  37. import android.content.res.Resources.NotFoundException;
  38. import android.database.Cursor;
  39. import android.net.Uri;
  40. import android.os.Build;
  41. import android.os.Bundle;
  42. import android.os.IBinder;
  43. import android.os.Parcelable;
  44. import android.preference.PreferenceManager;
  45. import android.provider.OpenableColumns;
  46. import android.support.design.widget.Snackbar;
  47. import android.support.v4.app.Fragment;
  48. import android.support.v4.app.FragmentTransaction;
  49. import android.support.v4.content.ContextCompat;
  50. import android.support.v4.view.GravityCompat;
  51. import android.support.v7.app.AlertDialog;
  52. import android.view.Menu;
  53. import android.view.MenuInflater;
  54. import android.view.MenuItem;
  55. import android.view.View;
  56. import android.widget.ProgressBar;
  57. import android.widget.Toast;
  58. import com.owncloud.android.MainApp;
  59. import com.owncloud.android.R;
  60. import com.owncloud.android.datamodel.FileDataStorageManager;
  61. import com.owncloud.android.datamodel.OCFile;
  62. import com.owncloud.android.files.services.FileDownloader;
  63. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  64. import com.owncloud.android.files.services.FileUploader;
  65. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  66. import com.owncloud.android.lib.common.operations.RemoteOperation;
  67. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  68. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  69. import com.owncloud.android.lib.common.utils.Log_OC;
  70. import com.owncloud.android.operations.CopyFileOperation;
  71. import com.owncloud.android.operations.CreateFolderOperation;
  72. import com.owncloud.android.operations.MoveFileOperation;
  73. import com.owncloud.android.operations.RefreshFolderOperation;
  74. import com.owncloud.android.operations.RemoveFileOperation;
  75. import com.owncloud.android.operations.RenameFileOperation;
  76. import com.owncloud.android.operations.SynchronizeFileOperation;
  77. import com.owncloud.android.operations.UploadFileOperation;
  78. import com.owncloud.android.services.observer.FileObserverService;
  79. import com.owncloud.android.syncadapter.FileSyncAdapter;
  80. import com.owncloud.android.ui.asynctasks.CopyAndUploadContentUrisTask;
  81. import com.owncloud.android.ui.fragment.FileDetailFragment;
  82. import com.owncloud.android.ui.fragment.FileFragment;
  83. import com.owncloud.android.ui.fragment.OCFileListFragment;
  84. import com.owncloud.android.ui.helpers.UriUploader;
  85. import com.owncloud.android.ui.preview.PreviewImageActivity;
  86. import com.owncloud.android.ui.preview.PreviewImageFragment;
  87. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  88. import com.owncloud.android.ui.preview.PreviewTextFragment;
  89. import com.owncloud.android.ui.preview.PreviewVideoActivity;
  90. import com.owncloud.android.utils.DisplayUtils;
  91. import com.owncloud.android.utils.ErrorMessageAdapter;
  92. import com.owncloud.android.utils.FileStorageUtils;
  93. import com.owncloud.android.utils.PermissionUtil;
  94. import com.owncloud.android.utils.UriUtils;
  95. import java.io.File;
  96. import java.util.ArrayList;
  97. import java.util.Arrays;
  98. /**
  99. * Displays, what files the user has available in his ownCloud. This is the main view.
  100. */
  101. public class FileDisplayActivity extends HookActivity
  102. implements FileFragment.ContainerActivity,
  103. OnEnforceableRefreshListener, CopyAndUploadContentUrisTask.OnCopyTmpFilesTaskListener {
  104. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  105. private UploadFinishReceiver mUploadFinishReceiver;
  106. private DownloadFinishReceiver mDownloadFinishReceiver;
  107. private RemoteOperationResult mLastSslUntrustedServerResult = null;
  108. private boolean mDualPane;
  109. private View mLeftFragmentContainer;
  110. private View mRightFragmentContainer;
  111. private ProgressBar mProgressBar;
  112. private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  113. private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
  114. private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
  115. public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
  116. public static final int REQUEST_CODE__SELECT_CONTENT_FROM_APPS = REQUEST_CODE__LAST_SHARED + 1;
  117. public static final int REQUEST_CODE__SELECT_MULTIPLE_FILES = REQUEST_CODE__LAST_SHARED + 2;
  118. public static final int REQUEST_CODE__MOVE_FILES = REQUEST_CODE__LAST_SHARED + 3;
  119. public static final int REQUEST_CODE__COPY_FILES = REQUEST_CODE__LAST_SHARED + 4;
  120. private static final String TAG = FileDisplayActivity.class.getSimpleName();
  121. private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
  122. private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
  123. private OCFile mWaitingToPreview;
  124. private boolean mSyncInProgress = false;
  125. private OCFile mWaitingToSend;
  126. @Override
  127. protected void onCreate(Bundle savedInstanceState) {
  128. Log_OC.v(TAG, "onCreate() start");
  129. super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account
  130. // is valid
  131. /// grant that FileObserverService is watching favorite files
  132. if (savedInstanceState == null) {
  133. Intent initObserversIntent = FileObserverService.makeInitIntent(this);
  134. startService(initObserversIntent);
  135. }
  136. /// Load of saved instance state
  137. if (savedInstanceState != null) {
  138. mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(
  139. FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
  140. mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
  141. mWaitingToSend = (OCFile) savedInstanceState.getParcelable(
  142. FileDisplayActivity.KEY_WAITING_TO_SEND);
  143. } else {
  144. mWaitingToPreview = null;
  145. mSyncInProgress = false;
  146. mWaitingToSend = null;
  147. }
  148. /// USER INTERFACE
  149. // Inflate and set the layout view
  150. setContentView(R.layout.files);
  151. // Navigation Drawer
  152. initDrawer();
  153. mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
  154. mProgressBar.setIndeterminateDrawable(
  155. ContextCompat.getDrawable(this,
  156. R.drawable.actionbar_progress_indeterminate_horizontal));
  157. mDualPane = getResources().getBoolean(R.bool.large_land_layout);
  158. mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
  159. mRightFragmentContainer = findViewById(R.id.right_fragment_container);
  160. // Action bar setup
  161. getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS,
  162. // according to the official
  163. // documentation
  164. // enable ActionBar app icon to behave as action to toggle nav drawer
  165. //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  166. getSupportActionBar().setHomeButtonEnabled(true);
  167. Log_OC.v(TAG, "onCreate() end");
  168. }
  169. @Override
  170. protected void onPostCreate(Bundle savedInstanceState) {
  171. super.onPostCreate(savedInstanceState);
  172. if (PermissionUtil.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  173. // Check if we should show an explanation
  174. if (PermissionUtil.shouldShowRequestPermissionRationale(this,
  175. Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  176. // Show explanation to the user and then request permission
  177. Snackbar snackbar = Snackbar.make(findViewById(R.id.ListLayout), R.string.permission_storage_access,
  178. Snackbar.LENGTH_INDEFINITE)
  179. .setAction(R.string.common_ok, new View.OnClickListener() {
  180. @Override
  181. public void onClick(View v) {
  182. PermissionUtil.requestWriteExternalStoreagePermission(FileDisplayActivity.this);
  183. }
  184. });
  185. DisplayUtils.colorSnackbar(this, snackbar);
  186. snackbar.show();
  187. } else {
  188. // No explanation needed, request the permission.
  189. PermissionUtil.requestWriteExternalStoreagePermission(this);
  190. }
  191. }
  192. if (savedInstanceState == null) {
  193. createMinFragments();
  194. }
  195. mProgressBar.setIndeterminate(mSyncInProgress);
  196. // always AFTER setContentView(...) in onCreate(); to work around bug in its implementation
  197. setBackgroundText();
  198. }
  199. @Override
  200. public void onRequestPermissionsResult(int requestCode,
  201. String permissions[], int[] grantResults) {
  202. switch (requestCode) {
  203. case PermissionUtil.PERMISSIONS_WRITE_EXTERNAL_STORAGE: {
  204. // If request is cancelled, result arrays are empty.
  205. if (grantResults.length > 0
  206. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  207. // permission was granted
  208. startSynchronization();
  209. // toggle on is save since this is the only scenario this code gets accessed
  210. } else {
  211. // permission denied --> do nothing
  212. }
  213. return;
  214. }
  215. }
  216. }
  217. @Override
  218. protected void onStart() {
  219. Log_OC.v(TAG, "onStart() start");
  220. super.onStart();
  221. Log_OC.v(TAG, "onStart() end");
  222. }
  223. @Override
  224. protected void onStop() {
  225. Log_OC.v(TAG, "onStop() start");
  226. super.onStop();
  227. Log_OC.v(TAG, "onStop() end");
  228. }
  229. @Override
  230. protected void onDestroy() {
  231. Log_OC.v(TAG, "onDestroy() start");
  232. super.onDestroy();
  233. Log_OC.v(TAG, "onDestroy() end");
  234. }
  235. /**
  236. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  237. */
  238. @Override
  239. protected void onAccountSet(boolean stateWasRecovered) {
  240. super.onAccountSet(stateWasRecovered);
  241. if (getAccount() != null) {
  242. /// Check whether the 'main' OCFile handled by the Activity is contained in the
  243. // current Account
  244. OCFile file = getFile();
  245. // get parent from path
  246. String parentPath = "";
  247. if (file != null) {
  248. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  249. // upload in progress - right now, files are not inserted in the local
  250. // cache until the upload is successful get parent from path
  251. parentPath = file.getRemotePath().substring(0,
  252. file.getRemotePath().lastIndexOf(file.getFileName()));
  253. if (getStorageManager().getFileByPath(parentPath) == null)
  254. file = null; // not able to know the directory where the file is uploading
  255. } else {
  256. file = getStorageManager().getFileByPath(file.getRemotePath());
  257. // currentDir = null if not in the current Account
  258. }
  259. }
  260. if (file == null) {
  261. // fall back to root folder
  262. file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
  263. }
  264. setFile(file);
  265. if (mAccountWasSet) {
  266. setUsernameInDrawer(findViewById(R.id.left_drawer), getAccount());
  267. }
  268. if (!stateWasRecovered) {
  269. Log_OC.d(TAG, "Initializing Fragments in onAccountChanged..");
  270. initFragmentsWithFile();
  271. if (file.isFolder()) {
  272. startSyncFolderOperation(file, false);
  273. }
  274. } else {
  275. updateFragmentsVisibility(!file.isFolder());
  276. updateActionBarTitleAndHomeButton(file.isFolder() ? null : file);
  277. }
  278. }
  279. }
  280. private void createMinFragments() {
  281. OCFileListFragment listOfFiles = new OCFileListFragment();
  282. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  283. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  284. transaction.commit();
  285. }
  286. private void initFragmentsWithFile() {
  287. if (getAccount() != null && getFile() != null) {
  288. /// First fragment
  289. OCFileListFragment listOfFiles = getListOfFilesFragment();
  290. if (listOfFiles != null) {
  291. listOfFiles.listDirectory(getCurrentDir());
  292. // TODO Enable when "On Device" is recovered
  293. // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
  294. } else {
  295. Log_OC.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
  296. }
  297. /// Second fragment
  298. OCFile file = getFile();
  299. Fragment secondFragment = chooseInitialSecondFragment(file);
  300. if (secondFragment != null) {
  301. setSecondFragment(secondFragment);
  302. updateFragmentsVisibility(true);
  303. updateActionBarTitleAndHomeButton(file);
  304. } else {
  305. cleanSecondFragment();
  306. if (file.isDown() && PreviewTextFragment.canBePreviewed(file))
  307. startTextPreview(file);
  308. }
  309. } else {
  310. Log_OC.wtf(TAG, "initFragments() called with invalid NULLs!");
  311. if (getAccount() == null) {
  312. Log_OC.wtf(TAG, "\t account is NULL");
  313. }
  314. if (getFile() == null) {
  315. Log_OC.wtf(TAG, "\t file is NULL");
  316. }
  317. }
  318. }
  319. private Fragment chooseInitialSecondFragment(OCFile file) {
  320. Fragment secondFragment = null;
  321. if (file != null && !file.isFolder()) {
  322. if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
  323. && file.getLastSyncDateForProperties() > 0 // temporal fix
  324. ) {
  325. int startPlaybackPosition =
  326. getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
  327. boolean autoplay =
  328. getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
  329. secondFragment = new PreviewMediaFragment(file, getAccount(),
  330. startPlaybackPosition, autoplay);
  331. } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) {
  332. secondFragment = null;
  333. } else {
  334. secondFragment = FileDetailFragment.newInstance(file, getAccount());
  335. }
  336. }
  337. return secondFragment;
  338. }
  339. /**
  340. * Replaces the second fragment managed by the activity with the received as
  341. * a parameter.
  342. * <p/>
  343. * Assumes never will be more than two fragments managed at the same time.
  344. *
  345. * @param fragment New second Fragment to set.
  346. */
  347. private void setSecondFragment(Fragment fragment) {
  348. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  349. transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
  350. transaction.commit();
  351. }
  352. private void updateFragmentsVisibility(boolean existsSecondFragment) {
  353. if (mDualPane) {
  354. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  355. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  356. }
  357. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  358. mRightFragmentContainer.setVisibility(View.VISIBLE);
  359. }
  360. } else if (existsSecondFragment) {
  361. if (mLeftFragmentContainer.getVisibility() != View.GONE) {
  362. mLeftFragmentContainer.setVisibility(View.GONE);
  363. }
  364. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  365. mRightFragmentContainer.setVisibility(View.VISIBLE);
  366. }
  367. } else {
  368. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  369. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  370. }
  371. if (mRightFragmentContainer.getVisibility() != View.GONE) {
  372. mRightFragmentContainer.setVisibility(View.GONE);
  373. }
  374. }
  375. }
  376. private OCFileListFragment getListOfFilesFragment() {
  377. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(
  378. FileDisplayActivity.TAG_LIST_OF_FILES);
  379. if (listOfFiles != null) {
  380. return (OCFileListFragment) listOfFiles;
  381. }
  382. Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
  383. return null;
  384. }
  385. public FileFragment getSecondFragment() {
  386. Fragment second = getSupportFragmentManager().findFragmentByTag(
  387. FileDisplayActivity.TAG_SECOND_FRAGMENT);
  388. if (second != null) {
  389. return (FileFragment) second;
  390. }
  391. return null;
  392. }
  393. protected void cleanSecondFragment() {
  394. Fragment second = getSecondFragment();
  395. if (second != null) {
  396. FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
  397. tr.remove(second);
  398. tr.commit();
  399. }
  400. updateFragmentsVisibility(false);
  401. updateActionBarTitleAndHomeButton(null);
  402. }
  403. protected void refreshListOfFilesFragment() {
  404. OCFileListFragment fileListFragment = getListOfFilesFragment();
  405. if (fileListFragment != null) {
  406. fileListFragment.listDirectory();
  407. // TODO Enable when "On Device" is recovered ?
  408. // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
  409. }
  410. }
  411. protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath,
  412. boolean success) {
  413. FileFragment secondFragment = getSecondFragment();
  414. boolean waitedPreview = (mWaitingToPreview != null &&
  415. mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
  416. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  417. FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
  418. OCFile fileInFragment = detailsFragment.getFile();
  419. if (fileInFragment != null &&
  420. !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  421. // the user browsed to other file ; forget the automatic preview
  422. mWaitingToPreview = null;
  423. } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
  424. // grant that the right panel updates the progress bar
  425. detailsFragment.listenForTransferProgress();
  426. detailsFragment.updateFileDetails(true, false);
  427. } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
  428. // update the right panel
  429. boolean detailsFragmentChanged = false;
  430. if (waitedPreview) {
  431. if (success) {
  432. mWaitingToPreview = getStorageManager().getFileById(
  433. mWaitingToPreview.getFileId()); // update the file from database,
  434. // for the local storage path
  435. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  436. startMediaPreview(mWaitingToPreview, 0, true);
  437. detailsFragmentChanged = true;
  438. } else if (PreviewTextFragment.canBePreviewed(mWaitingToPreview)) {
  439. startTextPreview(mWaitingToPreview);
  440. detailsFragmentChanged = true;
  441. } else {
  442. getFileOperationsHelper().openFile(mWaitingToPreview);
  443. }
  444. }
  445. mWaitingToPreview = null;
  446. }
  447. if (!detailsFragmentChanged) {
  448. detailsFragment.updateFileDetails(false, (success));
  449. }
  450. }
  451. }
  452. }
  453. @Override
  454. public boolean onPrepareOptionsMenu(Menu menu) {
  455. boolean drawerOpen = mDrawerLayout.isDrawerOpen(GravityCompat.START);
  456. menu.findItem(R.id.action_sort).setVisible(!drawerOpen);
  457. menu.findItem(R.id.action_sync_account).setVisible(!drawerOpen);
  458. menu.findItem(R.id.action_switch_view).setVisible(!drawerOpen);
  459. return super.onPrepareOptionsMenu(menu);
  460. }
  461. @Override
  462. public boolean onCreateOptionsMenu(Menu menu) {
  463. MenuInflater inflater = getMenuInflater();
  464. inflater.inflate(R.menu.main_menu, menu);
  465. menu.findItem(R.id.action_create_dir).setVisible(false);
  466. return true;
  467. }
  468. @Override
  469. public boolean onOptionsItemSelected(MenuItem item) {
  470. boolean retval = true;
  471. switch (item.getItemId()) {
  472. case R.id.action_sync_account: {
  473. startSynchronization();
  474. break;
  475. }
  476. case android.R.id.home: {
  477. FileFragment second = getSecondFragment();
  478. OCFile currentDir = getCurrentDir();
  479. if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
  480. mDrawerLayout.closeDrawer(GravityCompat.START);
  481. } else if ((currentDir != null && currentDir.getParentId() != 0) ||
  482. (second != null && second.getFile() != null)) {
  483. onBackPressed();
  484. } else {
  485. mDrawerLayout.openDrawer(GravityCompat.START);
  486. }
  487. break;
  488. }
  489. case R.id.action_sort: {
  490. SharedPreferences appPreferences = PreferenceManager
  491. .getDefaultSharedPreferences(this);
  492. // Read sorting order, default to sort by name ascending
  493. Integer sortOrder = appPreferences
  494. .getInt("sortOrder", FileStorageUtils.SORT_NAME);
  495. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  496. builder.setTitle(R.string.actionbar_sort_title)
  497. .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder,
  498. new DialogInterface.OnClickListener() {
  499. public void onClick(DialogInterface dialog, int which) {
  500. switch (which) {
  501. case 0:
  502. sortByName(true);
  503. break;
  504. case 1:
  505. sortByDate(false);
  506. break;
  507. }
  508. dialog.dismiss();
  509. }
  510. });
  511. builder.create().show();
  512. break;
  513. }
  514. case R.id.action_switch_view: {
  515. if (isGridView()) {
  516. item.setTitle(getString(R.string.action_switch_grid_view));
  517. item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
  518. R.drawable.ic_view_module));
  519. getListOfFilesFragment().setListAsPreferred();
  520. } else {
  521. item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
  522. item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
  523. R.drawable.ic_view_list));
  524. getListOfFilesFragment().setGridAsPreferred();
  525. }
  526. return true;
  527. }
  528. default:
  529. retval = super.onOptionsItemSelected(item);
  530. }
  531. return retval;
  532. }
  533. private void startSynchronization() {
  534. Log_OC.d(TAG, "Got to start sync");
  535. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  536. Log_OC.d(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  537. ContentResolver.cancelSync(null, MainApp.getAuthority());
  538. // cancel the current synchronizations of any ownCloud account
  539. Bundle bundle = new Bundle();
  540. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  541. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  542. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  543. MainApp.getAuthority());
  544. ContentResolver.requestSync(
  545. getAccount(),
  546. MainApp.getAuthority(), bundle);
  547. } else {
  548. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  549. MainApp.getAuthority() + " with new API");
  550. SyncRequest.Builder builder = new SyncRequest.Builder();
  551. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  552. builder.setExpedited(true);
  553. builder.setManual(true);
  554. builder.syncOnce();
  555. // Fix bug in Android Lollipop when you click on refresh the whole account
  556. Bundle extras = new Bundle();
  557. builder.setExtras(extras);
  558. SyncRequest request = builder.build();
  559. ContentResolver.requestSync(request);
  560. }
  561. }
  562. /**
  563. * Called, when the user selected something for uploading
  564. */
  565. @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  566. @Override
  567. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  568. if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK ||
  569. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  570. //getClipData is only supported on api level 16+, Jelly Bean
  571. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN &&
  572. data.getClipData() != null &&
  573. data.getClipData().getItemCount() > 0) {
  574. for (int i = 0; i < data.getClipData().getItemCount(); i++) {
  575. Intent intent = new Intent();
  576. intent.setData(data.getClipData().getItemAt(i).getUri());
  577. requestSimpleUpload(intent, resultCode);
  578. }
  579. } else {
  580. requestSimpleUpload(data, resultCode);
  581. }
  582. } else if (requestCode == REQUEST_CODE__SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK ||
  583. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  584. requestMultipleUpload(data, resultCode);
  585. } else if (requestCode == REQUEST_CODE__MOVE_FILES && resultCode == RESULT_OK) {
  586. final Intent fData = data;
  587. final int fResultCode = resultCode;
  588. getHandler().postDelayed(
  589. new Runnable() {
  590. @Override
  591. public void run() {
  592. requestMoveOperation(fData, fResultCode);
  593. }
  594. },
  595. DELAY_TO_REQUEST_OPERATIONS_LATER
  596. );
  597. } else if (requestCode == REQUEST_CODE__COPY_FILES && resultCode == RESULT_OK) {
  598. final Intent fData = data;
  599. final int fResultCode = resultCode;
  600. getHandler().postDelayed(
  601. new Runnable() {
  602. @Override
  603. public void run() {
  604. requestCopyOperation(fData, fResultCode);
  605. }
  606. },
  607. DELAY_TO_REQUEST_OPERATIONS_LATER
  608. );
  609. } else {
  610. super.onActivityResult(requestCode, resultCode, data);
  611. }
  612. }
  613. private void requestMultipleUpload(Intent data, int resultCode) {
  614. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  615. if (filePaths != null) {
  616. String[] remotePaths = new String[filePaths.length];
  617. String remotePathBase = getCurrentDir().getRemotePath();
  618. for (int j = 0; j < remotePaths.length; j++) {
  619. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  620. }
  621. int behaviour = (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) ? FileUploader
  622. .LOCAL_BEHAVIOUR_MOVE : FileUploader.LOCAL_BEHAVIOUR_COPY;
  623. FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
  624. requester.uploadNewFile(
  625. this,
  626. getAccount(),
  627. filePaths,
  628. remotePaths,
  629. null, // MIME type will be detected from file name
  630. behaviour,
  631. false, // do not create parent folder if not existent
  632. UploadFileOperation.CREATED_BY_USER
  633. );
  634. } else {
  635. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  636. Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected),
  637. Toast.LENGTH_LONG);
  638. t.show();
  639. return;
  640. }
  641. }
  642. private void requestSimpleUpload(final Intent data, int resultCode) {
  643. /* String filePath = null;
  644. String mimeType = null;*/
  645. int behaviour = (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) ? FileUploader.LOCAL_BEHAVIOUR_MOVE :
  646. FileUploader.LOCAL_BEHAVIOUR_COPY;
  647. ArrayList<Parcelable> mStreamsToUpload = new ArrayList<Parcelable>() {{
  648. add(data.getData());
  649. }};
  650. OCFile currentDir = getCurrentDir();
  651. String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
  652. UriUploader uploader = new UriUploader(this,
  653. mStreamsToUpload,
  654. remotePath,
  655. getAccount(),
  656. behaviour);
  657. uploader.uploadUris();
  658. /*Uri selectedFileUri = data.getData();
  659. try {
  660. mimeType = getContentResolver().getType(selectedFileUri);
  661. String fileManagerString = selectedFileUri.getPath();
  662. String selectedFilePath = UriUtils.getLocalPath(selectedFileUri, this);
  663. if (selectedFilePath != null)
  664. filePath = selectedFilePath;
  665. else
  666. filePath = fileManagerString;
  667. } catch (Exception e) {
  668. Log_OC.e(TAG, "Unexpected exception when trying to read the result of " +
  669. "Intent.ACTION_GET_CONTENT", e);
  670. } finally {
  671. if (filePath == null) {
  672. Log_OC.e(TAG, "Couldn't resolve path to file");
  673. Toast t = Toast.makeText(
  674. this, getString(R.string.filedisplay_unexpected_bad_get_content),
  675. Toast.LENGTH_LONG
  676. );
  677. t.show();
  678. return;
  679. }
  680. }*/
  681. /* Uri selectedFileUri = data.getData();
  682. try {
  683. mimeType = getContentResolver().getType(selectedFileUri);
  684. String fileManagerString = selectedFileUri.getPath();
  685. String selectedFilePath = UriUtils.getLocalPath(selectedFileUri, this);
  686. if (selectedFilePath != null)
  687. filePath = selectedFilePath;
  688. else
  689. filePath = fileManagerString;
  690. } catch (Exception e) {
  691. Log_OC.e(TAG, "Unexpected exception when trying to read the result of " +
  692. "Intent.ACTION_GET_CONTENT", e);
  693. } finally {
  694. if (filePath == null) {
  695. Log_OC.e(TAG, "Couldn't resolve path to file");
  696. Toast t = Toast.makeText(
  697. this, getString(R.string.filedisplay_unexpected_bad_get_content),
  698. Toast.LENGTH_LONG
  699. );
  700. t.show();
  701. return;
  702. }
  703. }
  704. Intent i = new Intent(this, FileUploader.class);
  705. i.putExtra(FileUploader.KEY_ACCOUNT,
  706. getAccount());
  707. OCFile currentDir = getCurrentDir();
  708. String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
  709. if (selectedFileUri.toString().startsWith(UriUtils.URI_CONTENT_SCHEME)) {
  710. Cursor cursor = getContentResolver().query(selectedFileUri, null, null, null, null);
  711. try {
  712. if (cursor != null && cursor.moveToFirst()) {
  713. String displayName = cursor.getString(cursor.getColumnIndex(
  714. OpenableColumns.DISPLAY_NAME));
  715. Log_OC.v(TAG, "Display Name: " + displayName);
  716. displayName = displayName.replace(File.separatorChar, '_');
  717. remotePath += displayName;
  718. // Check if extension is not included in file display name and add file extension
  719. int pos = displayName.lastIndexOf('.');
  720. if (pos < 0) {
  721. remotePath += DisplayUtils.getFileExtension(filePath);
  722. }
  723. // URi and remote path parameters
  724. Uri[] uris = new Uri[]{selectedFileUri};
  725. String[] remotePaths = new String[]{remotePath};;
  726. // Call to copy and then upload the selected file
  727. copyThenUpload(uris, remotePaths);
  728. cursor.close();
  729. return;
  730. } else {
  731. Toast.makeText(this, R.string.uploader_error_message_no_file_to_upload,
  732. Toast.LENGTH_SHORT).show();
  733. }
  734. // and what happens in case of error?; wrong target name for the upload
  735. } catch (Exception e) {
  736. Log_OC.e(TAG, "Error while trying to copy and upload a schema type content file ", e);
  737. Toast.makeText(this, R.string.common_error_unknown, Toast.LENGTH_SHORT).show();
  738. }
  739. } else {
  740. remotePath += new File(filePath).getName();
  741. }
  742. int behaviour = (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) ? FileUploader.LOCAL_BEHAVIOUR_MOVE :
  743. FileUploader.LOCAL_BEHAVIOUR_COPY;
  744. FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
  745. requester.uploadNewFile(
  746. this,
  747. getAccount(),
  748. filePath,
  749. remotePath,
  750. behaviour,
  751. mimeType,
  752. false, // do not create parent folder if not existent
  753. UploadFileOperation.CREATED_BY_USER
  754. );*/
  755. }
  756. /**
  757. * Call asyncTask to copy passed files from uris in temporal files
  758. *
  759. * @param sourceUris Array of content:// URIs to the files to upload
  760. * @param remotePaths Array of absolute paths to set to the uploaded files
  761. */
  762. private void copyThenUpload(Uri[] sourceUris, String[] remotePaths) {
  763. CopyAndUploadContentUrisTask copyTask = new CopyAndUploadContentUrisTask(this, getApplicationContext());
  764. copyTask.execute(
  765. CopyAndUploadContentUrisTask.makeParamsToExecute(
  766. getAccount(),
  767. sourceUris,
  768. remotePaths,
  769. getContentResolver()
  770. )
  771. );
  772. }
  773. /**
  774. * Request the operation for moving the file/folder from one path to another
  775. *
  776. * @param data Intent received
  777. * @param resultCode Result code received
  778. */
  779. private void requestMoveOperation(Intent data, int resultCode) {
  780. OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  781. OCFile targetFile = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
  782. getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
  783. }
  784. /**
  785. * Request the operation for copying the file/folder from one path to another
  786. *
  787. * @param data Intent received
  788. * @param resultCode Result code received
  789. */
  790. private void requestCopyOperation(Intent data, int resultCode) {
  791. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  792. OCFile targetFile = data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
  793. getFileOperationsHelper().copyFile(folderToMoveAt, targetFile);
  794. }
  795. @Override
  796. public void onBackPressed() {
  797. boolean isFabOpen = isFabOpen();
  798. boolean isDrawerOpen = isDrawerOpen();
  799. /*
  800. * BackPressed priority/hierarchy:
  801. * 1. close drawer if opened
  802. * 2. close FAB if open (only if drawer isn't open)
  803. * 3. navigate up (only if drawer and FAB aren't open)
  804. */
  805. if(isDrawerOpen && isFabOpen) {
  806. // close drawer first
  807. super.onBackPressed();
  808. } else if(isDrawerOpen && !isFabOpen) {
  809. // close drawer
  810. super.onBackPressed();
  811. } else if (!isDrawerOpen && isFabOpen) {
  812. // close fab
  813. getListOfFilesFragment().getFabMain().collapse();
  814. } else {
  815. // all closed
  816. OCFileListFragment listOfFiles = getListOfFilesFragment();
  817. if (mDualPane || getSecondFragment() == null) {
  818. OCFile currentDir = getCurrentDir();
  819. if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
  820. finish();
  821. return;
  822. }
  823. if (listOfFiles != null) { // should never be null, indeed
  824. listOfFiles.onBrowseUp();
  825. }
  826. }
  827. if (listOfFiles != null) { // should never be null, indeed
  828. setFile(listOfFiles.getCurrentFile());
  829. }
  830. cleanSecondFragment();
  831. }
  832. }
  833. @Override
  834. protected void onSaveInstanceState(Bundle outState) {
  835. // responsibility of restore is preferred in onCreate() before than in
  836. // onRestoreInstanceState when there are Fragments involved
  837. Log_OC.v(TAG, "onSaveInstanceState() start");
  838. super.onSaveInstanceState(outState);
  839. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  840. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  841. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
  842. // mRefreshSharesInProgress);
  843. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  844. Log_OC.v(TAG, "onSaveInstanceState() end");
  845. }
  846. @Override
  847. protected void onResume() {
  848. Log_OC.v(TAG, "onResume() start");
  849. super.onResume();
  850. // refresh Navigation Drawer account list
  851. mNavigationDrawerAdapter.updateAccountList();
  852. // refresh list of files
  853. refreshListOfFilesFragment();
  854. // Listen for sync messages
  855. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  856. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  857. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  858. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  859. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  860. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  861. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  862. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
  863. // syncIntentFilter);
  864. // Listen for upload messages
  865. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  866. mUploadFinishReceiver = new UploadFinishReceiver();
  867. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  868. // Listen for download messages
  869. IntentFilter downloadIntentFilter = new IntentFilter(
  870. FileDownloader.getDownloadAddedMessage());
  871. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  872. mDownloadFinishReceiver = new DownloadFinishReceiver();
  873. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  874. Log_OC.v(TAG, "onResume() end");
  875. }
  876. @Override
  877. protected void onPause() {
  878. Log_OC.v(TAG, "onPause() start");
  879. if (mSyncBroadcastReceiver != null) {
  880. unregisterReceiver(mSyncBroadcastReceiver);
  881. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  882. mSyncBroadcastReceiver = null;
  883. }
  884. if (mUploadFinishReceiver != null) {
  885. unregisterReceiver(mUploadFinishReceiver);
  886. mUploadFinishReceiver = null;
  887. }
  888. if (mDownloadFinishReceiver != null) {
  889. unregisterReceiver(mDownloadFinishReceiver);
  890. mDownloadFinishReceiver = null;
  891. }
  892. super.onPause();
  893. Log_OC.v(TAG, "onPause() end");
  894. }
  895. public boolean isFabOpen() {
  896. if(getListOfFilesFragment() != null
  897. && getListOfFilesFragment().getFabMain() != null
  898. && getListOfFilesFragment().getFabMain().isExpanded()) {
  899. return true;
  900. } else {
  901. return false;
  902. }
  903. }
  904. @Override
  905. public void onTmpFilesCopied(ResultCode result) {
  906. }
  907. private class SyncBroadcastReceiver extends BroadcastReceiver {
  908. /**
  909. * {@link BroadcastReceiver} to enable syncing feedback in UI
  910. */
  911. @Override
  912. public void onReceive(Context context, Intent intent) {
  913. try {
  914. String event = intent.getAction();
  915. Log_OC.d(TAG, "Received broadcast " + event);
  916. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  917. String synchFolderRemotePath =
  918. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  919. RemoteOperationResult synchResult =
  920. (RemoteOperationResult) intent.getSerializableExtra(
  921. FileSyncAdapter.EXTRA_RESULT);
  922. boolean sameAccount = (getAccount() != null &&
  923. accountName.equals(getAccount().name) && getStorageManager() != null);
  924. if (sameAccount) {
  925. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  926. mSyncInProgress = true;
  927. } else {
  928. OCFile currentFile = (getFile() == null) ? null :
  929. getStorageManager().getFileByPath(getFile().getRemotePath());
  930. OCFile currentDir = (getCurrentDir() == null) ? null :
  931. getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  932. if (currentDir == null) {
  933. // current folder was removed from the server
  934. Toast.makeText(FileDisplayActivity.this,
  935. String.format(
  936. getString(R.string.
  937. sync_current_folder_was_removed),
  938. synchFolderRemotePath),
  939. Toast.LENGTH_LONG)
  940. .show();
  941. browseToRoot();
  942. } else {
  943. if (currentFile == null && !getFile().isFolder()) {
  944. // currently selected file was removed in the server, and now we
  945. // know it
  946. cleanSecondFragment();
  947. currentFile = currentDir;
  948. }
  949. if (synchFolderRemotePath != null &&
  950. currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  951. OCFileListFragment fileListFragment = getListOfFilesFragment();
  952. if (fileListFragment != null) {
  953. fileListFragment.listDirectory();
  954. // TODO Enable when "On Device" is recovered ?
  955. // fileListFragment.listDirectory(currentDir,
  956. // MainApp.getOnlyOnDevice());
  957. }
  958. }
  959. setFile(currentFile);
  960. }
  961. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  962. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED
  963. .equals(event));
  964. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
  965. equals(event) &&/// TODO refactor and make common
  966. synchResult != null && !synchResult.isSuccess()) {
  967. if(ResultCode.UNAUTHORIZED.equals(synchResult.getCode()) ||
  968. (synchResult.isException() && synchResult.getException()
  969. instanceof AuthenticatorException)) {
  970. requestCredentialsUpdate(context);
  971. } else if(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(
  972. synchResult.getCode())) {
  973. showUntrustedCertDialog(synchResult);
  974. }
  975. }
  976. }
  977. removeStickyBroadcast(intent);
  978. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  979. mProgressBar.setIndeterminate(mSyncInProgress);
  980. setBackgroundText();
  981. }
  982. if (synchResult != null) {
  983. if (synchResult.getCode().equals(
  984. RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  985. mLastSslUntrustedServerResult = synchResult;
  986. }
  987. }
  988. } catch (RuntimeException e) {
  989. // avoid app crashes after changing the serial id of RemoteOperationResult
  990. // in owncloud library with broadcast notifications pending to process
  991. removeStickyBroadcast(intent);
  992. }
  993. }
  994. }
  995. /**
  996. * Show a text message on screen view for notifying user if content is
  997. * loading or folder is empty
  998. */
  999. private void setBackgroundText() {
  1000. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  1001. if (ocFileListFragment != null) {
  1002. int message = R.string.file_list_loading;
  1003. if (!mSyncInProgress) {
  1004. // In case file list is empty
  1005. message = R.string.file_list_empty;
  1006. }
  1007. ocFileListFragment.setMessageForEmptyList(getString(message));
  1008. } else {
  1009. Log_OC.e(TAG, "OCFileListFragment is null");
  1010. }
  1011. }
  1012. /**
  1013. * Once the file upload has finished -> update view
  1014. */
  1015. private class UploadFinishReceiver extends BroadcastReceiver {
  1016. /**
  1017. * Once the file upload has finished -> update view
  1018. *
  1019. * @author David A. Velasco
  1020. * {@link BroadcastReceiver} to enable upload feedback in UI
  1021. */
  1022. @Override
  1023. public void onReceive(Context context, Intent intent) {
  1024. try {
  1025. String uploadedRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
  1026. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  1027. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  1028. OCFile currentDir = getCurrentDir();
  1029. boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
  1030. (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
  1031. if (sameAccount && isDescendant) {
  1032. String linkedToRemotePath =
  1033. intent.getStringExtra(FileUploader.EXTRA_LINKED_TO_PATH);
  1034. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1035. refreshListOfFilesFragment();
  1036. }
  1037. }
  1038. boolean uploadWasFine = intent.getBooleanExtra(
  1039. FileUploader.EXTRA_UPLOAD_RESULT,
  1040. false);
  1041. boolean renamedInUpload = getFile().getRemotePath().
  1042. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  1043. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  1044. renamedInUpload;
  1045. FileFragment details = getSecondFragment();
  1046. boolean detailFragmentIsShown = (details != null &&
  1047. details instanceof FileDetailFragment);
  1048. if (sameAccount && sameFile && detailFragmentIsShown) {
  1049. if (uploadWasFine) {
  1050. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  1051. } else {
  1052. //TODO remove upload progress bar after upload failed.
  1053. }
  1054. if (renamedInUpload) {
  1055. String newName = (new File(uploadedRemotePath)).getName();
  1056. Toast msg = Toast.makeText(
  1057. context,
  1058. String.format(
  1059. getString(R.string.filedetails_renamed_in_upload_msg),
  1060. newName),
  1061. Toast.LENGTH_LONG);
  1062. msg.show();
  1063. }
  1064. if (uploadWasFine || getFile().fileExists()) {
  1065. ((FileDetailFragment) details).updateFileDetails(false, true);
  1066. } else {
  1067. cleanSecondFragment();
  1068. }
  1069. // Force the preview if the file is an image or text file
  1070. if (uploadWasFine) {
  1071. OCFile ocFile = getFile();
  1072. if (PreviewImageFragment.canBePreviewed(ocFile))
  1073. startImagePreview(getFile());
  1074. else if (PreviewTextFragment.canBePreviewed(ocFile))
  1075. startTextPreview(ocFile);
  1076. // TODO what about other kind of previews?
  1077. }
  1078. }
  1079. mProgressBar.setIndeterminate(false);
  1080. } finally {
  1081. if (intent != null) {
  1082. removeStickyBroadcast(intent);
  1083. }
  1084. }
  1085. }
  1086. // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
  1087. private boolean isAscendant(String linkedToRemotePath) {
  1088. OCFile currentDir = getCurrentDir();
  1089. return (
  1090. currentDir != null &&
  1091. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1092. );
  1093. }
  1094. }
  1095. /**
  1096. * Class waiting for broadcast events from the {@link FileDownloader} service.
  1097. * <p/>
  1098. * Updates the UI when a download is started or finished, provided that it is relevant for the
  1099. * current folder.
  1100. */
  1101. private class DownloadFinishReceiver extends BroadcastReceiver {
  1102. @Override
  1103. public void onReceive(Context context, Intent intent) {
  1104. try {
  1105. boolean sameAccount = isSameAccount(intent);
  1106. String downloadedRemotePath =
  1107. intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  1108. boolean isDescendant = isDescendant(downloadedRemotePath);
  1109. if (sameAccount && isDescendant) {
  1110. String linkedToRemotePath =
  1111. intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
  1112. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1113. refreshListOfFilesFragment();
  1114. }
  1115. refreshSecondFragment(
  1116. intent.getAction(),
  1117. downloadedRemotePath,
  1118. intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false)
  1119. );
  1120. }
  1121. if (mWaitingToSend != null) {
  1122. mWaitingToSend =
  1123. getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
  1124. if (mWaitingToSend.isDown()) {
  1125. sendDownloadedFile();
  1126. }
  1127. }
  1128. } finally {
  1129. if (intent != null) {
  1130. removeStickyBroadcast(intent);
  1131. }
  1132. }
  1133. }
  1134. private boolean isDescendant(String downloadedRemotePath) {
  1135. OCFile currentDir = getCurrentDir();
  1136. return (
  1137. currentDir != null &&
  1138. downloadedRemotePath != null &&
  1139. downloadedRemotePath.startsWith(currentDir.getRemotePath())
  1140. );
  1141. }
  1142. private boolean isAscendant(String linkedToRemotePath) {
  1143. OCFile currentDir = getCurrentDir();
  1144. return (
  1145. currentDir != null &&
  1146. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1147. );
  1148. }
  1149. private boolean isSameAccount(Intent intent) {
  1150. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  1151. return (accountName != null && getAccount() != null &&
  1152. accountName.equals(getAccount().name));
  1153. }
  1154. }
  1155. public void browseToRoot() {
  1156. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1157. if (listOfFiles != null) { // should never be null, indeed
  1158. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  1159. listOfFiles.listDirectory(root);
  1160. // TODO Enable when "On Device" is recovered ?
  1161. // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
  1162. setFile(listOfFiles.getCurrentFile());
  1163. startSyncFolderOperation(root, false);
  1164. }
  1165. cleanSecondFragment();
  1166. }
  1167. /**
  1168. * {@inheritDoc}
  1169. * Updates action bar and second fragment, if in dual pane mode.
  1170. */
  1171. @Override
  1172. public void onBrowsedDownTo(OCFile directory) {
  1173. setFile(directory);
  1174. cleanSecondFragment();
  1175. // Sync Folder
  1176. startSyncFolderOperation(directory, false);
  1177. }
  1178. /**
  1179. * Shows the information of the {@link OCFile} received as a
  1180. * parameter in the second fragment.
  1181. *
  1182. * @param file {@link OCFile} whose details will be shown
  1183. */
  1184. @Override
  1185. public void showDetails(OCFile file) {
  1186. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  1187. setSecondFragment(detailFragment);
  1188. updateFragmentsVisibility(true);
  1189. updateActionBarTitleAndHomeButton(file);
  1190. setFile(file);
  1191. }
  1192. @Override
  1193. protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
  1194. if (mDualPane) {
  1195. // in dual pane mode, keep the focus of title an action bar in the current folder
  1196. super.updateActionBarTitleAndHomeButton(getCurrentDir());
  1197. } else {
  1198. super.updateActionBarTitleAndHomeButton(chosenFile);
  1199. }
  1200. }
  1201. @Override
  1202. protected ServiceConnection newTransferenceServiceConnection() {
  1203. return new ListServiceConnection();
  1204. }
  1205. /**
  1206. * Defines callbacks for service binding, passed to bindService()
  1207. */
  1208. private class ListServiceConnection implements ServiceConnection {
  1209. @Override
  1210. public void onServiceConnected(ComponentName component, IBinder service) {
  1211. if (component.equals(new ComponentName(
  1212. FileDisplayActivity.this, FileDownloader.class))) {
  1213. Log_OC.d(TAG, "Download service connected");
  1214. mDownloaderBinder = (FileDownloaderBinder) service;
  1215. if (mWaitingToPreview != null)
  1216. if (getStorageManager() != null) {
  1217. // update the file
  1218. mWaitingToPreview =
  1219. getStorageManager().getFileById(mWaitingToPreview.getFileId());
  1220. if (!mWaitingToPreview.isDown()) {
  1221. requestForDownload();
  1222. }
  1223. }
  1224. } else if (component.equals(new ComponentName(FileDisplayActivity.this,
  1225. FileUploader.class))) {
  1226. Log_OC.d(TAG, "Upload service connected");
  1227. mUploaderBinder = (FileUploaderBinder) service;
  1228. } else {
  1229. return;
  1230. }
  1231. // a new chance to get the mDownloadBinder through
  1232. // getFileDownloadBinder() - THIS IS A MESS
  1233. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1234. if (listOfFiles != null) {
  1235. listOfFiles.listDirectory();
  1236. // TODO Enable when "On Device" is recovered ?
  1237. // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
  1238. }
  1239. FileFragment secondFragment = getSecondFragment();
  1240. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  1241. FileDetailFragment detailFragment = (FileDetailFragment) secondFragment;
  1242. detailFragment.listenForTransferProgress();
  1243. detailFragment.updateFileDetails(false, false);
  1244. }
  1245. }
  1246. @Override
  1247. public void onServiceDisconnected(ComponentName component) {
  1248. if (component.equals(new ComponentName(FileDisplayActivity.this,
  1249. FileDownloader.class))) {
  1250. Log_OC.d(TAG, "Download service disconnected");
  1251. mDownloaderBinder = null;
  1252. } else if (component.equals(new ComponentName(FileDisplayActivity.this,
  1253. FileUploader.class))) {
  1254. Log_OC.d(TAG, "Upload service disconnected");
  1255. mUploaderBinder = null;
  1256. }
  1257. }
  1258. }
  1259. /**
  1260. * Updates the view associated to the activity after the finish of some operation over files
  1261. * in the current account.
  1262. *
  1263. * @param operation Removal operation performed.
  1264. * @param result Result of the removal.
  1265. */
  1266. @Override
  1267. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1268. super.onRemoteOperationFinish(operation, result);
  1269. if (operation instanceof RemoveFileOperation) {
  1270. onRemoveFileOperationFinish((RemoveFileOperation) operation, result);
  1271. } else if (operation instanceof RenameFileOperation) {
  1272. onRenameFileOperationFinish((RenameFileOperation) operation, result);
  1273. } else if (operation instanceof SynchronizeFileOperation) {
  1274. onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
  1275. } else if (operation instanceof CreateFolderOperation) {
  1276. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  1277. } else if (operation instanceof MoveFileOperation) {
  1278. onMoveFileOperationFinish((MoveFileOperation) operation, result);
  1279. } else if (operation instanceof CopyFileOperation) {
  1280. onCopyFileOperationFinish((CopyFileOperation) operation, result);
  1281. }
  1282. }
  1283. private void refreshShowDetails() {
  1284. FileFragment details = getSecondFragment();
  1285. if (details != null) {
  1286. OCFile file = details.getFile();
  1287. if (file != null) {
  1288. file = getStorageManager().getFileByPath(file.getRemotePath());
  1289. if (details instanceof PreviewMediaFragment) {
  1290. // Refresh OCFile of the fragment
  1291. ((PreviewMediaFragment) details).updateFile(file);
  1292. } else if (details instanceof PreviewTextFragment) {
  1293. // Refresh OCFile of the fragment
  1294. ((PreviewTextFragment) details).updateFile(file);
  1295. } else {
  1296. showDetails(file);
  1297. }
  1298. }
  1299. invalidateOptionsMenu();
  1300. }
  1301. }
  1302. /**
  1303. * Updates the view associated to the activity after the finish of an operation trying to
  1304. * remove a file.
  1305. *
  1306. * @param operation Removal operation performed.
  1307. * @param result Result of the removal.
  1308. */
  1309. private void onRemoveFileOperationFinish(RemoveFileOperation operation,
  1310. RemoteOperationResult result) {
  1311. Toast msg = Toast.makeText(this,
  1312. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1313. Toast.LENGTH_LONG);
  1314. msg.show();
  1315. if (result.isSuccess()) {
  1316. OCFile removedFile = operation.getFile();
  1317. FileFragment second = getSecondFragment();
  1318. if (second != null && removedFile.equals(second.getFile())) {
  1319. if (second instanceof PreviewMediaFragment) {
  1320. ((PreviewMediaFragment) second).stopPreview(true);
  1321. }
  1322. setFile(getStorageManager().getFileById(removedFile.getParentId()));
  1323. cleanSecondFragment();
  1324. }
  1325. if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
  1326. refreshListOfFilesFragment();
  1327. }
  1328. invalidateOptionsMenu();
  1329. } else {
  1330. if (result.isSslRecoverableException()) {
  1331. mLastSslUntrustedServerResult = result;
  1332. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1333. }
  1334. }
  1335. }
  1336. /**
  1337. * Updates the view associated to the activity after the finish of an operation trying to move a
  1338. * file.
  1339. *
  1340. * @param operation Move operation performed.
  1341. * @param result Result of the move operation.
  1342. */
  1343. private void onMoveFileOperationFinish(MoveFileOperation operation,
  1344. RemoteOperationResult result) {
  1345. if (result.isSuccess()) {
  1346. refreshListOfFilesFragment();
  1347. } else {
  1348. try {
  1349. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1350. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1351. Toast.LENGTH_LONG);
  1352. msg.show();
  1353. } catch (NotFoundException e) {
  1354. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1355. }
  1356. }
  1357. }
  1358. /**
  1359. * Updates the view associated to the activity after the finish of an operation trying to copy a
  1360. * file.
  1361. *
  1362. * @param operation Copy operation performed.
  1363. * @param result Result of the copy operation.
  1364. */
  1365. private void onCopyFileOperationFinish(CopyFileOperation operation, RemoteOperationResult result) {
  1366. if (result.isSuccess()) {
  1367. refreshListOfFilesFragment();
  1368. } else {
  1369. try {
  1370. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1371. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1372. Toast.LENGTH_LONG);
  1373. msg.show();
  1374. } catch (NotFoundException e) {
  1375. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1376. }
  1377. }
  1378. }
  1379. /**
  1380. * Updates the view associated to the activity after the finish of an operation trying to rename
  1381. * a file.
  1382. *
  1383. * @param operation Renaming operation performed.
  1384. * @param result Result of the renaming.
  1385. */
  1386. private void onRenameFileOperationFinish(RenameFileOperation operation,
  1387. RemoteOperationResult result) {
  1388. OCFile renamedFile = operation.getFile();
  1389. if (result.isSuccess()) {
  1390. FileFragment details = getSecondFragment();
  1391. if (details != null) {
  1392. if (details instanceof FileDetailFragment &&
  1393. renamedFile.equals(details.getFile())) {
  1394. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1395. showDetails(renamedFile);
  1396. } else if (details instanceof PreviewMediaFragment &&
  1397. renamedFile.equals(details.getFile())) {
  1398. ((PreviewMediaFragment) details).updateFile(renamedFile);
  1399. if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
  1400. int position = ((PreviewMediaFragment) details).getPosition();
  1401. startMediaPreview(renamedFile, position, true);
  1402. } else {
  1403. getFileOperationsHelper().openFile(renamedFile);
  1404. }
  1405. } else if (details instanceof PreviewTextFragment &&
  1406. renamedFile.equals(details.getFile())) {
  1407. ((PreviewTextFragment) details).updateFile(renamedFile);
  1408. if (PreviewTextFragment.canBePreviewed(renamedFile)) {
  1409. startTextPreview(renamedFile);
  1410. } else {
  1411. getFileOperationsHelper().openFile(renamedFile);
  1412. }
  1413. }
  1414. }
  1415. if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
  1416. refreshListOfFilesFragment();
  1417. }
  1418. } else {
  1419. Toast msg = Toast.makeText(this,
  1420. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1421. Toast.LENGTH_LONG);
  1422. msg.show();
  1423. if (result.isSslRecoverableException()) {
  1424. mLastSslUntrustedServerResult = result;
  1425. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1426. }
  1427. }
  1428. }
  1429. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
  1430. RemoteOperationResult result) {
  1431. if (result.isSuccess()) {
  1432. if (operation.transferWasRequested()) {
  1433. OCFile syncedFile = operation.getLocalFile();
  1434. onTransferStateChanged(syncedFile, true, true);
  1435. invalidateOptionsMenu();
  1436. refreshShowDetails();
  1437. }
  1438. }
  1439. }
  1440. /**
  1441. * Updates the view associated to the activity after the finish of an operation trying create a
  1442. * new folder
  1443. *
  1444. * @param operation Creation operation performed.
  1445. * @param result Result of the creation.
  1446. */
  1447. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  1448. RemoteOperationResult result) {
  1449. if (result.isSuccess()) {
  1450. refreshListOfFilesFragment();
  1451. } else {
  1452. try {
  1453. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1454. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1455. Toast.LENGTH_LONG);
  1456. msg.show();
  1457. } catch (NotFoundException e) {
  1458. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1459. }
  1460. }
  1461. }
  1462. /**
  1463. * {@inheritDoc}
  1464. */
  1465. @Override
  1466. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1467. refreshListOfFilesFragment();
  1468. FileFragment details = getSecondFragment();
  1469. if (details != null && details instanceof FileDetailFragment &&
  1470. file.equals(details.getFile())) {
  1471. if (downloading || uploading) {
  1472. ((FileDetailFragment) details).updateFileDetails(file, getAccount());
  1473. } else {
  1474. if (!file.fileExists()) {
  1475. cleanSecondFragment();
  1476. } else {
  1477. ((FileDetailFragment) details).updateFileDetails(false, true);
  1478. }
  1479. }
  1480. }
  1481. }
  1482. private void requestForDownload() {
  1483. Account account = getAccount();
  1484. //if (!mWaitingToPreview.isDownloading()) {
  1485. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1486. Intent i = new Intent(this, FileDownloader.class);
  1487. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1488. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1489. startService(i);
  1490. }
  1491. }
  1492. @Override
  1493. public void onSavedCertificate() {
  1494. startSyncFolderOperation(getCurrentDir(), false);
  1495. }
  1496. /**
  1497. * Starts an operation to refresh the requested folder.
  1498. * <p/>
  1499. * The operation is run in a new background thread created on the fly.
  1500. * <p/>
  1501. * The refresh updates is a "light sync": properties of regular files in folder are updated (including
  1502. * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
  1503. * synchronized too.
  1504. *
  1505. * @param folder Folder to refresh.
  1506. * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
  1507. * didn't change.
  1508. */
  1509. public void startSyncFolderOperation(final OCFile folder, final boolean ignoreETag) {
  1510. // the execution is slightly delayed to allow the activity get the window focus if it's being started
  1511. // or if the method is called from a dialog that is being dismissed
  1512. getHandler().postDelayed(
  1513. new Runnable() {
  1514. @Override
  1515. public void run() {
  1516. if (hasWindowFocus()) {
  1517. long currentSyncTime = System.currentTimeMillis();
  1518. mSyncInProgress = true;
  1519. // perform folder synchronization
  1520. RemoteOperation synchFolderOp = new RefreshFolderOperation(folder,
  1521. currentSyncTime,
  1522. false,
  1523. getFileOperationsHelper().isSharedSupported(),
  1524. ignoreETag,
  1525. getStorageManager(),
  1526. getAccount(),
  1527. getApplicationContext()
  1528. );
  1529. synchFolderOp.execute(
  1530. getAccount(),
  1531. MainApp.getAppContext(),
  1532. FileDisplayActivity.this,
  1533. null,
  1534. null
  1535. );
  1536. mProgressBar.setIndeterminate(true);
  1537. setBackgroundText();
  1538. } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
  1539. // another window floating over
  1540. }
  1541. },
  1542. DELAY_TO_REQUEST_OPERATIONS_LATER
  1543. );
  1544. }
  1545. private void requestForDownload(OCFile file) {
  1546. Account account = getAccount();
  1547. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1548. Intent i = new Intent(this, FileDownloader.class);
  1549. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1550. i.putExtra(FileDownloader.EXTRA_FILE, file);
  1551. startService(i);
  1552. }
  1553. }
  1554. private void sendDownloadedFile() {
  1555. getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
  1556. mWaitingToSend = null;
  1557. }
  1558. /**
  1559. * Requests the download of the received {@link OCFile} , updates the UI
  1560. * to monitor the download progress and prepares the activity to send the file
  1561. * when the download finishes.
  1562. *
  1563. * @param file {@link OCFile} to download and preview.
  1564. */
  1565. public void startDownloadForSending(OCFile file) {
  1566. mWaitingToSend = file;
  1567. requestForDownload(mWaitingToSend);
  1568. boolean hasSecondFragment = (getSecondFragment() != null);
  1569. updateFragmentsVisibility(hasSecondFragment);
  1570. }
  1571. /**
  1572. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1573. *
  1574. * @param file Image {@link OCFile} to show.
  1575. */
  1576. public void startImagePreview(OCFile file) {
  1577. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1578. showDetailsIntent.putExtra(EXTRA_FILE, file);
  1579. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1580. startActivity(showDetailsIntent);
  1581. }
  1582. /**
  1583. * Stars the preview of an already down media {@link OCFile}.
  1584. *
  1585. * @param file Media {@link OCFile} to preview.
  1586. * @param startPlaybackPosition Media position where the playback will be started,
  1587. * in milliseconds.
  1588. * @param autoplay When 'true', the playback will start without user
  1589. * interactions.
  1590. */
  1591. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
  1592. Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition,
  1593. autoplay);
  1594. setSecondFragment(mediaFragment);
  1595. updateFragmentsVisibility(true);
  1596. updateActionBarTitleAndHomeButton(file);
  1597. setFile(file);
  1598. }
  1599. /**
  1600. * Stars the preview of a text file {@link OCFile}.
  1601. *
  1602. * @param file Text {@link OCFile} to preview.
  1603. */
  1604. public void startTextPreview(OCFile file) {
  1605. Bundle args = new Bundle();
  1606. args.putParcelable(EXTRA_FILE, file);
  1607. args.putParcelable(EXTRA_ACCOUNT, getAccount());
  1608. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  1609. PreviewTextFragment.class.getName(), args);
  1610. setSecondFragment(textPreviewFragment);
  1611. updateFragmentsVisibility(true);
  1612. //updateNavigationElementsInActionBar(file);
  1613. setFile(file);
  1614. }
  1615. /**
  1616. * Requests the download of the received {@link OCFile} , updates the UI
  1617. * to monitor the download progress and prepares the activity to preview
  1618. * or open the file when the download finishes.
  1619. *
  1620. * @param file {@link OCFile} to download and preview.
  1621. */
  1622. public void startDownloadForPreview(OCFile file) {
  1623. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  1624. setSecondFragment(detailFragment);
  1625. mWaitingToPreview = file;
  1626. requestForDownload();
  1627. updateFragmentsVisibility(true);
  1628. updateActionBarTitleAndHomeButton(file);
  1629. setFile(file);
  1630. }
  1631. public void cancelTransference(OCFile file) {
  1632. getFileOperationsHelper().cancelTransference(file);
  1633. if (mWaitingToPreview != null &&
  1634. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  1635. mWaitingToPreview = null;
  1636. }
  1637. if (mWaitingToSend != null &&
  1638. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  1639. mWaitingToSend = null;
  1640. }
  1641. onTransferStateChanged(file, false, false);
  1642. }
  1643. @Override
  1644. public void onRefresh(boolean ignoreETag) {
  1645. refreshList(ignoreETag);
  1646. }
  1647. @Override
  1648. public void onRefresh() {
  1649. refreshList(true);
  1650. }
  1651. private void refreshList(boolean ignoreETag) {
  1652. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1653. if (listOfFiles != null) {
  1654. OCFile folder = listOfFiles.getCurrentFile();
  1655. if (folder != null) {
  1656. /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
  1657. listDirectory(mFile);*/
  1658. startSyncFolderOperation(folder, ignoreETag);
  1659. }
  1660. }
  1661. }
  1662. private void sortByDate(boolean ascending) {
  1663. getListOfFilesFragment().sortByDate(ascending);
  1664. }
  1665. private void sortBySize(boolean ascending) {
  1666. getListOfFilesFragment().sortBySize(ascending);
  1667. }
  1668. private void sortByName(boolean ascending) {
  1669. getListOfFilesFragment().sortByName(ascending);
  1670. }
  1671. private boolean isGridView() {
  1672. return getListOfFilesFragment().isGridView();
  1673. }
  1674. public void allFilesOption() {
  1675. browseToRoot();
  1676. }
  1677. }