FileDisplayActivity.java 78 KB

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