FileDisplayActivity.java 91 KB

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