FileDisplayActivity.java 105 KB

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