FileDisplayActivity.java 105 KB

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