FileDisplayActivity.java 83 KB

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