FileDisplayActivity.java 79 KB

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