FileDisplayActivity.java 108 KB

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