FileDisplayActivity.java 109 KB

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