FileDisplayActivity.java 106 KB

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