FileDisplayActivity.java 107 KB

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