FileDisplayActivity.java 107 KB

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