FileDisplayActivity.java 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  1. /* ownCloud Android client application
  2. * Copyright (C) 2011 Bartek Przybylski
  3. * Copyright (C) 2012-2014 ownCloud Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2,
  7. * as published by the Free Software Foundation.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. */
  18. package com.owncloud.android.ui.activity;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import android.accounts.Account;
  22. import android.accounts.AccountManager;
  23. import android.accounts.AuthenticatorException;
  24. import android.accounts.OperationCanceledException;
  25. import android.annotation.SuppressLint;
  26. import android.annotation.TargetApi;
  27. import android.app.AlertDialog;
  28. import android.app.Dialog;
  29. import android.app.ProgressDialog;
  30. import android.content.BroadcastReceiver;
  31. import android.content.ComponentName;
  32. import android.content.ContentResolver;
  33. import android.content.ContentUris;
  34. import android.content.Context;
  35. import android.content.DialogInterface;
  36. import android.content.Intent;
  37. import android.content.IntentFilter;
  38. import android.content.ServiceConnection;
  39. import android.content.SharedPreferences;
  40. import android.content.SyncRequest;
  41. import android.content.res.Resources.NotFoundException;
  42. import android.database.Cursor;
  43. import android.net.Uri;
  44. import android.os.Build;
  45. import android.os.Bundle;
  46. import android.os.Environment;
  47. import android.os.IBinder;
  48. import android.preference.PreferenceManager;
  49. import android.provider.DocumentsContract;
  50. import android.provider.MediaStore;
  51. import android.provider.OpenableColumns;
  52. import android.support.v4.app.Fragment;
  53. import android.support.v4.app.FragmentManager;
  54. import android.support.v4.app.FragmentTransaction;
  55. import android.util.Log;
  56. import android.view.View;
  57. import android.view.ViewGroup;
  58. import android.widget.ArrayAdapter;
  59. import android.widget.TextView;
  60. import android.widget.Toast;
  61. import com.actionbarsherlock.app.ActionBar;
  62. import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
  63. import com.actionbarsherlock.view.Menu;
  64. import com.actionbarsherlock.view.MenuInflater;
  65. import com.actionbarsherlock.view.MenuItem;
  66. import com.actionbarsherlock.view.Window;
  67. import com.owncloud.android.BuildConfig;
  68. import com.owncloud.android.MainApp;
  69. import com.owncloud.android.R;
  70. import com.owncloud.android.datamodel.OCFile;
  71. import com.owncloud.android.files.services.FileDownloader;
  72. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  73. import com.owncloud.android.files.services.FileUploader;
  74. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  75. import com.owncloud.android.lib.common.OwnCloudAccount;
  76. import com.owncloud.android.lib.common.OwnCloudClient;
  77. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  78. import com.owncloud.android.lib.common.OwnCloudCredentials;
  79. import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
  80. import com.owncloud.android.lib.common.network.CertificateCombinedException;
  81. import com.owncloud.android.lib.common.operations.RemoteOperation;
  82. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  83. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  84. import com.owncloud.android.lib.common.utils.Log_OC;
  85. import com.owncloud.android.operations.CreateFolderOperation;
  86. import com.owncloud.android.operations.CreateShareOperation;
  87. import com.owncloud.android.operations.MoveFileOperation;
  88. import com.owncloud.android.operations.RemoveFileOperation;
  89. import com.owncloud.android.operations.RenameFileOperation;
  90. import com.owncloud.android.operations.SynchronizeFileOperation;
  91. import com.owncloud.android.operations.RefreshFolderOperation;
  92. import com.owncloud.android.operations.UnshareLinkOperation;
  93. import com.owncloud.android.services.observer.FileObserverService;
  94. import com.owncloud.android.syncadapter.FileSyncAdapter;
  95. import com.owncloud.android.ui.adapter.FileListListAdapter;
  96. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  97. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
  98. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
  99. import com.owncloud.android.ui.fragment.FileDetailFragment;
  100. import com.owncloud.android.ui.fragment.FileFragment;
  101. import com.owncloud.android.ui.fragment.OCFileListFragment;
  102. import com.owncloud.android.ui.preview.PreviewImageActivity;
  103. import com.owncloud.android.ui.preview.PreviewImageFragment;
  104. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  105. import com.owncloud.android.ui.preview.PreviewVideoActivity;
  106. import com.owncloud.android.utils.DisplayUtils;
  107. import com.owncloud.android.utils.ErrorMessageAdapter;
  108. import com.owncloud.android.utils.FileStorageUtils;
  109. import com.owncloud.android.utils.UriUtils;
  110. /**
  111. * Displays, what files the user has available in his ownCloud.
  112. *
  113. * @author Bartek Przybylski
  114. * @author David A. Velasco
  115. */
  116. public class FileDisplayActivity extends HookActivity implements
  117. FileFragment.ContainerActivity, OnNavigationListener,
  118. OnSslUntrustedCertListener, OnEnforceableRefreshListener {
  119. private ArrayAdapter<String> mDirectories;
  120. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  121. private UploadFinishReceiver mUploadFinishReceiver;
  122. private DownloadFinishReceiver mDownloadFinishReceiver;
  123. private RemoteOperationResult mLastSslUntrustedServerResult = null;
  124. private boolean mDualPane;
  125. private View mLeftFragmentContainer;
  126. private View mRightFragmentContainer;
  127. private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  128. private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
  129. private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
  130. public static final int DIALOG_SHORT_WAIT = 0;
  131. private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
  132. private static final int DIALOG_CERT_NOT_SAVED = 2;
  133. public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
  134. private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
  135. private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
  136. public static final int ACTION_MOVE_FILES = 3;
  137. private static final String TAG = FileDisplayActivity.class.getSimpleName();
  138. private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
  139. private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
  140. private OCFile mWaitingToPreview;
  141. private boolean mSyncInProgress = false;
  142. private String DIALOG_UNTRUSTED_CERT;
  143. private OCFile mWaitingToSend;
  144. @Override
  145. protected void onCreate(Bundle savedInstanceState) {
  146. Log_OC.d(TAG, "onCreate() start");
  147. requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
  148. super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
  149. // PIN CODE request ; best location is to decide, let's try this first
  150. if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
  151. requestPinCode();
  152. } else if (getIntent().getAction() == null && savedInstanceState == null) {
  153. requestPinCode();
  154. }
  155. /// grant that FileObserverService is watching favourite files
  156. if (savedInstanceState == null) {
  157. Intent initObserversIntent = FileObserverService.makeInitIntent(this);
  158. startService(initObserversIntent);
  159. }
  160. /// Load of saved instance state
  161. if(savedInstanceState != null) {
  162. mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
  163. mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
  164. mWaitingToSend = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND);
  165. } else {
  166. mWaitingToPreview = null;
  167. mSyncInProgress = false;
  168. mWaitingToSend = null;
  169. }
  170. /// USER INTERFACE
  171. // Inflate and set the layout view
  172. setContentView(R.layout.files);
  173. mDualPane = getResources().getBoolean(R.bool.large_land_layout);
  174. mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
  175. mRightFragmentContainer = findViewById(R.id.right_fragment_container);
  176. if (savedInstanceState == null) {
  177. createMinFragments();
  178. }
  179. // Action bar setup
  180. mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
  181. getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
  182. setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
  183. setBackgroundText();
  184. Log_OC.d(TAG, "onCreate() end");
  185. }
  186. @Override
  187. protected void onStart() {
  188. super.onStart();
  189. getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
  190. }
  191. @Override
  192. protected void onDestroy() {
  193. super.onDestroy();
  194. }
  195. /**
  196. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  197. */
  198. @Override
  199. protected void onAccountSet(boolean stateWasRecovered) {
  200. super.onAccountSet(stateWasRecovered);
  201. if (getAccount() != null) {
  202. /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
  203. OCFile file = getFile();
  204. // get parent from path
  205. String parentPath = "";
  206. if (file != null) {
  207. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  208. // upload in progress - right now, files are not inserted in the local cache until the upload is successful
  209. // get parent from path
  210. parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
  211. if (getStorageManager().getFileByPath(parentPath) == null)
  212. file = null; // not able to know the directory where the file is uploading
  213. } else {
  214. file = getStorageManager().getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
  215. }
  216. }
  217. if (file == null) {
  218. // fall back to root folder
  219. file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
  220. }
  221. setFile(file);
  222. setNavigationListWithFolder(file);
  223. if (!stateWasRecovered) {
  224. Log_OC.d(TAG, "Initializing Fragments in onAccountChanged..");
  225. initFragmentsWithFile();
  226. if (file.isFolder()) {
  227. startSyncFolderOperation(file, false);
  228. }
  229. } else {
  230. updateFragmentsVisibility(!file.isFolder());
  231. updateNavigationElementsInActionBar(file.isFolder() ? null : file);
  232. }
  233. }
  234. }
  235. private void setNavigationListWithFolder(OCFile file) {
  236. mDirectories.clear();
  237. OCFile fileIt = file;
  238. String parentPath;
  239. while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
  240. if (fileIt.isFolder()) {
  241. mDirectories.add(fileIt.getFileName());
  242. }
  243. // get parent from path
  244. parentPath = fileIt.getRemotePath().substring(0, fileIt.getRemotePath().lastIndexOf(fileIt.getFileName()));
  245. fileIt = getStorageManager().getFileByPath(parentPath);
  246. }
  247. mDirectories.add(OCFile.PATH_SEPARATOR);
  248. }
  249. private void createMinFragments() {
  250. OCFileListFragment listOfFiles = new OCFileListFragment();
  251. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  252. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  253. transaction.commit();
  254. }
  255. private void initFragmentsWithFile() {
  256. if (getAccount() != null && getFile() != null) {
  257. /// First fragment
  258. OCFileListFragment listOfFiles = getListOfFilesFragment();
  259. if (listOfFiles != null) {
  260. listOfFiles.listDirectory(getCurrentDir());
  261. } else {
  262. Log_OC.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
  263. }
  264. /// Second fragment
  265. OCFile file = getFile();
  266. Fragment secondFragment = chooseInitialSecondFragment(file);
  267. if (secondFragment != null) {
  268. setSecondFragment(secondFragment);
  269. updateFragmentsVisibility(true);
  270. updateNavigationElementsInActionBar(file);
  271. } else {
  272. cleanSecondFragment();
  273. }
  274. } else {
  275. Log_OC.wtf(TAG, "initFragments() called with invalid NULLs!");
  276. if (getAccount() == null) {
  277. Log_OC.wtf(TAG, "\t account is NULL");
  278. }
  279. if (getFile() == null) {
  280. Log_OC.wtf(TAG, "\t file is NULL");
  281. }
  282. }
  283. }
  284. private Fragment chooseInitialSecondFragment(OCFile file) {
  285. Fragment secondFragment = null;
  286. if (file != null && !file.isFolder()) {
  287. if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
  288. && file.getLastSyncDateForProperties() > 0 // temporal fix
  289. ) {
  290. int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
  291. boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
  292. secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
  293. } else {
  294. secondFragment = new FileDetailFragment(file, getAccount());
  295. }
  296. }
  297. return secondFragment;
  298. }
  299. /**
  300. * Replaces the second fragment managed by the activity with the received as
  301. * a parameter.
  302. *
  303. * Assumes never will be more than two fragments managed at the same time.
  304. *
  305. * @param fragment New second Fragment to set.
  306. */
  307. private void setSecondFragment(Fragment fragment) {
  308. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  309. transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
  310. transaction.commit();
  311. }
  312. private void updateFragmentsVisibility(boolean existsSecondFragment) {
  313. if (mDualPane) {
  314. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  315. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  316. }
  317. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  318. mRightFragmentContainer.setVisibility(View.VISIBLE);
  319. }
  320. } else if (existsSecondFragment) {
  321. if (mLeftFragmentContainer.getVisibility() != View.GONE) {
  322. mLeftFragmentContainer.setVisibility(View.GONE);
  323. }
  324. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  325. mRightFragmentContainer.setVisibility(View.VISIBLE);
  326. }
  327. } else {
  328. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  329. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  330. }
  331. if (mRightFragmentContainer.getVisibility() != View.GONE) {
  332. mRightFragmentContainer.setVisibility(View.GONE);
  333. }
  334. }
  335. }
  336. private OCFileListFragment getListOfFilesFragment() {
  337. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
  338. if (listOfFiles != null) {
  339. return (OCFileListFragment)listOfFiles;
  340. }
  341. Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
  342. return null;
  343. }
  344. public FileFragment getSecondFragment() {
  345. Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
  346. if (second != null) {
  347. return (FileFragment)second;
  348. }
  349. return null;
  350. }
  351. protected void cleanSecondFragment() {
  352. Fragment second = getSecondFragment();
  353. if (second != null) {
  354. FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
  355. tr.remove(second);
  356. tr.commit();
  357. }
  358. updateFragmentsVisibility(false);
  359. updateNavigationElementsInActionBar(null);
  360. }
  361. protected void refreshListOfFilesFragment() {
  362. OCFileListFragment fileListFragment = getListOfFilesFragment();
  363. if (fileListFragment != null) {
  364. fileListFragment.listDirectory();
  365. }
  366. }
  367. protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
  368. FileFragment secondFragment = getSecondFragment();
  369. boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
  370. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  371. FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
  372. OCFile fileInFragment = detailsFragment.getFile();
  373. if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  374. // the user browsed to other file ; forget the automatic preview
  375. mWaitingToPreview = null;
  376. } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
  377. // grant that the right panel updates the progress bar
  378. detailsFragment.listenForTransferProgress();
  379. detailsFragment.updateFileDetails(true, false);
  380. } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
  381. // update the right panel
  382. boolean detailsFragmentChanged = false;
  383. if (waitedPreview) {
  384. if (success) {
  385. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
  386. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  387. startMediaPreview(mWaitingToPreview, 0, true);
  388. detailsFragmentChanged = true;
  389. } else {
  390. getFileOperationsHelper().openFile(mWaitingToPreview);
  391. }
  392. }
  393. mWaitingToPreview = null;
  394. }
  395. if (!detailsFragmentChanged) {
  396. detailsFragment.updateFileDetails(false, (success));
  397. }
  398. }
  399. }
  400. }
  401. @Override
  402. public boolean onPrepareOptionsMenu(Menu menu) {
  403. if (BuildConfig.DEBUG) {
  404. menu.findItem(R.id.action_logger).setVisible(true);
  405. } else {
  406. menu.findItem(R.id.action_logger).setVisible(false);
  407. }
  408. return super.onPrepareOptionsMenu(menu);
  409. }
  410. @Override
  411. public boolean onCreateOptionsMenu(Menu menu) {
  412. MenuInflater inflater = getSherlock().getMenuInflater();
  413. inflater.inflate(R.menu.main_menu, menu);
  414. return true;
  415. }
  416. @Override
  417. public boolean onOptionsItemSelected(MenuItem item) {
  418. boolean retval = true;
  419. switch (item.getItemId()) {
  420. case R.id.action_create_dir: {
  421. CreateFolderDialogFragment dialog =
  422. CreateFolderDialogFragment.newInstance(getCurrentDir());
  423. dialog.show(getSupportFragmentManager(), "createdirdialog");
  424. break;
  425. }
  426. case R.id.action_sync_account: {
  427. startSynchronization();
  428. break;
  429. }
  430. case R.id.action_upload: {
  431. showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
  432. break;
  433. }
  434. case R.id.action_settings: {
  435. Intent settingsIntent = new Intent(this, Preferences.class);
  436. startActivity(settingsIntent);
  437. break;
  438. }
  439. case R.id.action_logger: {
  440. Intent loggerIntent = new Intent(getApplicationContext(),LogHistoryActivity.class);
  441. startActivity(loggerIntent);
  442. break;
  443. }
  444. case android.R.id.home: {
  445. FileFragment second = getSecondFragment();
  446. OCFile currentDir = getCurrentDir();
  447. if((currentDir != null && currentDir.getParentId() != 0) ||
  448. (second != null && second.getFile() != null)) {
  449. onBackPressed();
  450. }
  451. break;
  452. }
  453. case R.id.action_sort: {
  454. SharedPreferences appPreferences = PreferenceManager
  455. .getDefaultSharedPreferences(this);
  456. // Read sorting order, default to sort by name ascending
  457. Integer sortOrder = appPreferences
  458. .getInt("sortOrder", FileStorageUtils.SORT_NAME);
  459. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  460. builder.setTitle(R.string.actionbar_sort_title)
  461. .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder , new DialogInterface.OnClickListener() {
  462. public void onClick(DialogInterface dialog, int which) {
  463. switch (which){
  464. case 0:
  465. sortByName(true);
  466. break;
  467. case 1:
  468. sortByDate(false);
  469. break;
  470. // TODO re-enable when server-side folder size calculation is available
  471. // case 2:
  472. // sortBySize(false);
  473. // break;
  474. }
  475. dialog.dismiss();
  476. }
  477. });
  478. builder.create().show();
  479. break;
  480. }
  481. default:
  482. retval = super.onOptionsItemSelected(item);
  483. }
  484. return retval;
  485. }
  486. private void startSynchronization() {
  487. Log_OC.d(TAG, "Got to start sync");
  488. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  489. Log_OC.d(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  490. ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
  491. Bundle bundle = new Bundle();
  492. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  493. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  494. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
  495. ContentResolver.requestSync(
  496. getAccount(),
  497. MainApp.getAuthority(), bundle);
  498. } else {
  499. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
  500. SyncRequest.Builder builder = new SyncRequest.Builder();
  501. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  502. builder.setExpedited(true);
  503. builder.setManual(true);
  504. builder.syncOnce();
  505. // Fix bug in Android Lollipop when you click on refresh the whole account
  506. Bundle extras = new Bundle();
  507. builder.setExtras(extras);
  508. SyncRequest request = builder.build();
  509. ContentResolver.requestSync(request);
  510. }
  511. }
  512. @Override
  513. public boolean onNavigationItemSelected(int itemPosition, long itemId) {
  514. if (itemPosition != 0) {
  515. String targetPath = "";
  516. for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
  517. targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
  518. }
  519. targetPath = OCFile.PATH_SEPARATOR + targetPath;
  520. OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
  521. if (targetFolder != null) {
  522. browseTo(targetFolder);
  523. }
  524. // the next operation triggers a new call to this method, but it's necessary to
  525. // ensure that the name exposed in the action bar is the current directory when the
  526. // user selected it in the navigation list
  527. if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
  528. getSupportActionBar().setSelectedNavigationItem(0);
  529. }
  530. return true;
  531. }
  532. /**
  533. * Called, when the user selected something for uploading
  534. *
  535. */
  536. @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  537. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  538. super.onActivityResult(requestCode, resultCode, data);
  539. if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  540. //getClipData is only supported on api level 16+, Jelly Bean
  541. if (data.getData() == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
  542. for( int i = 0; i < data.getClipData().getItemCount(); i++){
  543. Intent intent = new Intent();
  544. intent.setData(data.getClipData().getItemAt(i).getUri());
  545. requestSimpleUpload(intent, resultCode);
  546. }
  547. }else {
  548. requestSimpleUpload(data, resultCode);
  549. }
  550. } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  551. requestMultipleUpload(data, resultCode);
  552. } else if (requestCode == ACTION_MOVE_FILES && resultCode == RESULT_OK){
  553. final Intent fData = data;
  554. final int fResultCode = resultCode;
  555. getHandler().postDelayed(
  556. new Runnable() {
  557. @Override
  558. public void run() {
  559. requestMoveOperation(fData, fResultCode);
  560. }
  561. },
  562. DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
  563. );
  564. }
  565. }
  566. private void requestMultipleUpload(Intent data, int resultCode) {
  567. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  568. if (filePaths != null) {
  569. String[] remotePaths = new String[filePaths.length];
  570. String remotePathBase = "";
  571. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  572. remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  573. }
  574. if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
  575. remotePathBase += OCFile.PATH_SEPARATOR;
  576. for (int j = 0; j< remotePaths.length; j++) {
  577. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  578. }
  579. Intent i = new Intent(this, FileUploader.class);
  580. i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
  581. i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
  582. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
  583. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
  584. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  585. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  586. startService(i);
  587. } else {
  588. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  589. Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
  590. t.show();
  591. return;
  592. }
  593. }
  594. private void requestSimpleUpload(Intent data, int resultCode) {
  595. String filepath = null;
  596. String mimeType = null;
  597. Uri selectedImageUri = data.getData();
  598. try {
  599. mimeType = getContentResolver().getType(selectedImageUri);
  600. String filemanagerstring = selectedImageUri.getPath();
  601. String selectedImagePath = getPath(selectedImageUri);
  602. if (selectedImagePath != null)
  603. filepath = selectedImagePath;
  604. else
  605. filepath = filemanagerstring;
  606. } catch (Exception e) {
  607. Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
  608. e.printStackTrace();
  609. } finally {
  610. if (filepath == null) {
  611. Log_OC.e(TAG, "Couldn't resolve path to file");
  612. Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
  613. t.show();
  614. return;
  615. }
  616. }
  617. Intent i = new Intent(this, FileUploader.class);
  618. i.putExtra(FileUploader.KEY_ACCOUNT,
  619. getAccount());
  620. String remotepath = new String();
  621. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  622. remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  623. }
  624. if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
  625. remotepath += OCFile.PATH_SEPARATOR;
  626. if (filepath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
  627. Cursor cursor = MainApp.getAppContext().getContentResolver()
  628. .query(Uri.parse(filepath), null, null, null, null, null);
  629. try {
  630. if (cursor != null && cursor.moveToFirst()) {
  631. String displayName = cursor.getString(
  632. cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
  633. Log.i(TAG, "Display Name: " + displayName + "; mimeType: " + mimeType);
  634. displayName.replace(File.separatorChar, '_');
  635. displayName.replace(File.pathSeparatorChar, '_');
  636. remotepath += displayName + DisplayUtils.getComposedFileExtension(filepath);
  637. }
  638. } finally {
  639. cursor.close();
  640. }
  641. } else {
  642. remotepath += new File(filepath).getName();
  643. }
  644. i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
  645. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
  646. i.putExtra(FileUploader.KEY_MIME_TYPE, mimeType);
  647. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
  648. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  649. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  650. startService(i);
  651. }
  652. /**
  653. * Request the operation for moving the file/folder from one path to another
  654. *
  655. * @param data Intent received
  656. * @param resultCode Result code received
  657. */
  658. private void requestMoveOperation(Intent data, int resultCode) {
  659. OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  660. OCFile targetFile = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
  661. getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
  662. }
  663. @Override
  664. public void onBackPressed() {
  665. OCFileListFragment listOfFiles = getListOfFilesFragment();
  666. if (mDualPane || getSecondFragment() == null) {
  667. if (listOfFiles != null) { // should never be null, indeed
  668. if (mDirectories.getCount() <= 1) {
  669. finish();
  670. return;
  671. }
  672. int levelsUp = listOfFiles.onBrowseUp();
  673. for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
  674. popDirname();
  675. }
  676. }
  677. }
  678. if (listOfFiles != null) { // should never be null, indeed
  679. setFile(listOfFiles.getCurrentFile());
  680. }
  681. cleanSecondFragment();
  682. }
  683. @Override
  684. protected void onSaveInstanceState(Bundle outState) {
  685. // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
  686. Log_OC.d(TAG, "onSaveInstanceState() start");
  687. super.onSaveInstanceState(outState);
  688. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  689. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  690. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
  691. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  692. Log_OC.d(TAG, "onSaveInstanceState() end");
  693. }
  694. @Override
  695. protected void onResume() {
  696. super.onResume();
  697. Log_OC.d(TAG, "onResume() start");
  698. // refresh list of files
  699. refreshListOfFilesFragment();
  700. // Listen for sync messages
  701. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  702. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  703. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  704. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  705. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  706. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  707. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  708. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  709. // Listen for upload messages
  710. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  711. mUploadFinishReceiver = new UploadFinishReceiver();
  712. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  713. // Listen for download messages
  714. IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
  715. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  716. mDownloadFinishReceiver = new DownloadFinishReceiver();
  717. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  718. Log_OC.d(TAG, "onResume() end");
  719. }
  720. @Override
  721. protected void onPause() {
  722. Log_OC.d(TAG, "onPause() start");
  723. if (mSyncBroadcastReceiver != null) {
  724. unregisterReceiver(mSyncBroadcastReceiver);
  725. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  726. mSyncBroadcastReceiver = null;
  727. }
  728. if (mUploadFinishReceiver != null) {
  729. unregisterReceiver(mUploadFinishReceiver);
  730. mUploadFinishReceiver = null;
  731. }
  732. if (mDownloadFinishReceiver != null) {
  733. unregisterReceiver(mDownloadFinishReceiver);
  734. mDownloadFinishReceiver = null;
  735. }
  736. Log_OC.d(TAG, "onPause() end");
  737. super.onPause();
  738. }
  739. @Override
  740. protected Dialog onCreateDialog(int id) {
  741. Dialog dialog = null;
  742. AlertDialog.Builder builder;
  743. switch (id) {
  744. case DIALOG_SHORT_WAIT: {
  745. ProgressDialog working_dialog = new ProgressDialog(this);
  746. working_dialog.setMessage(getResources().getString(
  747. R.string.wait_a_moment));
  748. working_dialog.setIndeterminate(true);
  749. working_dialog.setCancelable(false);
  750. dialog = working_dialog;
  751. break;
  752. }
  753. case DIALOG_CHOOSE_UPLOAD_SOURCE: {
  754. String[] allTheItems = { getString(R.string.actionbar_upload_files),
  755. getString(R.string.actionbar_upload_from_apps) };
  756. builder = new AlertDialog.Builder(this);
  757. builder.setTitle(R.string.actionbar_upload);
  758. builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
  759. public void onClick(DialogInterface dialog, int item) {
  760. if (item == 0) {
  761. // if (!mDualPane) {
  762. Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
  763. action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
  764. startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
  765. // } else {
  766. // TODO create and handle new fragment
  767. // LocalFileListFragment
  768. // }
  769. } else if (item == 1) {
  770. Intent action = new Intent(Intent.ACTION_GET_CONTENT);
  771. action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
  772. //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
  773. if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
  774. action.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
  775. }
  776. startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
  777. ACTION_SELECT_CONTENT_FROM_APPS);
  778. }
  779. }
  780. });
  781. dialog = builder.create();
  782. break;
  783. }
  784. case DIALOG_CERT_NOT_SAVED: {
  785. builder = new AlertDialog.Builder(this);
  786. builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
  787. builder.setCancelable(false);
  788. builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
  789. @Override
  790. public void onClick(DialogInterface dialog, int which) {
  791. dialog.dismiss();
  792. };
  793. });
  794. dialog = builder.create();
  795. break;
  796. }
  797. default:
  798. dialog = null;
  799. }
  800. return dialog;
  801. }
  802. /**
  803. * Translates a content URI of an content to a physical path on the disk
  804. *
  805. * @param uri The URI to resolve
  806. * @return The path to the content or null if it could not be found
  807. */
  808. public String getPath(Uri uri) {
  809. final boolean isKitKatOrLater = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
  810. // DocumentProvider
  811. if (isKitKatOrLater && DocumentsContract.isDocumentUri(getApplicationContext(), uri)) {
  812. // ExternalStorageProvider
  813. if (UriUtils.isExternalStorageDocument(uri)) {
  814. final String docId = DocumentsContract.getDocumentId(uri);
  815. final String[] split = docId.split(":");
  816. final String type = split[0];
  817. if ("primary".equalsIgnoreCase(type)) {
  818. return Environment.getExternalStorageDirectory() + "/" + split[1];
  819. }
  820. }
  821. // DownloadsProvider
  822. else if (UriUtils.isDownloadsDocument(uri)) {
  823. final String id = DocumentsContract.getDocumentId(uri);
  824. final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
  825. Long.valueOf(id));
  826. return UriUtils.getDataColumn(getApplicationContext(), contentUri, null, null);
  827. }
  828. // MediaProvider
  829. else if (UriUtils.isMediaDocument(uri)) {
  830. final String docId = DocumentsContract.getDocumentId(uri);
  831. final String[] split = docId.split(":");
  832. final String type = split[0];
  833. Uri contentUri = null;
  834. if ("image".equals(type)) {
  835. contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
  836. } else if ("video".equals(type)) {
  837. contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
  838. } else if ("audio".equals(type)) {
  839. contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  840. }
  841. final String selection = "_id=?";
  842. final String[] selectionArgs = new String[] { split[1] };
  843. return UriUtils.getDataColumn(getApplicationContext(), contentUri, selection, selectionArgs);
  844. }
  845. // Documents providers returned as content://...
  846. else if (UriUtils.isContentDocument(uri)) {
  847. return uri.toString();
  848. }
  849. }
  850. // MediaStore (and general)
  851. else if ("content".equalsIgnoreCase(uri.getScheme())) {
  852. // Return the remote address
  853. if (UriUtils.isGooglePhotosUri(uri))
  854. return uri.getLastPathSegment();
  855. return UriUtils.getDataColumn(getApplicationContext(), uri, null, null);
  856. }
  857. // File
  858. else if ("file".equalsIgnoreCase(uri.getScheme())) {
  859. return uri.getPath();
  860. }
  861. return null;
  862. }
  863. /**
  864. * Pushes a directory to the drop down list
  865. * @param directory to push
  866. * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
  867. */
  868. public void pushDirname(OCFile directory) {
  869. if(!directory.isFolder()){
  870. throw new IllegalArgumentException("Only directories may be pushed!");
  871. }
  872. mDirectories.insert(directory.getFileName(), 0);
  873. setFile(directory);
  874. }
  875. /**
  876. * Pops a directory name from the drop down list
  877. * @return True, unless the stack is empty
  878. */
  879. public boolean popDirname() {
  880. mDirectories.remove(mDirectories.getItem(0));
  881. return !mDirectories.isEmpty();
  882. }
  883. // Custom array adapter to override text colors
  884. private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
  885. public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
  886. super(ctx, view);
  887. }
  888. public View getView(int position, View convertView, ViewGroup parent) {
  889. View v = super.getView(position, convertView, parent);
  890. ((TextView) v).setTextColor(getResources().getColorStateList(
  891. android.R.color.white));
  892. fixRoot((TextView) v );
  893. return v;
  894. }
  895. public View getDropDownView(int position, View convertView,
  896. ViewGroup parent) {
  897. View v = super.getDropDownView(position, convertView, parent);
  898. ((TextView) v).setTextColor(getResources().getColorStateList(
  899. android.R.color.white));
  900. fixRoot((TextView) v );
  901. return v;
  902. }
  903. private void fixRoot(TextView v) {
  904. if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
  905. v.setText(R.string.default_display_name_for_root_folder);
  906. }
  907. }
  908. }
  909. private class SyncBroadcastReceiver extends BroadcastReceiver {
  910. /**
  911. * {@link BroadcastReceiver} to enable syncing feedback in UI
  912. */
  913. @Override
  914. public void onReceive(Context context, Intent intent) {
  915. try {
  916. String event = intent.getAction();
  917. Log_OC.d(TAG, "Received broadcast " + event);
  918. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  919. String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  920. RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
  921. boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
  922. if (sameAccount) {
  923. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  924. mSyncInProgress = true;
  925. } else {
  926. OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
  927. OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  928. if (currentDir == null) {
  929. // current folder was removed from the server
  930. Toast.makeText( FileDisplayActivity.this,
  931. String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
  932. Toast.LENGTH_LONG)
  933. .show();
  934. browseToRoot();
  935. } else {
  936. if (currentFile == null && !getFile().isFolder()) {
  937. // currently selected file was removed in the server, and now we know it
  938. cleanSecondFragment();
  939. currentFile = currentDir;
  940. }
  941. if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  942. OCFileListFragment fileListFragment = getListOfFilesFragment();
  943. if (fileListFragment != null) {
  944. fileListFragment.listDirectory(currentDir);
  945. }
  946. }
  947. setFile(currentFile);
  948. }
  949. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
  950. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
  951. equals(event) &&
  952. /// TODO refactor and make common
  953. synchResult != null && !synchResult.isSuccess() &&
  954. (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
  955. synchResult.isIdPRedirection() ||
  956. (synchResult.isException() && synchResult.getException()
  957. instanceof AuthenticatorException))) {
  958. try {
  959. OwnCloudClient client;
  960. OwnCloudAccount ocAccount =
  961. new OwnCloudAccount(getAccount(), context);
  962. client = (OwnCloudClientManagerFactory.getDefaultSingleton().
  963. removeClientFor(ocAccount));
  964. if (client != null) {
  965. OwnCloudCredentials cred = client.getCredentials();
  966. if (cred != null) {
  967. AccountManager am = AccountManager.get(context);
  968. if (cred.authTokenExpires()) {
  969. am.invalidateAuthToken(
  970. getAccount().type,
  971. cred.getAuthToken()
  972. );
  973. } else {
  974. am.clearPassword(getAccount());
  975. }
  976. }
  977. }
  978. requestCredentialsUpdate();
  979. } catch (AccountNotFoundException e) {
  980. Log_OC.e(TAG, "Account " + getAccount() + " was removed!", e);
  981. }
  982. }
  983. }
  984. removeStickyBroadcast(intent);
  985. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  986. setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
  987. setBackgroundText();
  988. }
  989. if (synchResult != null) {
  990. if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  991. mLastSslUntrustedServerResult = synchResult;
  992. }
  993. }
  994. } catch (RuntimeException e) {
  995. // avoid app crashes after changing the serial id of RemoteOperationResult
  996. // in owncloud library with broadcast notifications pending to process
  997. removeStickyBroadcast(intent);
  998. }
  999. }
  1000. }
  1001. /**
  1002. * Show a text message on screen view for notifying user if content is
  1003. * loading or folder is empty
  1004. */
  1005. private void setBackgroundText() {
  1006. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  1007. if (ocFileListFragment != null) {
  1008. int message = R.string.file_list_loading;
  1009. if (!mSyncInProgress) {
  1010. // In case file list is empty
  1011. message = R.string.file_list_empty;
  1012. }
  1013. ocFileListFragment.setMessageForEmptyList(getString(message));
  1014. } else {
  1015. Log_OC.e(TAG, "OCFileListFragment is null");
  1016. }
  1017. }
  1018. /**
  1019. * Once the file upload has finished -> update view
  1020. */
  1021. private class UploadFinishReceiver extends BroadcastReceiver {
  1022. /**
  1023. * Once the file upload has finished -> update view
  1024. * @author David A. Velasco
  1025. * {@link BroadcastReceiver} to enable upload feedback in UI
  1026. */
  1027. @Override
  1028. public void onReceive(Context context, Intent intent) {
  1029. try {
  1030. String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  1031. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  1032. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  1033. OCFile currentDir = getCurrentDir();
  1034. boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
  1035. (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
  1036. if (sameAccount && isDescendant) {
  1037. refreshListOfFilesFragment();
  1038. }
  1039. boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
  1040. boolean renamedInUpload = getFile().getRemotePath().
  1041. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  1042. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  1043. renamedInUpload;
  1044. FileFragment details = getSecondFragment();
  1045. boolean detailFragmentIsShown = (details != null &&
  1046. details instanceof FileDetailFragment);
  1047. if (sameAccount && sameFile && detailFragmentIsShown) {
  1048. if (uploadWasFine) {
  1049. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  1050. }
  1051. if (renamedInUpload) {
  1052. String newName = (new File(uploadedRemotePath)).getName();
  1053. Toast msg = Toast.makeText(
  1054. context,
  1055. String.format(
  1056. getString(R.string.filedetails_renamed_in_upload_msg),
  1057. newName),
  1058. Toast.LENGTH_LONG);
  1059. msg.show();
  1060. }
  1061. if (uploadWasFine || getFile().fileExists()) {
  1062. ((FileDetailFragment)details).updateFileDetails(false, true);
  1063. } else {
  1064. cleanSecondFragment();
  1065. }
  1066. // Force the preview if the file is an image
  1067. if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
  1068. startImagePreview(getFile());
  1069. } // TODO what about other kind of previews?
  1070. }
  1071. } finally {
  1072. if (intent != null) {
  1073. removeStickyBroadcast(intent);
  1074. }
  1075. }
  1076. }
  1077. }
  1078. /**
  1079. * Class waiting for broadcast events from the {@link FileDownloader} service.
  1080. *
  1081. * Updates the UI when a download is started or finished, provided that it is relevant for the
  1082. * current folder.
  1083. */
  1084. private class DownloadFinishReceiver extends BroadcastReceiver {
  1085. //int refreshCounter = 0;
  1086. @Override
  1087. public void onReceive(Context context, Intent intent) {
  1088. try {
  1089. boolean sameAccount = isSameAccount(context, intent);
  1090. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  1091. boolean isDescendant = isDescendant(downloadedRemotePath);
  1092. if (sameAccount && isDescendant) {
  1093. String linkedToRemotePath = intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
  1094. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1095. //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
  1096. refreshListOfFilesFragment();
  1097. }
  1098. refreshSecondFragment(
  1099. intent.getAction(),
  1100. downloadedRemotePath,
  1101. intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false)
  1102. );
  1103. }
  1104. if (mWaitingToSend != null) {
  1105. mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
  1106. if (mWaitingToSend.isDown()) {
  1107. sendDownloadedFile();
  1108. }
  1109. }
  1110. } finally {
  1111. if (intent != null) {
  1112. removeStickyBroadcast(intent);
  1113. }
  1114. }
  1115. }
  1116. private boolean isDescendant(String downloadedRemotePath) {
  1117. OCFile currentDir = getCurrentDir();
  1118. return (
  1119. currentDir != null &&
  1120. downloadedRemotePath != null &&
  1121. downloadedRemotePath.startsWith(currentDir.getRemotePath())
  1122. );
  1123. }
  1124. private boolean isAscendant(String linkedToRemotePath) {
  1125. OCFile currentDir = getCurrentDir();
  1126. return (
  1127. currentDir != null &&
  1128. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1129. );
  1130. }
  1131. private boolean isSameAccount(Context context, Intent intent) {
  1132. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  1133. return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
  1134. }
  1135. }
  1136. public void browseToRoot() {
  1137. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1138. if (listOfFiles != null) { // should never be null, indeed
  1139. while (mDirectories.getCount() > 1) {
  1140. popDirname();
  1141. }
  1142. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  1143. listOfFiles.listDirectory(root);
  1144. setFile(listOfFiles.getCurrentFile());
  1145. startSyncFolderOperation(root, false);
  1146. }
  1147. cleanSecondFragment();
  1148. }
  1149. public void browseTo(OCFile folder) {
  1150. if (folder == null || !folder.isFolder()) {
  1151. throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
  1152. }
  1153. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1154. if (listOfFiles != null) {
  1155. setNavigationListWithFolder(folder);
  1156. listOfFiles.listDirectory(folder);
  1157. setFile(listOfFiles.getCurrentFile());
  1158. startSyncFolderOperation(folder, false);
  1159. } else {
  1160. Log_OC.e(TAG, "Unexpected null when accessing list fragment");
  1161. }
  1162. cleanSecondFragment();
  1163. }
  1164. /**
  1165. * {@inheritDoc}
  1166. *
  1167. * Updates action bar and second fragment, if in dual pane mode.
  1168. */
  1169. @Override
  1170. public void onBrowsedDownTo(OCFile directory) {
  1171. pushDirname(directory);
  1172. cleanSecondFragment();
  1173. // Sync Folder
  1174. startSyncFolderOperation(directory, false);
  1175. }
  1176. /**
  1177. * Shows the information of the {@link OCFile} received as a
  1178. * parameter in the second fragment.
  1179. *
  1180. * @param file {@link OCFile} whose details will be shown
  1181. */
  1182. @Override
  1183. public void showDetails(OCFile file) {
  1184. Fragment detailFragment = new FileDetailFragment(file, getAccount());
  1185. setSecondFragment(detailFragment);
  1186. updateFragmentsVisibility(true);
  1187. updateNavigationElementsInActionBar(file);
  1188. setFile(file);
  1189. }
  1190. /**
  1191. * TODO
  1192. */
  1193. private void updateNavigationElementsInActionBar(OCFile chosenFile) {
  1194. ActionBar actionBar = getSupportActionBar();
  1195. if (chosenFile == null || mDualPane) {
  1196. // only list of files - set for browsing through folders
  1197. OCFile currentDir = getCurrentDir();
  1198. boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
  1199. actionBar.setDisplayHomeAsUpEnabled(noRoot);
  1200. actionBar.setDisplayShowTitleEnabled(!noRoot);
  1201. if (!noRoot) {
  1202. actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
  1203. }
  1204. actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
  1205. actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
  1206. } else {
  1207. actionBar.setDisplayHomeAsUpEnabled(true);
  1208. actionBar.setDisplayShowTitleEnabled(true);
  1209. actionBar.setTitle(chosenFile.getFileName());
  1210. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
  1211. }
  1212. }
  1213. @Override
  1214. protected ServiceConnection newTransferenceServiceConnection() {
  1215. return new ListServiceConnection();
  1216. }
  1217. /** Defines callbacks for service binding, passed to bindService() */
  1218. private class ListServiceConnection implements ServiceConnection {
  1219. @Override
  1220. public void onServiceConnected(ComponentName component, IBinder service) {
  1221. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1222. Log_OC.d(TAG, "Download service connected");
  1223. mDownloaderBinder = (FileDownloaderBinder) service;
  1224. if (mWaitingToPreview != null)
  1225. if (getStorageManager() != null) {
  1226. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
  1227. if (!mWaitingToPreview.isDown()) {
  1228. requestForDownload();
  1229. }
  1230. }
  1231. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1232. Log_OC.d(TAG, "Upload service connected");
  1233. mUploaderBinder = (FileUploaderBinder) service;
  1234. } else {
  1235. return;
  1236. }
  1237. // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
  1238. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1239. if (listOfFiles != null) {
  1240. listOfFiles.listDirectory();
  1241. }
  1242. FileFragment secondFragment = getSecondFragment();
  1243. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  1244. FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
  1245. detailFragment.listenForTransferProgress();
  1246. detailFragment.updateFileDetails(false, false);
  1247. }
  1248. }
  1249. @Override
  1250. public void onServiceDisconnected(ComponentName component) {
  1251. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1252. Log_OC.d(TAG, "Download service disconnected");
  1253. mDownloaderBinder = null;
  1254. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1255. Log_OC.d(TAG, "Upload service disconnected");
  1256. mUploaderBinder = null;
  1257. }
  1258. }
  1259. };
  1260. /**
  1261. * Launch an intent to request the PIN code to the user before letting him use the app
  1262. */
  1263. private void requestPinCode() {
  1264. boolean pinStart = false;
  1265. SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  1266. pinStart = appPrefs.getBoolean("set_pincode", false);
  1267. if (pinStart) {
  1268. Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
  1269. i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
  1270. startActivity(i);
  1271. }
  1272. }
  1273. @Override
  1274. public void onSavedCertificate() {
  1275. startSyncFolderOperation(getCurrentDir(), false);
  1276. }
  1277. @Override
  1278. public void onFailedSavingCertificate() {
  1279. showDialog(DIALOG_CERT_NOT_SAVED);
  1280. }
  1281. @Override
  1282. public void onCancelCertificate() {
  1283. // nothing to do
  1284. }
  1285. /**
  1286. * Updates the view associated to the activity after the finish of some operation over files
  1287. * in the current account.
  1288. *
  1289. * @param operation Removal operation performed.
  1290. * @param result Result of the removal.
  1291. */
  1292. @Override
  1293. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1294. super.onRemoteOperationFinish(operation, result);
  1295. if (operation instanceof RemoveFileOperation) {
  1296. onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
  1297. } else if (operation instanceof RenameFileOperation) {
  1298. onRenameFileOperationFinish((RenameFileOperation)operation, result);
  1299. } else if (operation instanceof SynchronizeFileOperation) {
  1300. onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
  1301. } else if (operation instanceof CreateFolderOperation) {
  1302. onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
  1303. } else if (operation instanceof CreateShareOperation) {
  1304. onCreateShareOperationFinish((CreateShareOperation) operation, result);
  1305. } else if (operation instanceof UnshareLinkOperation) {
  1306. onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
  1307. } else if (operation instanceof MoveFileOperation) {
  1308. onMoveFileOperationFinish((MoveFileOperation)operation, result);
  1309. }
  1310. }
  1311. private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
  1312. if (result.isSuccess()) {
  1313. refreshShowDetails();
  1314. refreshListOfFilesFragment();
  1315. }
  1316. }
  1317. private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
  1318. if (result.isSuccess()) {
  1319. refreshShowDetails();
  1320. refreshListOfFilesFragment();
  1321. } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
  1322. cleanSecondFragment();
  1323. refreshListOfFilesFragment();
  1324. }
  1325. }
  1326. private void refreshShowDetails() {
  1327. FileFragment details = getSecondFragment();
  1328. if (details != null) {
  1329. OCFile file = details.getFile();
  1330. if (file != null) {
  1331. file = getStorageManager().getFileByPath(file.getRemotePath());
  1332. if (details instanceof PreviewMediaFragment) {
  1333. // Refresh OCFile of the fragment
  1334. ((PreviewMediaFragment) details).updateFile(file);
  1335. } else {
  1336. showDetails(file);
  1337. }
  1338. }
  1339. invalidateOptionsMenu();
  1340. }
  1341. }
  1342. /**
  1343. * Updates the view associated to the activity after the finish of an operation trying to remove a
  1344. * file.
  1345. *
  1346. * @param operation Removal operation performed.
  1347. * @param result Result of the removal.
  1348. */
  1349. private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
  1350. dismissLoadingDialog();
  1351. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1352. Toast.LENGTH_LONG);
  1353. msg.show();
  1354. if (result.isSuccess()) {
  1355. OCFile removedFile = operation.getFile();
  1356. FileFragment second = getSecondFragment();
  1357. if (second != null && removedFile.equals(second.getFile())) {
  1358. if (second instanceof PreviewMediaFragment) {
  1359. ((PreviewMediaFragment)second).stopPreview(true);
  1360. }
  1361. setFile(getStorageManager().getFileById(removedFile.getParentId()));
  1362. cleanSecondFragment();
  1363. }
  1364. if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
  1365. refreshListOfFilesFragment();
  1366. }
  1367. invalidateOptionsMenu();
  1368. } else {
  1369. if (result.isSslRecoverableException()) {
  1370. mLastSslUntrustedServerResult = result;
  1371. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1372. }
  1373. }
  1374. }
  1375. /**
  1376. * Updates the view associated to the activity after the finish of an operation trying to move a
  1377. * file.
  1378. *
  1379. * @param operation Move operation performed.
  1380. * @param result Result of the move operation.
  1381. */
  1382. private void onMoveFileOperationFinish(MoveFileOperation operation, RemoteOperationResult result) {
  1383. if (result.isSuccess()) {
  1384. dismissLoadingDialog();
  1385. refreshListOfFilesFragment();
  1386. } else {
  1387. dismissLoadingDialog();
  1388. try {
  1389. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1390. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1391. Toast.LENGTH_LONG);
  1392. msg.show();
  1393. } catch (NotFoundException e) {
  1394. Log_OC.e(TAG, "Error while trying to show fail message " , e);
  1395. }
  1396. }
  1397. }
  1398. /**
  1399. * Updates the view associated to the activity after the finish of an operation trying to rename a
  1400. * file.
  1401. *
  1402. * @param operation Renaming operation performed.
  1403. * @param result Result of the renaming.
  1404. */
  1405. private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
  1406. dismissLoadingDialog();
  1407. OCFile renamedFile = operation.getFile();
  1408. if (result.isSuccess()) {
  1409. FileFragment details = getSecondFragment();
  1410. if (details != null) {
  1411. if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
  1412. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1413. showDetails(renamedFile);
  1414. } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
  1415. ((PreviewMediaFragment) details).updateFile(renamedFile);
  1416. if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
  1417. int position = ((PreviewMediaFragment)details).getPosition();
  1418. startMediaPreview(renamedFile, position, true);
  1419. } else {
  1420. getFileOperationsHelper().openFile(renamedFile);
  1421. }
  1422. }
  1423. }
  1424. if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
  1425. refreshListOfFilesFragment();
  1426. }
  1427. } else {
  1428. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1429. Toast.LENGTH_LONG);
  1430. msg.show();
  1431. if (result.isSslRecoverableException()) {
  1432. mLastSslUntrustedServerResult = result;
  1433. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1434. }
  1435. }
  1436. }
  1437. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
  1438. dismissLoadingDialog();
  1439. OCFile syncedFile = operation.getLocalFile();
  1440. if (!result.isSuccess()) {
  1441. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  1442. Intent i = new Intent(this, ConflictsResolveActivity.class);
  1443. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
  1444. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
  1445. startActivity(i);
  1446. }
  1447. } else {
  1448. if (operation.transferWasRequested()) {
  1449. onTransferStateChanged(syncedFile, true, true);
  1450. } else {
  1451. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1452. Toast.LENGTH_LONG);
  1453. msg.show();
  1454. }
  1455. }
  1456. }
  1457. /**
  1458. * Updates the view associated to the activity after the finish of an operation trying create a new folder
  1459. *
  1460. * @param operation Creation operation performed.
  1461. * @param result Result of the creation.
  1462. */
  1463. private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
  1464. if (result.isSuccess()) {
  1465. dismissLoadingDialog();
  1466. refreshListOfFilesFragment();
  1467. } else {
  1468. dismissLoadingDialog();
  1469. try {
  1470. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1471. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1472. Toast.LENGTH_LONG);
  1473. msg.show();
  1474. } catch (NotFoundException e) {
  1475. Log_OC.e(TAG, "Error while trying to show fail message " , e);
  1476. }
  1477. }
  1478. }
  1479. /**
  1480. * {@inheritDoc}
  1481. */
  1482. @Override
  1483. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1484. refreshListOfFilesFragment();
  1485. FileFragment details = getSecondFragment();
  1486. if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
  1487. if (downloading || uploading) {
  1488. ((FileDetailFragment)details).updateFileDetails(file, getAccount());
  1489. } else {
  1490. if (!file.fileExists()) {
  1491. cleanSecondFragment();
  1492. } else {
  1493. ((FileDetailFragment)details).updateFileDetails(false, true);
  1494. }
  1495. }
  1496. }
  1497. }
  1498. private void requestForDownload() {
  1499. Account account = getAccount();
  1500. //if (!mWaitingToPreview.isDownloading()) {
  1501. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1502. Intent i = new Intent(this, FileDownloader.class);
  1503. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1504. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1505. startService(i);
  1506. }
  1507. }
  1508. private OCFile getCurrentDir() {
  1509. OCFile file = getFile();
  1510. if (file != null) {
  1511. if (file.isFolder()) {
  1512. return file;
  1513. } else if (getStorageManager() != null) {
  1514. String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
  1515. return getStorageManager().getFileByPath(parentPath);
  1516. }
  1517. }
  1518. return null;
  1519. }
  1520. public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
  1521. long currentSyncTime = System.currentTimeMillis();
  1522. mSyncInProgress = true;
  1523. // perform folder synchronization
  1524. RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
  1525. currentSyncTime,
  1526. false,
  1527. getFileOperationsHelper().isSharedSupported(),
  1528. ignoreETag,
  1529. getStorageManager(),
  1530. getAccount(),
  1531. getApplicationContext()
  1532. );
  1533. synchFolderOp.execute(getAccount(), this, null, null);
  1534. setSupportProgressBarIndeterminateVisibility(true);
  1535. setBackgroundText();
  1536. }
  1537. /**
  1538. * Show untrusted cert dialog
  1539. */
  1540. public void showUntrustedCertDialog(RemoteOperationResult result) {
  1541. // Show a dialog with the certificate info
  1542. SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
  1543. FragmentManager fm = getSupportFragmentManager();
  1544. FragmentTransaction ft = fm.beginTransaction();
  1545. dialog.show(ft, DIALOG_UNTRUSTED_CERT);
  1546. }
  1547. private void requestForDownload(OCFile file) {
  1548. Account account = getAccount();
  1549. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1550. Intent i = new Intent(this, FileDownloader.class);
  1551. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1552. i.putExtra(FileDownloader.EXTRA_FILE, file);
  1553. startService(i);
  1554. }
  1555. }
  1556. private void sendDownloadedFile(){
  1557. getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
  1558. mWaitingToSend = null;
  1559. }
  1560. /**
  1561. * Requests the download of the received {@link OCFile} , updates the UI
  1562. * to monitor the download progress and prepares the activity to send the file
  1563. * when the download finishes.
  1564. *
  1565. * @param file {@link OCFile} to download and preview.
  1566. */
  1567. public void startDownloadForSending(OCFile file) {
  1568. mWaitingToSend = file;
  1569. requestForDownload(mWaitingToSend);
  1570. boolean hasSecondFragment = (getSecondFragment()!= null);
  1571. updateFragmentsVisibility(hasSecondFragment);
  1572. }
  1573. /**
  1574. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1575. *
  1576. * @param file Image {@link OCFile} to show.
  1577. */
  1578. public void startImagePreview(OCFile file) {
  1579. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1580. showDetailsIntent.putExtra(EXTRA_FILE, file);
  1581. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1582. startActivity(showDetailsIntent);
  1583. }
  1584. /**
  1585. * Stars the preview of an already down media {@link OCFile}.
  1586. *
  1587. * @param file Media {@link OCFile} to preview.
  1588. * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
  1589. * @param autoplay When 'true', the playback will start without user interactions.
  1590. */
  1591. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
  1592. Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
  1593. setSecondFragment(mediaFragment);
  1594. updateFragmentsVisibility(true);
  1595. updateNavigationElementsInActionBar(file);
  1596. setFile(file);
  1597. }
  1598. /**
  1599. * Requests the download of the received {@link OCFile} , updates the UI
  1600. * to monitor the download progress and prepares the activity to preview
  1601. * or open the file when the download finishes.
  1602. *
  1603. * @param file {@link OCFile} to download and preview.
  1604. */
  1605. public void startDownloadForPreview(OCFile file) {
  1606. Fragment detailFragment = new FileDetailFragment(file, getAccount());
  1607. setSecondFragment(detailFragment);
  1608. mWaitingToPreview = file;
  1609. requestForDownload();
  1610. updateFragmentsVisibility(true);
  1611. updateNavigationElementsInActionBar(file);
  1612. setFile(file);
  1613. }
  1614. public void cancelTransference(OCFile file) {
  1615. getFileOperationsHelper().cancelTransference(file);
  1616. if (mWaitingToPreview != null &&
  1617. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  1618. mWaitingToPreview = null;
  1619. }
  1620. if (mWaitingToSend != null &&
  1621. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  1622. mWaitingToSend = null;
  1623. }
  1624. onTransferStateChanged(file, false, false);
  1625. }
  1626. @Override
  1627. public void onRefresh(boolean ignoreETag) {
  1628. refreshList(ignoreETag);
  1629. }
  1630. @Override
  1631. public void onRefresh() {
  1632. refreshList(true);
  1633. }
  1634. private void refreshList(boolean ignoreETag) {
  1635. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1636. if (listOfFiles != null) {
  1637. OCFile folder = listOfFiles.getCurrentFile();
  1638. if (folder != null) {
  1639. /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
  1640. listDirectory(mFile);*/
  1641. startSyncFolderOperation(folder, ignoreETag);
  1642. }
  1643. }
  1644. }
  1645. private void sortByDate(boolean ascending){
  1646. getListOfFilesFragment().sortByDate(ascending);
  1647. }
  1648. private void sortBySize(boolean ascending){
  1649. getListOfFilesFragment().sortBySize(ascending);
  1650. }
  1651. private void sortByName(boolean ascending){
  1652. getListOfFilesFragment().sortByName(ascending);
  1653. }
  1654. }