FileDisplayActivity.java 102 KB

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