FileDisplayActivity.java 100 KB

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