FileDisplayActivity.java 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489
  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. mWaitingToPreview = getStorageManager().getFileById(
  631. mWaitingToPreview.getFileId()); // update the file from database,
  632. // for the local storage path
  633. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  634. startMediaPreview(mWaitingToPreview, 0, true, true);
  635. detailsFragmentChanged = true;
  636. } else if (MimeTypeUtil.isVCard(mWaitingToPreview.getMimeType())) {
  637. startContactListFragment(mWaitingToPreview);
  638. detailsFragmentChanged = true;
  639. } else if (PreviewTextFragment.canBePreviewed(mWaitingToPreview)) {
  640. startTextPreview(mWaitingToPreview, true);
  641. detailsFragmentChanged = true;
  642. } else {
  643. getFileOperationsHelper().openFile(mWaitingToPreview);
  644. }
  645. }
  646. mWaitingToPreview = null;
  647. }
  648. if (!detailsFragmentChanged) {
  649. detailsFragment.updateFileDetails(false, (success));
  650. }
  651. }
  652. }
  653. }
  654. @Override
  655. public boolean onPrepareOptionsMenu(Menu menu) {
  656. boolean drawerOpen = isDrawerOpen();
  657. for (MenuItem menuItem : mDrawerMenuItemstoShowHideList) {
  658. menuItem.setVisible(!drawerOpen);
  659. }
  660. return super.onPrepareOptionsMenu(menu);
  661. }
  662. @Override
  663. public boolean onCreateOptionsMenu(Menu menu) {
  664. MenuInflater inflater = getMenuInflater();
  665. inflater.inflate(R.menu.main_menu, menu);
  666. menu.findItem(R.id.action_create_dir).setVisible(false);
  667. menu.findItem(R.id.action_select_all).setVisible(false);
  668. final MenuItem item = menu.findItem(R.id.action_search);
  669. searchView = (SearchView) MenuItemCompat.getActionView(item);
  670. // hacky as no default way is provided
  671. int fontColor = ThemeUtils.fontColor(this);
  672. EditText editText = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
  673. editText.setHintTextColor(fontColor);
  674. editText.setTextColor(fontColor);
  675. ImageView searchClose = searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
  676. searchClose.setColorFilter(ThemeUtils.fontColor(this));
  677. // populate list of menu items to show/hide when drawer is opened/closed
  678. mDrawerMenuItemstoShowHideList = new ArrayList<>(4);
  679. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_sort));
  680. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_sync_account));
  681. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_switch_view));
  682. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_search));
  683. //focus the SearchView
  684. if (!TextUtils.isEmpty(searchQuery)) {
  685. searchView.post(new Runnable() {
  686. @Override
  687. public void run() {
  688. searchView.setIconified(false);
  689. searchView.setQuery(searchQuery, true);
  690. searchView.clearFocus();
  691. }
  692. });
  693. }
  694. final View mSearchEditFrame = searchView
  695. .findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
  696. searchView.setOnCloseListener(new SearchView.OnCloseListener() {
  697. @Override
  698. public boolean onClose() {
  699. if (TextUtils.isEmpty(searchView.getQuery().toString())) {
  700. searchView.onActionViewCollapsed();
  701. setDrawerIndicatorEnabled(isDrawerIndicatorAvailable()); // order matters
  702. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  703. mDrawerToggle.syncState();
  704. if (getListOfFilesFragment() != null) {
  705. getListOfFilesFragment().setSearchFragment(false);
  706. getListOfFilesFragment().refreshDirectory();
  707. }
  708. } else {
  709. searchView.post(new Runnable() {
  710. @Override
  711. public void run() {
  712. searchView.setQuery("", true);
  713. }
  714. });
  715. }
  716. return true;
  717. }
  718. });
  719. ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
  720. vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  721. int oldVisibility = -1;
  722. @Override
  723. public void onGlobalLayout() {
  724. int currentVisibility = mSearchEditFrame.getVisibility();
  725. if (currentVisibility != oldVisibility) {
  726. if (currentVisibility == View.VISIBLE) {
  727. setDrawerIndicatorEnabled(false);
  728. }
  729. oldVisibility = currentVisibility;
  730. }
  731. }
  732. });
  733. return true;
  734. }
  735. @Override
  736. public boolean onOptionsItemSelected(MenuItem item) {
  737. boolean retval = true;
  738. switch (item.getItemId()) {
  739. case R.id.action_sync_account: {
  740. startSynchronization();
  741. break;
  742. }
  743. case android.R.id.home: {
  744. FileFragment second = getSecondFragment();
  745. OCFile currentDir = getCurrentDir();
  746. if (isDrawerOpen()) {
  747. closeDrawer();
  748. } else if ((currentDir != null && currentDir.getParentId() != 0) ||
  749. (second != null && second.getFile() != null) || isSearchOpen()) {
  750. onBackPressed();
  751. } else {
  752. openDrawer();
  753. }
  754. break;
  755. }
  756. case R.id.action_sort: {
  757. FragmentManager fm = getSupportFragmentManager();
  758. FragmentTransaction ft = fm.beginTransaction();
  759. ft.addToBackStack(null);
  760. SortingOrderDialogFragment mSortingOrderDialogFragment = SortingOrderDialogFragment.newInstance(
  761. getSortOrder(this, getListOfFilesFragment().getCurrentFile()));
  762. mSortingOrderDialogFragment.show(ft, SortingOrderDialogFragment.SORTING_ORDER_FRAGMENT);
  763. break;
  764. }
  765. case R.id.action_switch_view: {
  766. if (isGridView()) {
  767. item.setTitle(getString(R.string.action_switch_grid_view));
  768. item.setIcon(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_view_module));
  769. getListOfFilesFragment().setListAsPreferred();
  770. } else {
  771. item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
  772. item.setIcon(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_view_list));
  773. getListOfFilesFragment().setGridAsPreferred();
  774. }
  775. break;
  776. }
  777. case R.id.action_select_all: {
  778. getListOfFilesFragment().selectAllFiles(true);
  779. break;
  780. }
  781. default:
  782. retval = super.onOptionsItemSelected(item);
  783. break;
  784. }
  785. return retval;
  786. }
  787. private void startSynchronization() {
  788. Log_OC.d(TAG, "Got to start sync");
  789. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  790. Log_OC.d(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  791. ContentResolver.cancelSync(null, MainApp.getAuthority());
  792. // cancel the current synchronizations of any ownCloud account
  793. Bundle bundle = new Bundle();
  794. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  795. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  796. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  797. MainApp.getAuthority());
  798. ContentResolver.requestSync(
  799. getAccount(),
  800. MainApp.getAuthority(), bundle);
  801. } else {
  802. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  803. MainApp.getAuthority() + " with new API");
  804. SyncRequest.Builder builder = new SyncRequest.Builder();
  805. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  806. builder.setExpedited(true);
  807. builder.setManual(true);
  808. builder.syncOnce();
  809. // Fix bug in Android Lollipop when you click on refresh the whole account
  810. Bundle extras = new Bundle();
  811. builder.setExtras(extras);
  812. SyncRequest request = builder.build();
  813. ContentResolver.requestSync(request);
  814. }
  815. }
  816. /**
  817. * Called, when the user selected something for uploading
  818. */
  819. @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  820. @Override
  821. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  822. if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS &&
  823. (resultCode == RESULT_OK ||
  824. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  825. requestUploadOfContentFromApps(data, resultCode);
  826. } else if (requestCode == REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM &&
  827. (resultCode == RESULT_OK ||
  828. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE ||
  829. resultCode == UploadFilesActivity.RESULT_OK_AND_DO_NOTHING ||
  830. resultCode == UploadFilesActivity.RESULT_OK_AND_DELETE)) {
  831. requestUploadOfFilesFromFileSystem(data, resultCode);
  832. } else if (requestCode == REQUEST_CODE__MOVE_FILES && resultCode == RESULT_OK) {
  833. final Intent fData = data;
  834. getHandler().postDelayed(
  835. new Runnable() {
  836. @Override
  837. public void run() {
  838. requestMoveOperation(fData);
  839. }
  840. },
  841. DELAY_TO_REQUEST_OPERATIONS_LATER
  842. );
  843. } else if (requestCode == REQUEST_CODE__COPY_FILES && resultCode == RESULT_OK) {
  844. final Intent fData = data;
  845. getHandler().postDelayed(
  846. new Runnable() {
  847. @Override
  848. public void run() {
  849. requestCopyOperation(fData);
  850. }
  851. },
  852. DELAY_TO_REQUEST_OPERATIONS_LATER
  853. );
  854. } else {
  855. super.onActivityResult(requestCode, resultCode, data);
  856. }
  857. }
  858. private void requestUploadOfFilesFromFileSystem(Intent data, int resultCode) {
  859. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  860. if (filePaths != null) {
  861. String[] remotePaths = new String[filePaths.length];
  862. String remotePathBase = getCurrentDir().getRemotePath();
  863. for (int j = 0; j < remotePaths.length; j++) {
  864. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  865. }
  866. // default, as fallback
  867. int behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET;
  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. }
  879. FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
  880. requester.uploadNewFile(
  881. this,
  882. getAccount(),
  883. filePaths,
  884. remotePaths,
  885. null, // MIME type will be detected from file name
  886. behaviour,
  887. false, // do not create parent folder if not existent
  888. UploadFileOperation.CREATED_BY_USER,
  889. false,
  890. false
  891. );
  892. } else {
  893. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  894. DisplayUtils.showSnackMessage(this, R.string.filedisplay_no_file_selected);
  895. }
  896. }
  897. private void requestUploadOfContentFromApps(Intent contentIntent, int resultCode) {
  898. ArrayList<Parcelable> streamsToUpload = new ArrayList<>();
  899. //getClipData is only supported on api level 16+, Jelly Bean
  900. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN &&
  901. contentIntent.getClipData() != null &&
  902. contentIntent.getClipData().getItemCount() > 0) {
  903. for (int i = 0; i < contentIntent.getClipData().getItemCount(); i++) {
  904. streamsToUpload.add(contentIntent.getClipData().getItemAt(i).getUri());
  905. }
  906. } else {
  907. streamsToUpload.add(contentIntent.getData());
  908. }
  909. int behaviour = (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) ? FileUploader.LOCAL_BEHAVIOUR_MOVE :
  910. FileUploader.LOCAL_BEHAVIOUR_COPY;
  911. OCFile currentDir = getCurrentDir();
  912. String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
  913. UriUploader uploader = new UriUploader(
  914. this,
  915. streamsToUpload,
  916. remotePath,
  917. getAccount(),
  918. behaviour,
  919. false, // Not show waiting dialog while file is being copied from private storage
  920. null // Not needed copy temp task listener
  921. );
  922. uploader.uploadUris();
  923. }
  924. /**
  925. * Request the operation for moving the file/folder from one path to another
  926. *
  927. * @param data Intent received
  928. */
  929. private void requestMoveOperation(Intent data) {
  930. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  931. ArrayList<OCFile> files = data.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  932. getFileOperationsHelper().moveFiles(files, folderToMoveAt);
  933. }
  934. /**
  935. * Request the operation for copying the file/folder from one path to another
  936. *
  937. * @param data Intent received
  938. */
  939. private void requestCopyOperation(Intent data) {
  940. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  941. ArrayList<OCFile> files = data.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  942. getFileOperationsHelper().copyFiles(files, folderToMoveAt);
  943. }
  944. private boolean isSearchOpen() {
  945. if (searchView == null) {
  946. return false;
  947. } else {
  948. View mSearchEditFrame = searchView.findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
  949. return (mSearchEditFrame != null && mSearchEditFrame.getVisibility() == View.VISIBLE);
  950. }
  951. }
  952. private void revertBottomNavigationBarToAllFiles() {
  953. if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
  954. BottomNavigationView bottomNavigationView = getListOfFilesFragment().getView()
  955. .findViewById(R.id.bottom_navigation_view);
  956. if (bottomNavigationView.getMenu().findItem(R.id.nav_bar_settings).isChecked()) {
  957. bottomNavigationView.getMenu().findItem(R.id.nav_bar_files).setChecked(true);
  958. }
  959. }
  960. }
  961. @Override
  962. public void onBackPressed() {
  963. boolean isDrawerOpen = isDrawerOpen();
  964. boolean isSearchOpen = isSearchOpen();
  965. /*
  966. * BackPressed priority/hierarchy:
  967. * 1. close search view if opened
  968. * 2. close drawer if opened
  969. * 3. close FAB if open (only if drawer isn't open)
  970. * 4. navigate up (only if drawer and FAB aren't open)
  971. */
  972. if (isSearchOpen && searchView != null) {
  973. searchView.setQuery("", true);
  974. searchView.onActionViewCollapsed();
  975. setDrawerIndicatorEnabled(isDrawerIndicatorAvailable());
  976. } else if (isDrawerOpen) {
  977. // close drawer first
  978. super.onBackPressed();
  979. } else {
  980. // all closed
  981. //if PreviewImageActivity called this activity and mDualPane==false then calls PreviewImageActivity again
  982. if ((getIntent().getAction() != null && getIntent().getAction().equalsIgnoreCase(ACTION_DETAILS)) && !mDualPane) {
  983. getIntent().setAction(null);
  984. getIntent().putExtra(EXTRA_FILE, (OCFile) null);
  985. startImagePreview(getFile(), false);
  986. }
  987. OCFileListFragment listOfFiles = getListOfFilesFragment();
  988. if (mDualPane || getSecondFragment() == null) {
  989. OCFile currentDir = getCurrentDir();
  990. if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
  991. finish();
  992. return;
  993. }
  994. if (listOfFiles != null) { // should never be null, indeed
  995. listOfFiles.onBrowseUp();
  996. }
  997. }
  998. if (listOfFiles != null) { // should never be null, indeed
  999. setFile(listOfFiles.getCurrentFile());
  1000. }
  1001. cleanSecondFragment();
  1002. }
  1003. }
  1004. @Override
  1005. protected void onSaveInstanceState(Bundle outState) {
  1006. // responsibility of restore is preferred in onCreate() before than in
  1007. // onRestoreInstanceState when there are Fragments involved
  1008. Log_OC.v(TAG, "onSaveInstanceState() start");
  1009. super.onSaveInstanceState(outState);
  1010. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  1011. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  1012. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
  1013. // mRefreshSharesInProgress);
  1014. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  1015. if (searchView != null) {
  1016. outState.putString(KEY_SEARCH_QUERY, searchView.getQuery().toString());
  1017. }
  1018. Log_OC.v(TAG, "onSaveInstanceState() end");
  1019. }
  1020. @Override
  1021. protected void onResume() {
  1022. Log_OC.v(TAG, "onResume() start");
  1023. super.onResume();
  1024. OCFile startFile = null;
  1025. if (getIntent() != null && getIntent().getParcelableExtra(EXTRA_FILE) != null) {
  1026. startFile = getIntent().getParcelableExtra(EXTRA_FILE);
  1027. setFile(startFile);
  1028. }
  1029. revertBottomNavigationBarToAllFiles();
  1030. // refresh list of files
  1031. if (searchView != null && !TextUtils.isEmpty(searchQuery)) {
  1032. searchView.setQuery(searchQuery, true);
  1033. } else if (getListOfFilesFragment() != null && !getListOfFilesFragment().isSearchFragment()
  1034. && startFile == null) {
  1035. refreshListOfFilesFragment(false);
  1036. } else {
  1037. getListOfFilesFragment().listDirectory(startFile, false, false);
  1038. updateActionBarTitleAndHomeButton(startFile);
  1039. }
  1040. // Listen for sync messages
  1041. if (getListOfFilesFragment() != null && !getListOfFilesFragment().isSearchFragment()) {
  1042. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  1043. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  1044. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  1045. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  1046. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  1047. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  1048. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  1049. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
  1050. // syncIntentFilter);
  1051. }
  1052. // Listen for upload messages
  1053. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  1054. mUploadFinishReceiver = new UploadFinishReceiver();
  1055. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  1056. // Listen for download messages
  1057. IntentFilter downloadIntentFilter = new IntentFilter(
  1058. FileDownloader.getDownloadAddedMessage());
  1059. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  1060. mDownloadFinishReceiver = new DownloadFinishReceiver();
  1061. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  1062. Log_OC.v(TAG, "onResume() end");
  1063. }
  1064. @Override
  1065. protected void onPause() {
  1066. Log_OC.v(TAG, "onPause() start");
  1067. if (mSyncBroadcastReceiver != null) {
  1068. unregisterReceiver(mSyncBroadcastReceiver);
  1069. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  1070. mSyncBroadcastReceiver = null;
  1071. }
  1072. if (mUploadFinishReceiver != null) {
  1073. unregisterReceiver(mUploadFinishReceiver);
  1074. mUploadFinishReceiver = null;
  1075. }
  1076. if (mDownloadFinishReceiver != null) {
  1077. unregisterReceiver(mDownloadFinishReceiver);
  1078. mDownloadFinishReceiver = null;
  1079. }
  1080. super.onPause();
  1081. Log_OC.v(TAG, "onPause() end");
  1082. }
  1083. @Override
  1084. public void onSortingOrderChosen(FileSortOrder selection) {
  1085. getListOfFilesFragment().sortFiles(selection);
  1086. }
  1087. @Override
  1088. public void downloadFile(OCFile file, String packageName, String activityName) {
  1089. startDownloadForSending(file, OCFileListFragment.DOWNLOAD_SEND, packageName, activityName);
  1090. }
  1091. private class SyncBroadcastReceiver extends BroadcastReceiver {
  1092. /**
  1093. * {@link BroadcastReceiver} to enable syncing feedback in UI
  1094. */
  1095. @Override
  1096. public void onReceive(Context context, Intent intent) {
  1097. try {
  1098. String event = intent.getAction();
  1099. Log_OC.d(TAG, "Received broadcast " + event);
  1100. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  1101. String synchFolderRemotePath =
  1102. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  1103. RemoteOperationResult synchResult = (RemoteOperationResult)
  1104. DataHolderUtil.getInstance().retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1105. boolean sameAccount = (getAccount() != null &&
  1106. accountName.equals(getAccount().name) && getStorageManager() != null);
  1107. if (sameAccount) {
  1108. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  1109. mSyncInProgress = true;
  1110. } else {
  1111. OCFile currentFile = (getFile() == null) ? null :
  1112. getStorageManager().getFileByPath(getFile().getRemotePath());
  1113. OCFile currentDir = (getCurrentDir() == null) ? null :
  1114. getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  1115. if (currentDir == null) {
  1116. // current folder was removed from the server
  1117. DisplayUtils.showSnackMessage(
  1118. getActivity(),
  1119. R.string.sync_current_folder_was_removed,
  1120. synchFolderRemotePath
  1121. );
  1122. browseToRoot();
  1123. } else {
  1124. if (currentFile == null && !getFile().isFolder()) {
  1125. // currently selected file was removed in the server, and now we
  1126. // know it
  1127. cleanSecondFragment();
  1128. currentFile = currentDir;
  1129. }
  1130. if (currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  1131. OCFileListFragment fileListFragment = getListOfFilesFragment();
  1132. if (fileListFragment != null) {
  1133. fileListFragment.listDirectory(currentDir, MainApp.isOnlyOnDevice(), false);
  1134. }
  1135. }
  1136. setFile(currentFile);
  1137. }
  1138. mSyncInProgress = !FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  1139. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event);
  1140. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.equals(event) &&
  1141. synchResult != null && !synchResult.isSuccess()) {
  1142. /// TODO refactor and make common
  1143. if (checkForRemoteOperationError(synchResult)) {
  1144. requestCredentialsUpdate(context);
  1145. } else if (RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(
  1146. synchResult.getCode())) {
  1147. showUntrustedCertDialog(synchResult);
  1148. }
  1149. }
  1150. removeStickyBroadcast(intent);
  1151. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1152. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  1153. setIndeterminate(mSyncInProgress);
  1154. setBackgroundText();
  1155. }
  1156. }
  1157. if (synchResult != null && synchResult.getCode().equals(
  1158. RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  1159. mLastSslUntrustedServerResult = synchResult;
  1160. }
  1161. } catch (RuntimeException e) {
  1162. // avoid app crashes after changing the serial id of RemoteOperationResult
  1163. // in owncloud library with broadcast notifications pending to process
  1164. removeStickyBroadcast(intent);
  1165. try {
  1166. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1167. } catch (RuntimeException re) {
  1168. // we did not send this intent, so ignoring
  1169. Log_OC.i(TAG, "Ignoring error deleting data");
  1170. }
  1171. }
  1172. }
  1173. }
  1174. private boolean checkForRemoteOperationError(RemoteOperationResult syncResult) {
  1175. return ResultCode.UNAUTHORIZED.equals(syncResult.getCode()) ||
  1176. (syncResult.isException() && syncResult.getException()
  1177. instanceof AuthenticatorException);
  1178. }
  1179. /**
  1180. * Show a text message on screen view for notifying user if content is
  1181. * loading or folder is empty
  1182. */
  1183. private void setBackgroundText() {
  1184. final OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  1185. if (ocFileListFragment != null) {
  1186. if (mSyncInProgress) {
  1187. ocFileListFragment.setEmptyListLoadingMessage();
  1188. } else {
  1189. ocFileListFragment.setEmptyListMessage(ExtendedListFragment.SearchType.NO_SEARCH);
  1190. }
  1191. } else {
  1192. Log_OC.e(TAG, "OCFileListFragment is null");
  1193. }
  1194. }
  1195. /**
  1196. * Once the file upload has finished -> update view
  1197. */
  1198. private class UploadFinishReceiver extends BroadcastReceiver {
  1199. /**
  1200. * Once the file upload has finished -> update view
  1201. *
  1202. * {@link BroadcastReceiver} to enable upload feedback in UI
  1203. */
  1204. @Override
  1205. public void onReceive(Context context, Intent intent) {
  1206. try {
  1207. String uploadedRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
  1208. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  1209. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  1210. OCFile currentDir = getCurrentDir();
  1211. boolean isDescendant = currentDir != null && uploadedRemotePath != null &&
  1212. uploadedRemotePath.startsWith(currentDir.getRemotePath());
  1213. if (sameAccount && isDescendant) {
  1214. String linkedToRemotePath =
  1215. intent.getStringExtra(FileUploader.EXTRA_LINKED_TO_PATH);
  1216. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1217. refreshListOfFilesFragment(false);
  1218. }
  1219. }
  1220. boolean uploadWasFine = intent.getBooleanExtra(
  1221. FileUploader.EXTRA_UPLOAD_RESULT,
  1222. false);
  1223. boolean renamedInUpload = getFile().getRemotePath().
  1224. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  1225. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  1226. renamedInUpload;
  1227. FileFragment details = getSecondFragment();
  1228. boolean detailFragmentIsShown = (details instanceof FileDetailFragment);
  1229. if (sameAccount && sameFile && detailFragmentIsShown) {
  1230. if (uploadWasFine) {
  1231. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  1232. } else {
  1233. //TODO remove upload progress bar after upload failed.
  1234. Log_OC.d(TAG, "Remove upload progress bar after upload failed");
  1235. }
  1236. if (renamedInUpload) {
  1237. String newName = (new File(uploadedRemotePath)).getName();
  1238. DisplayUtils.showSnackMessage(
  1239. getActivity(),
  1240. R.string.filedetails_renamed_in_upload_msg,
  1241. newName
  1242. );
  1243. }
  1244. if (uploadWasFine || getFile().fileExists()) {
  1245. ((FileDetailFragment) details).updateFileDetails(false, true);
  1246. } else {
  1247. cleanSecondFragment();
  1248. }
  1249. // Force the preview if the file is an image or text file
  1250. if (uploadWasFine) {
  1251. OCFile ocFile = getFile();
  1252. if (PreviewImageFragment.canBePreviewed(ocFile)) {
  1253. startImagePreview(getFile(), true);
  1254. } else if (PreviewTextFragment.canBePreviewed(ocFile)) {
  1255. startTextPreview(ocFile, true);
  1256. }
  1257. // TODO what about other kind of previews?
  1258. }
  1259. }
  1260. setIndeterminate(false);
  1261. } finally {
  1262. if (intent != null) {
  1263. removeStickyBroadcast(intent);
  1264. }
  1265. }
  1266. }
  1267. // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
  1268. private boolean isAscendant(String linkedToRemotePath) {
  1269. OCFile currentDir = getCurrentDir();
  1270. return (
  1271. currentDir != null &&
  1272. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1273. );
  1274. }
  1275. }
  1276. /**
  1277. * Class waiting for broadcast events from the {@link FileDownloader} service.
  1278. *
  1279. * Updates the UI when a download is started or finished, provided that it is relevant for the
  1280. * current folder.
  1281. */
  1282. private class DownloadFinishReceiver extends BroadcastReceiver {
  1283. @Override
  1284. public void onReceive(Context context, Intent intent) {
  1285. try {
  1286. boolean sameAccount = isSameAccount(intent);
  1287. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  1288. String downloadBehaviour = intent.getStringExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR);
  1289. boolean isDescendant = isDescendant(downloadedRemotePath);
  1290. if (sameAccount && isDescendant) {
  1291. String linkedToRemotePath = intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
  1292. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1293. refreshListOfFilesFragment(false);
  1294. }
  1295. refreshSecondFragment(
  1296. intent.getAction(),
  1297. downloadedRemotePath,
  1298. intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
  1299. }
  1300. if (mWaitingToSend != null) {
  1301. mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
  1302. if (mWaitingToSend.isDown() && downloadBehaviour != null) {
  1303. switch (downloadBehaviour) {
  1304. case OCFileListFragment.DOWNLOAD_SEND:
  1305. String packageName = intent.getStringExtra(SendShareDialog.PACKAGE_NAME);
  1306. String activityName = intent.getStringExtra(SendShareDialog.ACTIVITY_NAME);
  1307. sendDownloadedFile(packageName, activityName);
  1308. break;
  1309. default:
  1310. // do nothing
  1311. break;
  1312. }
  1313. }
  1314. }
  1315. } finally {
  1316. if (intent != null) {
  1317. removeStickyBroadcast(intent);
  1318. }
  1319. }
  1320. }
  1321. private boolean isDescendant(String downloadedRemotePath) {
  1322. OCFile currentDir = getCurrentDir();
  1323. return (
  1324. currentDir != null &&
  1325. downloadedRemotePath != null &&
  1326. downloadedRemotePath.startsWith(currentDir.getRemotePath())
  1327. );
  1328. }
  1329. private boolean isAscendant(String linkedToRemotePath) {
  1330. OCFile currentDir = getCurrentDir();
  1331. return (
  1332. currentDir != null &&
  1333. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1334. );
  1335. }
  1336. private boolean isSameAccount(Intent intent) {
  1337. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  1338. return (accountName != null && getAccount() != null &&
  1339. accountName.equals(getAccount().name));
  1340. }
  1341. }
  1342. public void browseToRoot() {
  1343. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1344. if (listOfFiles != null) { // should never be null, indeed
  1345. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  1346. listOfFiles.listDirectory(root, MainApp.isOnlyOnDevice(), false);
  1347. setFile(listOfFiles.getCurrentFile());
  1348. startSyncFolderOperation(root, false);
  1349. }
  1350. cleanSecondFragment();
  1351. }
  1352. /**
  1353. * {@inheritDoc}
  1354. * Updates action bar and second fragment, if in dual pane mode.
  1355. */
  1356. @Override
  1357. public void onBrowsedDownTo(OCFile directory) {
  1358. setFile(directory);
  1359. cleanSecondFragment();
  1360. // Sync Folder
  1361. startSyncFolderOperation(directory, false);
  1362. }
  1363. /**
  1364. * Shows the information of the {@link OCFile} received as a
  1365. * parameter in the second fragment.
  1366. *
  1367. * @param file {@link OCFile} whose details will be shown
  1368. */
  1369. @Override
  1370. public void showDetails(OCFile file) {
  1371. showDetails(file, 0);
  1372. }
  1373. /**
  1374. * Shows the information of the {@link OCFile} received as a
  1375. * parameter in the second fragment.
  1376. *
  1377. * @param file {@link OCFile} whose details will be shown
  1378. * @param activeTab the active tab in the details view
  1379. */
  1380. public void showDetails(OCFile file, int activeTab) {
  1381. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount(), activeTab);
  1382. setSecondFragment(detailFragment);
  1383. updateFragmentsVisibility(true);
  1384. updateActionBarTitleAndHomeButton(file);
  1385. setFile(file);
  1386. }
  1387. @Override
  1388. protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
  1389. if (chosenFile == null) {
  1390. chosenFile = getFile(); // if no file is passed, current file decides
  1391. }
  1392. if (mDualPane) {
  1393. // in dual pane mode, keep the focus of title an action bar in the current folder
  1394. super.updateActionBarTitleAndHomeButton(getCurrentDir());
  1395. } else {
  1396. super.updateActionBarTitleAndHomeButton(chosenFile);
  1397. }
  1398. }
  1399. @Override
  1400. public boolean isDrawerIndicatorAvailable() {
  1401. return isRoot(getCurrentDir());
  1402. }
  1403. @Override
  1404. protected ServiceConnection newTransferenceServiceConnection() {
  1405. return new ListServiceConnection();
  1406. }
  1407. /**
  1408. * Defines callbacks for service binding, passed to bindService()
  1409. */
  1410. private class ListServiceConnection implements ServiceConnection {
  1411. @Override
  1412. public void onServiceConnected(ComponentName component, IBinder service) {
  1413. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1414. Log_OC.d(TAG, "Download service connected");
  1415. mDownloaderBinder = (FileDownloaderBinder) service;
  1416. if (mWaitingToPreview != null && getStorageManager() != null) {
  1417. // update the file
  1418. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId());
  1419. if (mWaitingToPreview != null && !mWaitingToPreview.isDown()) {
  1420. requestForDownload();
  1421. }
  1422. }
  1423. } else if (component.equals(new ComponentName(FileDisplayActivity.this,
  1424. FileUploader.class))) {
  1425. Log_OC.d(TAG, "Upload service connected");
  1426. mUploaderBinder = (FileUploaderBinder) service;
  1427. } else {
  1428. return;
  1429. }
  1430. // a new chance to get the mDownloadBinder through
  1431. // getFileDownloadBinder() - THIS IS A MESS
  1432. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1433. if (listOfFiles != null && (getIntent() == null ||
  1434. (getIntent() != null && getIntent().getParcelableExtra(EXTRA_FILE) == null))) {
  1435. listOfFiles.listDirectory(MainApp.isOnlyOnDevice(), false);
  1436. }
  1437. FileFragment secondFragment = getSecondFragment();
  1438. if (secondFragment instanceof FileDetailFragment) {
  1439. FileDetailFragment detailFragment = (FileDetailFragment) secondFragment;
  1440. detailFragment.listenForTransferProgress();
  1441. detailFragment.updateFileDetails(false, false);
  1442. }
  1443. }
  1444. @Override
  1445. public void onServiceDisconnected(ComponentName component) {
  1446. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1447. Log_OC.d(TAG, "Download service disconnected");
  1448. mDownloaderBinder = null;
  1449. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1450. Log_OC.d(TAG, "Upload service disconnected");
  1451. mUploaderBinder = null;
  1452. }
  1453. }
  1454. }
  1455. private MediaServiceConnection newMediaConnection(){
  1456. return new MediaServiceConnection();
  1457. }
  1458. /** Defines callbacks for service binding, passed to bindService() */
  1459. private class MediaServiceConnection implements ServiceConnection {
  1460. @Override
  1461. public void onServiceConnected(ComponentName component, IBinder service) {
  1462. if (component.equals(new ComponentName(FileDisplayActivity.this, MediaService.class))) {
  1463. Log_OC.d(TAG, "Media service connected");
  1464. mMediaServiceBinder = (MediaServiceBinder) service;
  1465. }else {
  1466. return;
  1467. }
  1468. }
  1469. @Override
  1470. public void onServiceDisconnected(ComponentName component) {
  1471. if (component.equals(new ComponentName(FileDisplayActivity.this,
  1472. MediaService.class))) {
  1473. Log_OC.e(TAG, "Media service disconnected");
  1474. mMediaServiceBinder = null;
  1475. }
  1476. }
  1477. }
  1478. /**
  1479. * Updates the view associated to the activity after the finish of some operation over files
  1480. * in the current account.
  1481. *
  1482. * @param operation Removal operation performed.
  1483. * @param result Result of the removal.
  1484. */
  1485. @Override
  1486. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1487. super.onRemoteOperationFinish(operation, result);
  1488. if (operation instanceof RemoveFileOperation) {
  1489. onRemoveFileOperationFinish((RemoveFileOperation) operation, result);
  1490. } else if (operation instanceof RenameFileOperation) {
  1491. onRenameFileOperationFinish((RenameFileOperation) operation, result);
  1492. } else if (operation instanceof SynchronizeFileOperation) {
  1493. onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
  1494. } else if (operation instanceof CreateFolderOperation) {
  1495. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  1496. } else if (operation instanceof MoveFileOperation) {
  1497. onMoveFileOperationFinish((MoveFileOperation) operation, result);
  1498. } else if (operation instanceof CopyFileOperation) {
  1499. onCopyFileOperationFinish((CopyFileOperation) operation, result);
  1500. } else if (operation instanceof CreateShareViaLinkOperation) {
  1501. onCreateShareViaLinkOperationFinish((CreateShareViaLinkOperation) operation, result);
  1502. } else if (operation instanceof CreateShareWithShareeOperation) {
  1503. onUpdateShareInformation(result, R.string.sharee_add_failed);
  1504. } else if (operation instanceof UpdateShareViaLinkOperation) {
  1505. onUpdateShareInformation(result, R.string.updating_share_failed);
  1506. } else if (operation instanceof UpdateSharePermissionsOperation) {
  1507. onUpdateShareInformation(result, R.string.updating_share_failed);
  1508. } else if (operation instanceof UnshareOperation) {
  1509. onUpdateShareInformation(result, R.string.unsharing_failed);
  1510. } else if (operation instanceof RestoreFileVersionOperation) {
  1511. onRestoreFileVersionOperationFinish(result);
  1512. }
  1513. }
  1514. private void refreshShowDetails() {
  1515. FileFragment details = getSecondFragment();
  1516. if (details != null) {
  1517. OCFile file = details.getFile();
  1518. if (file != null) {
  1519. file = getStorageManager().getFileByPath(file.getRemotePath());
  1520. if (details instanceof PreviewMediaFragment) {
  1521. // Refresh OCFile of the fragment
  1522. ((PreviewMediaFragment) details).updateFile(file);
  1523. } else if (details instanceof PreviewTextFragment) {
  1524. // Refresh OCFile of the fragment
  1525. ((PreviewTextFragment) details).updateFile(file);
  1526. } else {
  1527. showDetails(file);
  1528. }
  1529. }
  1530. supportInvalidateOptionsMenu();
  1531. }
  1532. }
  1533. /**
  1534. * Updates the view associated to the activity after the finish of an operation trying to
  1535. * remove a file.
  1536. *
  1537. * @param operation Removal operation performed.
  1538. * @param result Result of the removal.
  1539. */
  1540. private void onRemoveFileOperationFinish(RemoveFileOperation operation,
  1541. RemoteOperationResult result) {
  1542. if (!operation.isInBackground()) {
  1543. DisplayUtils.showSnackMessage(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation,
  1544. getResources()));
  1545. }
  1546. if (result.isSuccess()) {
  1547. OCFile removedFile = operation.getFile();
  1548. tryStopPlaying(removedFile);
  1549. FileFragment second = getSecondFragment();
  1550. // check if file is still available, if so do nothing
  1551. boolean fileAvailable = getStorageManager().fileExists(removedFile.getFileId());
  1552. if (second != null && !fileAvailable && removedFile.equals(second.getFile())) {
  1553. if (second instanceof PreviewMediaFragment) {
  1554. ((PreviewMediaFragment) second).stopPreview(true);
  1555. }
  1556. setFile(getStorageManager().getFileById(removedFile.getParentId()));
  1557. cleanSecondFragment();
  1558. }
  1559. if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
  1560. refreshListOfFilesFragment(false);
  1561. }
  1562. supportInvalidateOptionsMenu();
  1563. } else {
  1564. if (result.isSslRecoverableException()) {
  1565. mLastSslUntrustedServerResult = result;
  1566. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1567. }
  1568. }
  1569. }
  1570. private void onRestoreFileVersionOperationFinish(RemoteOperationResult result) {
  1571. if (result.isSuccess()) {
  1572. OCFile file = getFile();
  1573. // delete old local copy
  1574. if (file.isDown()) {
  1575. List<OCFile> list = new ArrayList<>();
  1576. list.add(file);
  1577. getFileOperationsHelper().removeFiles(list, true, true);
  1578. // download new version, only if file was previously download
  1579. getFileOperationsHelper().syncFile(file);
  1580. }
  1581. OCFile parent = getStorageManager().getFileById(file.getParentId());
  1582. startSyncFolderOperation(parent, true, true);
  1583. if (getSecondFragment() instanceof FileDetailFragment) {
  1584. FileDetailFragment fileDetailFragment = (FileDetailFragment) getSecondFragment();
  1585. fileDetailFragment.getFileDetailActivitiesFragment().reload();
  1586. }
  1587. DisplayUtils.showSnackMessage(this, R.string.file_version_restored_successfully);
  1588. } else {
  1589. DisplayUtils.showSnackMessage(this, R.string.file_version_restored_error);
  1590. }
  1591. }
  1592. public void setMediaServiceConnection() {
  1593. mMediaServiceConnection = newMediaConnection();// mediaServiceConnection;
  1594. bindService(new Intent(this, MediaService.class), mMediaServiceConnection, Context.BIND_AUTO_CREATE);
  1595. }
  1596. private void tryStopPlaying(OCFile file) {
  1597. if (mMediaServiceConnection != null && MimeTypeUtil.isAudio(file) && mMediaServiceBinder.isPlaying(file)) {
  1598. mMediaServiceBinder.pause();
  1599. }
  1600. }
  1601. /**
  1602. * Updates the view associated to the activity after the finish of an operation trying to move a
  1603. * file.
  1604. *
  1605. * @param operation Move operation performed.
  1606. * @param result Result of the move operation.
  1607. */
  1608. private void onMoveFileOperationFinish(MoveFileOperation operation,
  1609. RemoteOperationResult result) {
  1610. if (result.isSuccess()) {
  1611. refreshListOfFilesFragment(false);
  1612. } else {
  1613. try {
  1614. DisplayUtils.showSnackMessage(
  1615. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1616. );
  1617. } catch (NotFoundException e) {
  1618. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1619. }
  1620. }
  1621. }
  1622. private void onCreateShareViaLinkOperationFinish(CreateShareViaLinkOperation operation,
  1623. RemoteOperationResult result) {
  1624. FileDetailFragment fileDetailFragment = getShareFileFragment();
  1625. if (result.isSuccess()) {
  1626. updateFileFromDB();
  1627. // Create dialog to allow the user choose an app to send the link
  1628. Intent intentToShareLink = new Intent(Intent.ACTION_SEND);
  1629. // if share to user and share via link multiple ocshares are returned,
  1630. // therefore filtering for public_link
  1631. String link = "";
  1632. for (Object object : result.getData()) {
  1633. OCShare shareLink = (OCShare) object;
  1634. if (TAG_PUBLIC_LINK.equalsIgnoreCase(shareLink.getShareType().name())) {
  1635. link = shareLink.getShareLink();
  1636. break;
  1637. }
  1638. }
  1639. intentToShareLink.putExtra(Intent.EXTRA_TEXT, link);
  1640. intentToShareLink.setType("text/plain");
  1641. String username;
  1642. try {
  1643. OwnCloudAccount oca = new OwnCloudAccount(getAccount(), this);
  1644. if (oca.getDisplayName() != null && !oca.getDisplayName().isEmpty()) {
  1645. username = oca.getDisplayName();
  1646. } else {
  1647. username = AccountUtils.getUsernameForAccount(getAccount());
  1648. }
  1649. } catch (Exception e) {
  1650. username = AccountUtils.getUsernameForAccount(getAccount());
  1651. }
  1652. if (username != null) {
  1653. intentToShareLink.putExtra(
  1654. Intent.EXTRA_SUBJECT,
  1655. getString(
  1656. R.string.subject_user_shared_with_you,
  1657. username,
  1658. getFile().getFileName()
  1659. )
  1660. );
  1661. } else {
  1662. intentToShareLink.putExtra(
  1663. Intent.EXTRA_SUBJECT,
  1664. getString(
  1665. R.string.subject_shared_with_you,
  1666. getFile().getFileName()
  1667. )
  1668. );
  1669. }
  1670. String[] packagesToExclude = new String[]{getPackageName()};
  1671. DialogFragment chooserDialog = ShareLinkToDialog.newInstance(intentToShareLink, packagesToExclude);
  1672. chooserDialog.show(getSupportFragmentManager(), FTAG_CHOOSER_DIALOG);
  1673. if (fileDetailFragment != null && fileDetailFragment.getFileDetailSharingFragment() != null) {
  1674. fileDetailFragment.getFileDetailSharingFragment().refreshPublicShareFromDB();
  1675. fileDetailFragment.getFileDetailSharingFragment().onUpdateShareInformation(result, getFile());
  1676. }
  1677. refreshListOfFilesFragment(false);
  1678. } else {
  1679. // Detect Failure (403) --> maybe needs password
  1680. String password = operation.getPassword();
  1681. if (result.getCode() == RemoteOperationResult.ResultCode.SHARE_FORBIDDEN &&
  1682. (password == null || password.length() == 0) &&
  1683. getCapabilities().getFilesSharingPublicEnabled().isUnknown()) {
  1684. // Was tried without password, but not sure that it's optional.
  1685. // Try with password before giving up; see also ShareFileFragment#OnShareViaLinkListener
  1686. if (fileDetailFragment != null
  1687. && fileDetailFragment.isAdded()) { // only if added to the view hierarchy!!
  1688. fileDetailFragment.getFileDetailSharingFragment().requestPasswordForShareViaLink(true);
  1689. }
  1690. } else {
  1691. if (fileDetailFragment != null && fileDetailFragment.getFileDetailSharingFragment() != null) {
  1692. fileDetailFragment.getFileDetailSharingFragment().refreshPublicShareFromDB();
  1693. }
  1694. Snackbar.make(
  1695. findViewById(android.R.id.content),
  1696. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1697. Snackbar.LENGTH_LONG
  1698. ).show();
  1699. }
  1700. }
  1701. }
  1702. private void onUpdateShareInformation(RemoteOperationResult result, @StringRes int errorString) {
  1703. Fragment fileDetailFragment = getSecondFragment();
  1704. if (result.isSuccess()) {
  1705. updateFileFromDB();
  1706. refreshListOfFilesFragment(false);
  1707. } else if (fileDetailFragment.getView() != null) {
  1708. Snackbar.make(fileDetailFragment.getView(), errorString, Snackbar.LENGTH_LONG).show();
  1709. }
  1710. if (fileDetailFragment != null && fileDetailFragment instanceof FileDetailFragment) {
  1711. ((FileDetailFragment) fileDetailFragment).getFileDetailSharingFragment()
  1712. .onUpdateShareInformation(result, getFile());
  1713. }
  1714. }
  1715. /**
  1716. * Shortcut to get access to the {@link FileDetailFragment} instance, if any
  1717. *
  1718. * @return A {@link FileDetailFragment} instance, or null
  1719. */
  1720. private FileDetailFragment getShareFileFragment() {
  1721. return (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(TAG_SECOND_FRAGMENT);
  1722. }
  1723. /**
  1724. * Updates the view associated to the activity after the finish of an operation trying to copy a
  1725. * file.
  1726. *
  1727. * @param operation Copy operation performed.
  1728. * @param result Result of the copy operation.
  1729. */
  1730. private void onCopyFileOperationFinish(CopyFileOperation operation, RemoteOperationResult result) {
  1731. if (result.isSuccess()) {
  1732. refreshListOfFilesFragment(false);
  1733. } else {
  1734. try {
  1735. DisplayUtils.showSnackMessage(
  1736. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1737. );
  1738. } catch (NotFoundException e) {
  1739. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1740. }
  1741. }
  1742. }
  1743. /**
  1744. * Updates the view associated to the activity after the finish of an operation trying to rename
  1745. * a file.
  1746. *
  1747. * @param operation Renaming operation performed.
  1748. * @param result Result of the renaming.
  1749. */
  1750. private void onRenameFileOperationFinish(RenameFileOperation operation,
  1751. RemoteOperationResult result) {
  1752. OCFile renamedFile = operation.getFile();
  1753. if (result.isSuccess()) {
  1754. FileFragment details = getSecondFragment();
  1755. if (details != null) {
  1756. if (details instanceof FileDetailFragment &&
  1757. renamedFile.equals(details.getFile())) {
  1758. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1759. showDetails(renamedFile);
  1760. } else if (details instanceof PreviewMediaFragment &&
  1761. renamedFile.equals(details.getFile())) {
  1762. ((PreviewMediaFragment) details).updateFile(renamedFile);
  1763. if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
  1764. int position = ((PreviewMediaFragment) details).getPosition();
  1765. startMediaPreview(renamedFile, position, true, true);
  1766. } else {
  1767. getFileOperationsHelper().openFile(renamedFile);
  1768. }
  1769. } else if (details instanceof PreviewTextFragment &&
  1770. renamedFile.equals(details.getFile())) {
  1771. ((PreviewTextFragment) details).updateFile(renamedFile);
  1772. if (PreviewTextFragment.canBePreviewed(renamedFile)) {
  1773. startTextPreview(renamedFile, true);
  1774. } else {
  1775. getFileOperationsHelper().openFile(renamedFile);
  1776. }
  1777. }
  1778. }
  1779. if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
  1780. refreshListOfFilesFragment(false);
  1781. }
  1782. } else {
  1783. DisplayUtils.showSnackMessage(
  1784. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1785. );
  1786. if (result.isSslRecoverableException()) {
  1787. mLastSslUntrustedServerResult = result;
  1788. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1789. }
  1790. }
  1791. }
  1792. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
  1793. RemoteOperationResult result) {
  1794. if (result.isSuccess() && operation.transferWasRequested()) {
  1795. OCFile syncedFile = operation.getLocalFile();
  1796. onTransferStateChanged(syncedFile, true, true);
  1797. supportInvalidateOptionsMenu();
  1798. refreshShowDetails();
  1799. }
  1800. }
  1801. /**
  1802. * Updates the view associated to the activity after the finish of an operation trying create a
  1803. * new folder
  1804. *
  1805. * @param operation Creation operation performed.
  1806. * @param result Result of the creation.
  1807. */
  1808. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  1809. RemoteOperationResult result) {
  1810. if (result.isSuccess()) {
  1811. refreshListOfFilesFragment(false);
  1812. } else {
  1813. try {
  1814. DisplayUtils.showSnackMessage(
  1815. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1816. );
  1817. } catch (NotFoundException e) {
  1818. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1819. }
  1820. }
  1821. }
  1822. /**
  1823. * {@inheritDoc}
  1824. */
  1825. @Override
  1826. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1827. refreshListOfFilesFragment(false);
  1828. FileFragment details = getSecondFragment();
  1829. if (details instanceof FileDetailFragment &&
  1830. file.equals(details.getFile())) {
  1831. if (downloading || uploading) {
  1832. ((FileDetailFragment) details).updateFileDetails(file, getAccount());
  1833. } else {
  1834. if (!file.fileExists()) {
  1835. cleanSecondFragment();
  1836. } else {
  1837. ((FileDetailFragment) details).updateFileDetails(false, true);
  1838. }
  1839. }
  1840. }
  1841. }
  1842. private void requestForDownload() {
  1843. Account account = getAccount();
  1844. //if (!mWaitingToPreview.isDownloading()) {
  1845. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1846. Intent i = new Intent(this, FileDownloader.class);
  1847. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1848. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1849. startService(i);
  1850. }
  1851. }
  1852. @Override
  1853. public void onSavedCertificate() {
  1854. startSyncFolderOperation(getCurrentDir(), false);
  1855. }
  1856. /**
  1857. * Starts an operation to refresh the requested folder.
  1858. *
  1859. * The operation is run in a new background thread created on the fly.
  1860. *
  1861. * The refresh updates is a "light sync": properties of regular files in folder are updated (including
  1862. * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
  1863. * synchronized too.
  1864. *
  1865. * @param folder Folder to refresh.
  1866. * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
  1867. * didn't change.
  1868. */
  1869. public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
  1870. startSyncFolderOperation(folder, ignoreETag, false);
  1871. }
  1872. /**
  1873. * Starts an operation to refresh the requested folder.
  1874. *
  1875. * The operation is run in a new background thread created on the fly.
  1876. *
  1877. * The refresh updates is a "light sync": properties of regular files in folder are updated (including
  1878. * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
  1879. * synchronized too.
  1880. *
  1881. * @param folder Folder to refresh.
  1882. * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
  1883. * didn't change.
  1884. * @param ignoreFocus reloads file list even without focus, e.g. on tablet mode, focus can still be in detail view
  1885. */
  1886. public void startSyncFolderOperation(final OCFile folder, final boolean ignoreETag, boolean ignoreFocus) {
  1887. // the execution is slightly delayed to allow the activity get the window focus if it's being started
  1888. // or if the method is called from a dialog that is being dismissed
  1889. if (TextUtils.isEmpty(searchQuery)) {
  1890. getHandler().postDelayed(
  1891. new Runnable() {
  1892. @Override
  1893. public void run() {
  1894. if (ignoreFocus || hasWindowFocus()) {
  1895. long currentSyncTime = System.currentTimeMillis();
  1896. mSyncInProgress = true;
  1897. // perform folder synchronization
  1898. RemoteOperation synchFolderOp = new RefreshFolderOperation(folder,
  1899. currentSyncTime,
  1900. false,
  1901. ignoreETag,
  1902. getStorageManager(),
  1903. getAccount(),
  1904. getApplicationContext()
  1905. );
  1906. synchFolderOp.execute(
  1907. getAccount(),
  1908. MainApp.getAppContext(),
  1909. FileDisplayActivity.this,
  1910. null,
  1911. null
  1912. );
  1913. setIndeterminate(true);
  1914. setBackgroundText();
  1915. } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
  1916. // another window floating over
  1917. }
  1918. },
  1919. DELAY_TO_REQUEST_REFRESH_OPERATION_LATER
  1920. );
  1921. }
  1922. }
  1923. private void requestForDownload(OCFile file, String downloadBehaviour, String packageName, String activityName) {
  1924. Account account = getAccount();
  1925. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1926. Intent i = new Intent(this, FileDownloader.class);
  1927. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1928. i.putExtra(FileDownloader.EXTRA_FILE, file);
  1929. i.putExtra(SendShareDialog.PACKAGE_NAME, packageName);
  1930. i.putExtra(SendShareDialog.ACTIVITY_NAME, activityName);
  1931. i.putExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR, downloadBehaviour);
  1932. startService(i);
  1933. }
  1934. }
  1935. private void sendDownloadedFile(String packageName, String activityName) {
  1936. if (mWaitingToSend != null) {
  1937. Intent sendIntent = new Intent(Intent.ACTION_SEND);
  1938. sendIntent.setType(mWaitingToSend.getMimeType());
  1939. sendIntent.putExtra(Intent.EXTRA_STREAM, mWaitingToSend.getExposedFileUri(this));
  1940. sendIntent.putExtra(Intent.ACTION_SEND, true);
  1941. sendIntent.setComponent(new ComponentName(packageName, activityName));
  1942. // Show dialog
  1943. String sendTitle = getString(R.string.activity_chooser_send_file_title);
  1944. startActivity(Intent.createChooser(sendIntent, sendTitle));
  1945. } else {
  1946. Log_OC.e(TAG, "Trying to send a NULL OCFile");
  1947. }
  1948. mWaitingToSend = null;
  1949. }
  1950. /**
  1951. * Requests the download of the received {@link OCFile} , updates the UI
  1952. * to monitor the download progress and prepares the activity to send the file
  1953. * when the download finishes.
  1954. *
  1955. * @param file {@link OCFile} to download and preview.
  1956. * @param packageName
  1957. * @param activityName
  1958. */
  1959. public void startDownloadForSending(OCFile file, String downloadBehaviour, String packageName,
  1960. String activityName) {
  1961. mWaitingToSend = file;
  1962. requestForDownload(mWaitingToSend, downloadBehaviour, packageName, activityName);
  1963. boolean hasSecondFragment = getSecondFragment() != null;
  1964. updateFragmentsVisibility(hasSecondFragment);
  1965. }
  1966. /**
  1967. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1968. *
  1969. * @param file Image {@link OCFile} to show.
  1970. */
  1971. public void startImagePreview(OCFile file, boolean showPreview) {
  1972. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1973. showDetailsIntent.putExtra(EXTRA_FILE, file);
  1974. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1975. if (showPreview) {
  1976. startActivity(showDetailsIntent);
  1977. } else {
  1978. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  1979. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  1980. }
  1981. }
  1982. /**
  1983. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1984. *
  1985. * @param file Image {@link OCFile} to show.
  1986. */
  1987. public void startImagePreview(OCFile file, VirtualFolderType type, boolean showPreview) {
  1988. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1989. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_FILE, file);
  1990. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1991. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_VIRTUAL_TYPE, type);
  1992. if (showPreview) {
  1993. startActivity(showDetailsIntent);
  1994. } else {
  1995. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  1996. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  1997. }
  1998. }
  1999. /**
  2000. * Stars the preview of an already down media {@link OCFile}.
  2001. *
  2002. * @param file Media {@link OCFile} to preview.
  2003. * @param startPlaybackPosition Media position where the playback will be started,
  2004. * in milliseconds.
  2005. * @param autoplay When 'true', the playback will start without user
  2006. * interactions.
  2007. */
  2008. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay, boolean showPreview) {
  2009. if (showPreview && file.isDown() && !file.isDownloading()) {
  2010. Fragment mediaFragment = PreviewMediaFragment.newInstance(file, getAccount(), startPlaybackPosition, autoplay);
  2011. setSecondFragment(mediaFragment);
  2012. updateFragmentsVisibility(true);
  2013. updateActionBarTitleAndHomeButton(file);
  2014. setFile(file);
  2015. } else {
  2016. Intent previewIntent = new Intent();
  2017. previewIntent.putExtra(EXTRA_FILE, file);
  2018. previewIntent.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, startPlaybackPosition);
  2019. previewIntent.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, autoplay);
  2020. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  2021. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  2022. }
  2023. }
  2024. /**
  2025. * Stars the preview of a text file {@link OCFile}.
  2026. *
  2027. * @param file Text {@link OCFile} to preview.
  2028. */
  2029. public void startTextPreview(OCFile file, boolean showPreview) {
  2030. if (showPreview) {
  2031. Bundle args = new Bundle();
  2032. args.putParcelable(EXTRA_FILE, file);
  2033. args.putParcelable(EXTRA_ACCOUNT, getAccount());
  2034. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  2035. PreviewTextFragment.class.getName(), args);
  2036. setSecondFragment(textPreviewFragment);
  2037. updateFragmentsVisibility(true);
  2038. updateActionBarTitleAndHomeButton(file);
  2039. setFile(file);
  2040. } else {
  2041. Intent previewIntent = new Intent();
  2042. previewIntent.putExtra(EXTRA_FILE, file);
  2043. previewIntent.putExtra(TEXT_PREVIEW, true);
  2044. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  2045. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  2046. }
  2047. }
  2048. public void startContactListFragment(OCFile file) {
  2049. Intent intent = new Intent(this, ContactsPreferenceActivity.class);
  2050. intent.putExtra(ContactListFragment.FILE_NAME, Parcels.wrap(file));
  2051. intent.putExtra(ContactListFragment.ACCOUNT, Parcels.wrap(getAccount()));
  2052. startActivity(intent);
  2053. }
  2054. /**
  2055. * Requests the download of the received {@link OCFile} , updates the UI
  2056. * to monitor the download progress and prepares the activity to preview
  2057. * or open the file when the download finishes.
  2058. *
  2059. * @param file {@link OCFile} to download and preview.
  2060. */
  2061. public void startDownloadForPreview(OCFile file) {
  2062. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  2063. setSecondFragment(detailFragment);
  2064. mWaitingToPreview = file;
  2065. requestForDownload();
  2066. updateFragmentsVisibility(true);
  2067. updateActionBarTitleAndHomeButton(file);
  2068. setFile(file);
  2069. }
  2070. /**
  2071. * Request stopping the upload/download operation in progress over the given {@link OCFile} file.
  2072. *
  2073. * @param file {@link OCFile} file which operation are wanted to be cancel
  2074. */
  2075. public void cancelTransference(OCFile file) {
  2076. getFileOperationsHelper().cancelTransference(file);
  2077. if (mWaitingToPreview != null &&
  2078. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  2079. mWaitingToPreview = null;
  2080. }
  2081. if (mWaitingToSend != null &&
  2082. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  2083. mWaitingToSend = null;
  2084. }
  2085. onTransferStateChanged(file, false, false);
  2086. }
  2087. /**
  2088. * Request stopping all upload/download operations in progress over the given {@link OCFile} files.
  2089. *
  2090. * @param files collection of {@link OCFile} files which operations are wanted to be cancel
  2091. */
  2092. public void cancelTransference(Collection<OCFile> files) {
  2093. for (OCFile file : files) {
  2094. cancelTransference(file);
  2095. }
  2096. }
  2097. @Override
  2098. public void onRefresh(boolean ignoreETag) {
  2099. refreshList(ignoreETag);
  2100. }
  2101. @Override
  2102. public void onRefresh() {
  2103. refreshList(true);
  2104. }
  2105. private void refreshList(boolean ignoreETag) {
  2106. OCFileListFragment listOfFiles = getListOfFilesFragment();
  2107. if (listOfFiles != null && !listOfFiles.isSearchFragment()) {
  2108. OCFile folder = listOfFiles.getCurrentFile();
  2109. if (folder != null) {
  2110. startSyncFolderOperation(folder, ignoreETag);
  2111. }
  2112. }
  2113. }
  2114. private boolean isGridView() {
  2115. return getListOfFilesFragment().isGridEnabled();
  2116. }
  2117. public void allFilesOption() {
  2118. browseToRoot();
  2119. }
  2120. @Override
  2121. public void showFiles(boolean onDeviceOnly) {
  2122. super.showFiles(onDeviceOnly);
  2123. getListOfFilesFragment().refreshDirectory();
  2124. }
  2125. @Subscribe(threadMode = ThreadMode.MAIN)
  2126. public void onMessageEvent(SyncEventFinished event) {
  2127. Bundle bundle = event.getIntent().getExtras();
  2128. if (event.getIntent().getBooleanExtra(TEXT_PREVIEW, false)) {
  2129. startTextPreview((OCFile) bundle.get(EXTRA_FILE), true);
  2130. } else if (bundle.containsKey(PreviewVideoActivity.EXTRA_START_POSITION)) {
  2131. startMediaPreview((OCFile)bundle.get(EXTRA_FILE),
  2132. (int)bundle.get(PreviewVideoActivity.EXTRA_START_POSITION),
  2133. (boolean)bundle.get(PreviewVideoActivity.EXTRA_AUTOPLAY), true);
  2134. } else if (bundle.containsKey(PreviewImageActivity.EXTRA_VIRTUAL_TYPE)) {
  2135. startImagePreview((OCFile)bundle.get(EXTRA_FILE),
  2136. (VirtualFolderType)bundle.get(PreviewImageActivity.EXTRA_VIRTUAL_TYPE),
  2137. true);
  2138. } else {
  2139. startImagePreview((OCFile)bundle.get(EXTRA_FILE),true);
  2140. }
  2141. }
  2142. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  2143. public void onMessageEvent(TokenPushEvent event) {
  2144. if (!PreferenceManager.getKeysReInit(getApplicationContext())) {
  2145. PushUtils.reinitKeys();
  2146. } else {
  2147. PushUtils.pushRegistrationToServer();
  2148. }
  2149. }
  2150. @Override
  2151. public void onStart() {
  2152. super.onStart();
  2153. EventBus.getDefault().post(new TokenPushEvent());
  2154. checkForNewDevVersionNecessary(findViewById(R.id.root_layout), getApplicationContext());
  2155. }
  2156. @Override
  2157. protected void onRestart() {
  2158. super.onRestart();
  2159. checkForNewDevVersionNecessary(findViewById(R.id.root_layout), getApplicationContext());
  2160. }
  2161. }