FileDisplayActivity.java 111 KB

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