FileDisplayActivity.java 82 KB

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