FileDisplayActivity.java 112 KB

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