FileDisplayActivity.java 75 KB

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