FileDisplayActivity.java 77 KB

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