FileDisplayActivity.java 87 KB

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