FileDisplayActivity.java 105 KB

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