FileDisplayActivity.java 78 KB

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