FileDisplayActivity.java 78 KB

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