FileDisplayActivity.java 111 KB

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