FileDisplayActivity.java 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  1. /* ownCloud Android client application
  2. * Copyright (C) 2011 Bartek Przybylski
  3. * Copyright (C) 2012-2013 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 android.accounts.Account;
  21. import android.app.AlertDialog;
  22. import android.app.Dialog;
  23. import android.app.ProgressDialog;
  24. import android.content.BroadcastReceiver;
  25. import android.content.ComponentName;
  26. import android.content.ContentResolver;
  27. import android.content.Context;
  28. import android.content.DialogInterface;
  29. import android.content.Intent;
  30. import android.content.IntentFilter;
  31. import android.content.ServiceConnection;
  32. import android.content.SharedPreferences;
  33. import android.content.SyncRequest;
  34. import android.content.res.Resources.NotFoundException;
  35. import android.database.Cursor;
  36. import android.net.Uri;
  37. import android.os.Bundle;
  38. import android.os.IBinder;
  39. import android.preference.PreferenceManager;
  40. import android.provider.MediaStore;
  41. import android.support.v4.app.Fragment;
  42. import android.support.v4.app.FragmentManager;
  43. import android.support.v4.app.FragmentTransaction;
  44. //import android.support.v4.content.LocalBroadcastManager;
  45. import android.util.Log;
  46. import android.view.View;
  47. import android.view.ViewGroup;
  48. import android.widget.ArrayAdapter;
  49. import android.widget.TextView;
  50. import android.widget.Toast;
  51. import com.actionbarsherlock.app.ActionBar;
  52. import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
  53. import com.actionbarsherlock.view.Menu;
  54. import com.actionbarsherlock.view.MenuInflater;
  55. import com.actionbarsherlock.view.MenuItem;
  56. import com.actionbarsherlock.view.Window;
  57. import com.owncloud.android.MainApp;
  58. import com.owncloud.android.R;
  59. import com.owncloud.android.datamodel.OCFile;
  60. import com.owncloud.android.files.services.FileDownloader;
  61. import com.owncloud.android.files.services.FileObserverService;
  62. import com.owncloud.android.files.services.FileUploader;
  63. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  64. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  65. import com.owncloud.android.operations.CreateFolderOperation;
  66. import com.owncloud.android.lib.common.operations.RemoteOperation;
  67. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  68. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  69. import com.owncloud.android.operations.CreateShareOperation;
  70. import com.owncloud.android.operations.RemoveFileOperation;
  71. import com.owncloud.android.operations.RenameFileOperation;
  72. import com.owncloud.android.operations.SynchronizeFileOperation;
  73. import com.owncloud.android.operations.SynchronizeFolderOperation;
  74. import com.owncloud.android.operations.UnshareLinkOperation;
  75. import com.owncloud.android.services.OperationsService;
  76. import com.owncloud.android.syncadapter.FileSyncAdapter;
  77. import com.owncloud.android.ui.dialog.EditNameDialog;
  78. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
  79. import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
  80. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
  81. import com.owncloud.android.ui.fragment.FileDetailFragment;
  82. import com.owncloud.android.ui.fragment.FileFragment;
  83. import com.owncloud.android.ui.fragment.OCFileListFragment;
  84. import com.owncloud.android.ui.preview.PreviewImageActivity;
  85. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  86. import com.owncloud.android.ui.preview.PreviewVideoActivity;
  87. import com.owncloud.android.utils.DisplayUtils;
  88. import com.owncloud.android.utils.Log_OC;
  89. /**
  90. * Displays, what files the user has available in his ownCloud.
  91. *
  92. * @author Bartek Przybylski
  93. * @author David A. Velasco
  94. */
  95. public class FileDisplayActivity extends HookActivity implements
  96. OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslUntrustedCertListener, EditNameDialogListener {
  97. private ArrayAdapter<String> mDirectories;
  98. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  99. private UploadFinishReceiver mUploadFinishReceiver;
  100. private DownloadFinishReceiver mDownloadFinishReceiver;
  101. //private OperationsServiceReceiver mOperationsServiceReceiver;
  102. private FileDownloaderBinder mDownloaderBinder = null;
  103. private FileUploaderBinder mUploaderBinder = null;
  104. private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
  105. private RemoteOperationResult mLastSslUntrustedServerResult = null;
  106. private boolean mDualPane;
  107. private View mLeftFragmentContainer;
  108. private View mRightFragmentContainer;
  109. private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  110. private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
  111. //private static final String KEY_REFRESH_SHARES_IN_PROGRESS = "SHARES_IN_PROGRESS";
  112. public static final int DIALOG_SHORT_WAIT = 0;
  113. private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
  114. //private static final int DIALOG_SSL_VALIDATOR = 2;
  115. private static final int DIALOG_CERT_NOT_SAVED = 2;
  116. public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
  117. private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
  118. private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
  119. private static final String TAG = FileDisplayActivity.class.getSimpleName();
  120. private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
  121. private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
  122. private OCFile mWaitingToPreview;
  123. private boolean mSyncInProgress = false;
  124. //private boolean mRefreshSharesInProgress = false;
  125. private String DIALOG_UNTRUSTED_CERT;
  126. @Override
  127. protected void onCreate(Bundle savedInstanceState) {
  128. Log_OC.d(TAG, "onCreate() start");
  129. requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
  130. super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
  131. /// bindings to transference services
  132. mUploadConnection = new ListServiceConnection();
  133. mDownloadConnection = new ListServiceConnection();
  134. bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
  135. bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
  136. // PIN CODE request ; best location is to decide, let's try this first
  137. if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
  138. requestPinCode();
  139. } else if (getIntent().getAction() == null && savedInstanceState == null) {
  140. requestPinCode();
  141. }
  142. /// file observer
  143. Intent observer_intent = new Intent(this, FileObserverService.class);
  144. observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
  145. startService(observer_intent);
  146. /// Load of saved instance state
  147. if(savedInstanceState != null) {
  148. mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
  149. mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
  150. //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
  151. } else {
  152. mWaitingToPreview = null;
  153. mSyncInProgress = false;
  154. //mRefreshSharesInProgress = false;
  155. }
  156. /// USER INTERFACE
  157. // Inflate and set the layout view
  158. setContentView(R.layout.files);
  159. mDualPane = getResources().getBoolean(R.bool.large_land_layout);
  160. mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
  161. mRightFragmentContainer = findViewById(R.id.right_fragment_container);
  162. if (savedInstanceState == null) {
  163. createMinFragments();
  164. } else {
  165. Log_OC.d(TAG, "Init the secondFragment again");
  166. if (mDualPane) {
  167. initFragmentsWithFile();
  168. }
  169. }
  170. // Action bar setup
  171. mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
  172. getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
  173. setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
  174. Log_OC.d(TAG, "onCreate() end");
  175. }
  176. @Override
  177. protected void onStart() {
  178. super.onStart();
  179. getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
  180. refeshListOfFilesFragment();
  181. }
  182. @Override
  183. protected void onDestroy() {
  184. super.onDestroy();
  185. if (mDownloadConnection != null)
  186. unbindService(mDownloadConnection);
  187. if (mUploadConnection != null)
  188. unbindService(mUploadConnection);
  189. }
  190. /**
  191. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  192. */
  193. @Override
  194. protected void onAccountSet(boolean stateWasRecovered) {
  195. super.onAccountSet(stateWasRecovered);
  196. if (getAccount() != null) {
  197. /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
  198. OCFile file = getFile();
  199. // get parent from path
  200. String parentPath = "";
  201. if (file != null) {
  202. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  203. // upload in progress - right now, files are not inserted in the local cache until the upload is successful
  204. // get parent from path
  205. parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
  206. if (getStorageManager().getFileByPath(parentPath) == null)
  207. file = null; // not able to know the directory where the file is uploading
  208. } else {
  209. file = getStorageManager().getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
  210. }
  211. }
  212. if (file == null) {
  213. // fall back to root folder
  214. file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
  215. }
  216. setFile(file);
  217. setNavigationListWithFolder(file);
  218. if (!stateWasRecovered) {
  219. Log_OC.e(TAG, "Initializing Fragments in onAccountChanged..");
  220. initFragmentsWithFile();
  221. if (file.isFolder()) {
  222. startSyncFolderOperation(file);
  223. }
  224. } else {
  225. updateFragmentsVisibility(!file.isFolder());
  226. updateNavigationElementsInActionBar(file.isFolder() ? null : file);
  227. }
  228. }
  229. }
  230. private void setNavigationListWithFolder(OCFile file) {
  231. mDirectories.clear();
  232. OCFile fileIt = file;
  233. String parentPath;
  234. while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
  235. if (fileIt.isFolder()) {
  236. mDirectories.add(fileIt.getFileName());
  237. }
  238. // get parent from path
  239. parentPath = fileIt.getRemotePath().substring(0, fileIt.getRemotePath().lastIndexOf(fileIt.getFileName()));
  240. fileIt = getStorageManager().getFileByPath(parentPath);
  241. }
  242. mDirectories.add(OCFile.PATH_SEPARATOR);
  243. }
  244. private void createMinFragments() {
  245. OCFileListFragment listOfFiles = new OCFileListFragment();
  246. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  247. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  248. transaction.commit();
  249. }
  250. private void initFragmentsWithFile() {
  251. if (getAccount() != null && getFile() != null) {
  252. /// First fragment
  253. OCFileListFragment listOfFiles = getListOfFilesFragment();
  254. if (listOfFiles != null) {
  255. listOfFiles.listDirectory(getCurrentDir());
  256. } else {
  257. Log.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
  258. }
  259. /// Second fragment
  260. OCFile file = getFile();
  261. Fragment secondFragment = chooseInitialSecondFragment(file);
  262. if (secondFragment != null) {
  263. setSecondFragment(secondFragment);
  264. updateFragmentsVisibility(true);
  265. updateNavigationElementsInActionBar(file);
  266. } else {
  267. cleanSecondFragment();
  268. }
  269. } else {
  270. Log.wtf(TAG, "initFragments() called with invalid NULLs!");
  271. if (getAccount() == null) {
  272. Log.wtf(TAG, "\t account is NULL");
  273. }
  274. if (getFile() == null) {
  275. Log.wtf(TAG, "\t file is NULL");
  276. }
  277. }
  278. }
  279. private Fragment chooseInitialSecondFragment(OCFile file) {
  280. Fragment secondFragment = null;
  281. if (file != null && !file.isFolder()) {
  282. if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
  283. && file.getLastSyncDateForProperties() > 0 // temporal fix
  284. ) {
  285. int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
  286. boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
  287. secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
  288. } else {
  289. secondFragment = new FileDetailFragment(file, getAccount());
  290. }
  291. }
  292. return secondFragment;
  293. }
  294. /**
  295. * Replaces the second fragment managed by the activity with the received as
  296. * a parameter.
  297. *
  298. * Assumes never will be more than two fragments managed at the same time.
  299. *
  300. * @param fragment New second Fragment to set.
  301. */
  302. private void setSecondFragment(Fragment fragment) {
  303. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  304. transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
  305. transaction.commit();
  306. }
  307. private void updateFragmentsVisibility(boolean existsSecondFragment) {
  308. if (mDualPane) {
  309. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  310. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  311. }
  312. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  313. mRightFragmentContainer.setVisibility(View.VISIBLE);
  314. }
  315. } else if (existsSecondFragment) {
  316. if (mLeftFragmentContainer.getVisibility() != View.GONE) {
  317. mLeftFragmentContainer.setVisibility(View.GONE);
  318. }
  319. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  320. mRightFragmentContainer.setVisibility(View.VISIBLE);
  321. }
  322. } else {
  323. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  324. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  325. }
  326. if (mRightFragmentContainer.getVisibility() != View.GONE) {
  327. mRightFragmentContainer.setVisibility(View.GONE);
  328. }
  329. }
  330. }
  331. private OCFileListFragment getListOfFilesFragment() {
  332. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
  333. if (listOfFiles != null) {
  334. return (OCFileListFragment)listOfFiles;
  335. }
  336. Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
  337. return null;
  338. }
  339. protected FileFragment getSecondFragment() {
  340. Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
  341. if (second != null) {
  342. return (FileFragment)second;
  343. }
  344. return null;
  345. }
  346. public void cleanSecondFragment() {
  347. Fragment second = getSecondFragment();
  348. if (second != null) {
  349. FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
  350. tr.remove(second);
  351. tr.commit();
  352. }
  353. updateFragmentsVisibility(false);
  354. updateNavigationElementsInActionBar(null);
  355. }
  356. protected void refeshListOfFilesFragment() {
  357. OCFileListFragment fileListFragment = getListOfFilesFragment();
  358. if (fileListFragment != null) {
  359. fileListFragment.listDirectory();
  360. }
  361. }
  362. protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
  363. FileFragment secondFragment = getSecondFragment();
  364. boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
  365. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  366. FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
  367. OCFile fileInFragment = detailsFragment.getFile();
  368. if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  369. // the user browsed to other file ; forget the automatic preview
  370. mWaitingToPreview = null;
  371. } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
  372. // grant that the right panel updates the progress bar
  373. detailsFragment.listenForTransferProgress();
  374. detailsFragment.updateFileDetails(true, false);
  375. } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
  376. // update the right panel
  377. boolean detailsFragmentChanged = false;
  378. if (waitedPreview) {
  379. if (success) {
  380. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
  381. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  382. startMediaPreview(mWaitingToPreview, 0, true);
  383. detailsFragmentChanged = true;
  384. } else {
  385. getFileOperationsHelper().openFile(mWaitingToPreview, this);
  386. }
  387. }
  388. mWaitingToPreview = null;
  389. }
  390. if (!detailsFragmentChanged) {
  391. detailsFragment.updateFileDetails(false, (success));
  392. }
  393. }
  394. }
  395. }
  396. @Override
  397. public boolean onCreateOptionsMenu(Menu menu) {
  398. MenuInflater inflater = getSherlock().getMenuInflater();
  399. inflater.inflate(R.menu.main_menu, menu);
  400. return true;
  401. }
  402. @Override
  403. public boolean onOptionsItemSelected(MenuItem item) {
  404. boolean retval = true;
  405. switch (item.getItemId()) {
  406. case R.id.action_create_dir: {
  407. EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.uploader_info_dirname), "", -1, -1, this);
  408. dialog.show(getSupportFragmentManager(), "createdirdialog");
  409. break;
  410. }
  411. case R.id.action_sync_account: {
  412. startSynchronization();
  413. break;
  414. }
  415. case R.id.action_upload: {
  416. showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
  417. break;
  418. }
  419. case R.id.action_settings: {
  420. Intent settingsIntent = new Intent(this, Preferences.class);
  421. startActivity(settingsIntent);
  422. break;
  423. }
  424. case android.R.id.home: {
  425. FileFragment second = getSecondFragment();
  426. OCFile currentDir = getCurrentDir();
  427. if((currentDir != null && currentDir.getParentId() != 0) ||
  428. (second != null && second.getFile() != null)) {
  429. onBackPressed();
  430. }
  431. break;
  432. }
  433. default:
  434. retval = super.onOptionsItemSelected(item);
  435. }
  436. return retval;
  437. }
  438. private void startSynchronization() {
  439. Log_OC.e(TAG, "Got to start sync");
  440. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  441. Log_OC.e(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  442. ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
  443. Bundle bundle = new Bundle();
  444. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  445. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  446. Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
  447. ContentResolver.requestSync(
  448. getAccount(),
  449. MainApp.getAuthority(), bundle);
  450. } else {
  451. Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
  452. SyncRequest.Builder builder = new SyncRequest.Builder();
  453. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  454. builder.setExpedited(true);
  455. builder.setManual(true);
  456. builder.syncOnce();
  457. SyncRequest request = builder.build();
  458. ContentResolver.requestSync(request);
  459. }
  460. }
  461. @Override
  462. public boolean onNavigationItemSelected(int itemPosition, long itemId) {
  463. if (itemPosition != 0) {
  464. String targetPath = "";
  465. for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
  466. targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
  467. }
  468. targetPath = OCFile.PATH_SEPARATOR + targetPath;
  469. OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
  470. if (targetFolder != null) {
  471. browseTo(targetFolder);
  472. }
  473. // the next operation triggers a new call to this method, but it's necessary to
  474. // ensure that the name exposed in the action bar is the current directory when the
  475. // user selected it in the navigation list
  476. if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
  477. getSupportActionBar().setSelectedNavigationItem(0);
  478. }
  479. return true;
  480. }
  481. /**
  482. * Called, when the user selected something for uploading
  483. */
  484. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  485. super.onActivityResult(requestCode, resultCode, data);
  486. if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  487. requestSimpleUpload(data, resultCode);
  488. } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  489. requestMultipleUpload(data, resultCode);
  490. }
  491. }
  492. private void requestMultipleUpload(Intent data, int resultCode) {
  493. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  494. if (filePaths != null) {
  495. String[] remotePaths = new String[filePaths.length];
  496. String remotePathBase = "";
  497. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  498. remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  499. }
  500. if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
  501. remotePathBase += OCFile.PATH_SEPARATOR;
  502. for (int j = 0; j< remotePaths.length; j++) {
  503. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  504. }
  505. Intent i = new Intent(this, FileUploader.class);
  506. i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
  507. i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
  508. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
  509. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
  510. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  511. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  512. startService(i);
  513. } else {
  514. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  515. Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
  516. t.show();
  517. return;
  518. }
  519. }
  520. private void requestSimpleUpload(Intent data, int resultCode) {
  521. String filepath = null;
  522. try {
  523. Uri selectedImageUri = data.getData();
  524. String filemanagerstring = selectedImageUri.getPath();
  525. String selectedImagePath = getPath(selectedImageUri);
  526. if (selectedImagePath != null)
  527. filepath = selectedImagePath;
  528. else
  529. filepath = filemanagerstring;
  530. } catch (Exception e) {
  531. Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
  532. e.printStackTrace();
  533. } finally {
  534. if (filepath == null) {
  535. Log_OC.e(TAG, "Couldnt resolve path to file");
  536. Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
  537. t.show();
  538. return;
  539. }
  540. }
  541. Intent i = new Intent(this, FileUploader.class);
  542. i.putExtra(FileUploader.KEY_ACCOUNT,
  543. getAccount());
  544. String remotepath = new String();
  545. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  546. remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  547. }
  548. if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
  549. remotepath += OCFile.PATH_SEPARATOR;
  550. remotepath += new File(filepath).getName();
  551. i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
  552. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
  553. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
  554. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  555. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  556. startService(i);
  557. }
  558. @Override
  559. public void onBackPressed() {
  560. OCFileListFragment listOfFiles = getListOfFilesFragment();
  561. if (mDualPane || getSecondFragment() == null) {
  562. if (listOfFiles != null) { // should never be null, indeed
  563. if (mDirectories.getCount() <= 1) {
  564. finish();
  565. return;
  566. }
  567. int levelsUp = listOfFiles.onBrowseUp();
  568. for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
  569. popDirname();
  570. }
  571. }
  572. }
  573. if (listOfFiles != null) { // should never be null, indeed
  574. setFile(listOfFiles.getCurrentFile());
  575. }
  576. cleanSecondFragment();
  577. }
  578. @Override
  579. protected void onSaveInstanceState(Bundle outState) {
  580. // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
  581. Log_OC.e(TAG, "onSaveInstanceState() start");
  582. super.onSaveInstanceState(outState);
  583. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  584. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  585. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
  586. Log_OC.d(TAG, "onSaveInstanceState() end");
  587. }
  588. @Override
  589. protected void onResume() {
  590. super.onResume();
  591. Log_OC.e(TAG, "onResume() start");
  592. // Listen for sync messages
  593. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  594. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  595. //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
  596. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  597. syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  598. syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  599. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  600. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  601. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  602. // Listen for upload messages
  603. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  604. mUploadFinishReceiver = new UploadFinishReceiver();
  605. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  606. // Listen for download messages
  607. IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
  608. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  609. mDownloadFinishReceiver = new DownloadFinishReceiver();
  610. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  611. // Listen for messages from the OperationsService
  612. /*
  613. IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
  614. operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
  615. mOperationsServiceReceiver = new OperationsServiceReceiver();
  616. LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
  617. */
  618. Log_OC.d(TAG, "onResume() end");
  619. }
  620. @Override
  621. protected void onPause() {
  622. super.onPause();
  623. Log_OC.e(TAG, "onPause() start");
  624. if (mSyncBroadcastReceiver != null) {
  625. unregisterReceiver(mSyncBroadcastReceiver);
  626. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  627. mSyncBroadcastReceiver = null;
  628. }
  629. if (mUploadFinishReceiver != null) {
  630. unregisterReceiver(mUploadFinishReceiver);
  631. mUploadFinishReceiver = null;
  632. }
  633. if (mDownloadFinishReceiver != null) {
  634. unregisterReceiver(mDownloadFinishReceiver);
  635. mDownloadFinishReceiver = null;
  636. }
  637. /*
  638. if (mOperationsServiceReceiver != null) {
  639. LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
  640. mOperationsServiceReceiver = null;
  641. }
  642. */
  643. Log_OC.d(TAG, "onPause() end");
  644. }
  645. @Override
  646. protected Dialog onCreateDialog(int id) {
  647. Dialog dialog = null;
  648. AlertDialog.Builder builder;
  649. switch (id) {
  650. case DIALOG_SHORT_WAIT: {
  651. ProgressDialog working_dialog = new ProgressDialog(this);
  652. working_dialog.setMessage(getResources().getString(
  653. R.string.wait_a_moment));
  654. working_dialog.setIndeterminate(true);
  655. working_dialog.setCancelable(false);
  656. dialog = working_dialog;
  657. break;
  658. }
  659. case DIALOG_CHOOSE_UPLOAD_SOURCE: {
  660. String[] items = null;
  661. String[] allTheItems = { getString(R.string.actionbar_upload_files),
  662. getString(R.string.actionbar_upload_from_apps),
  663. getString(R.string.actionbar_failed_instant_upload) };
  664. String[] commonItems = { getString(R.string.actionbar_upload_files),
  665. getString(R.string.actionbar_upload_from_apps) };
  666. if (InstantUploadActivity.IS_ENABLED)
  667. items = allTheItems;
  668. else
  669. items = commonItems;
  670. builder = new AlertDialog.Builder(this);
  671. builder.setTitle(R.string.actionbar_upload);
  672. builder.setItems(items, new DialogInterface.OnClickListener() {
  673. public void onClick(DialogInterface dialog, int item) {
  674. if (item == 0) {
  675. // if (!mDualPane) {
  676. Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
  677. action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
  678. startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
  679. // } else {
  680. // TODO create and handle new fragment
  681. // LocalFileListFragment
  682. // }
  683. } else if (item == 1) {
  684. Intent action = new Intent(Intent.ACTION_GET_CONTENT);
  685. action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
  686. startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
  687. ACTION_SELECT_CONTENT_FROM_APPS);
  688. } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
  689. Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
  690. action.putExtra(FileUploader.KEY_ACCOUNT, FileDisplayActivity.this.getAccount());
  691. startActivity(action);
  692. }
  693. }
  694. });
  695. dialog = builder.create();
  696. break;
  697. }
  698. case DIALOG_CERT_NOT_SAVED: {
  699. builder = new AlertDialog.Builder(this);
  700. builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
  701. builder.setCancelable(false);
  702. builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
  703. @Override
  704. public void onClick(DialogInterface dialog, int which) {
  705. dialog.dismiss();
  706. };
  707. });
  708. dialog = builder.create();
  709. break;
  710. }
  711. default:
  712. dialog = null;
  713. }
  714. return dialog;
  715. }
  716. /**
  717. * Translates a content URI of an image to a physical path
  718. * on the disk
  719. * @param uri The URI to resolve
  720. * @return The path to the image or null if it could not be found
  721. */
  722. public String getPath(Uri uri) {
  723. String[] projection = { MediaStore.Images.Media.DATA };
  724. Cursor cursor = managedQuery(uri, projection, null, null, null);
  725. if (cursor != null) {
  726. int column_index = cursor
  727. .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  728. cursor.moveToFirst();
  729. return cursor.getString(column_index);
  730. }
  731. return null;
  732. }
  733. /**
  734. * Pushes a directory to the drop down list
  735. * @param directory to push
  736. * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
  737. */
  738. public void pushDirname(OCFile directory) {
  739. if(!directory.isFolder()){
  740. throw new IllegalArgumentException("Only directories may be pushed!");
  741. }
  742. mDirectories.insert(directory.getFileName(), 0);
  743. setFile(directory);
  744. }
  745. /**
  746. * Pops a directory name from the drop down list
  747. * @return True, unless the stack is empty
  748. */
  749. public boolean popDirname() {
  750. mDirectories.remove(mDirectories.getItem(0));
  751. return !mDirectories.isEmpty();
  752. }
  753. // Custom array adapter to override text colors
  754. private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
  755. public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
  756. super(ctx, view);
  757. }
  758. public View getView(int position, View convertView, ViewGroup parent) {
  759. View v = super.getView(position, convertView, parent);
  760. ((TextView) v).setTextColor(getResources().getColorStateList(
  761. android.R.color.white));
  762. fixRoot((TextView) v );
  763. return v;
  764. }
  765. public View getDropDownView(int position, View convertView,
  766. ViewGroup parent) {
  767. View v = super.getDropDownView(position, convertView, parent);
  768. ((TextView) v).setTextColor(getResources().getColorStateList(
  769. android.R.color.white));
  770. fixRoot((TextView) v );
  771. return v;
  772. }
  773. private void fixRoot(TextView v) {
  774. if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
  775. v.setText(R.string.default_display_name_for_root_folder);
  776. }
  777. }
  778. }
  779. private class SyncBroadcastReceiver extends BroadcastReceiver {
  780. /**
  781. * {@link BroadcastReceiver} to enable syncing feedback in UI
  782. */
  783. @Override
  784. public void onReceive(Context context, Intent intent) {
  785. String event = intent.getAction();
  786. Log_OC.d(TAG, "Received broadcast " + event);
  787. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  788. String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  789. RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
  790. boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
  791. if (sameAccount) {
  792. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  793. mSyncInProgress = true;
  794. } else {
  795. OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
  796. OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  797. if (currentDir == null) {
  798. // current folder was removed from the server
  799. Toast.makeText( FileDisplayActivity.this,
  800. String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
  801. Toast.LENGTH_LONG)
  802. .show();
  803. browseToRoot();
  804. } else {
  805. if (currentFile == null && !getFile().isFolder()) {
  806. // currently selected file was removed in the server, and now we know it
  807. cleanSecondFragment();
  808. currentFile = currentDir;
  809. }
  810. if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  811. OCFileListFragment fileListFragment = getListOfFilesFragment();
  812. if (fileListFragment != null) {
  813. fileListFragment.listDirectory(currentDir);
  814. }
  815. }
  816. setFile(currentFile);
  817. }
  818. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
  819. /*
  820. if (synchResult != null &&
  821. synchResult.isSuccess() &&
  822. (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
  823. FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
  824. ) &&
  825. !mRefreshSharesInProgress &&
  826. getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
  827. ) {
  828. startGetShares();
  829. }
  830. */
  831. }
  832. removeStickyBroadcast(intent);
  833. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  834. setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
  835. }
  836. if (synchResult != null) {
  837. if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  838. mLastSslUntrustedServerResult = synchResult;
  839. }
  840. }
  841. }
  842. }
  843. private class UploadFinishReceiver extends BroadcastReceiver {
  844. /**
  845. * Once the file upload has finished -> update view
  846. * @author David A. Velasco
  847. * {@link BroadcastReceiver} to enable upload feedback in UI
  848. */
  849. @Override
  850. public void onReceive(Context context, Intent intent) {
  851. String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  852. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  853. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  854. OCFile currentDir = getCurrentDir();
  855. boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
  856. if (sameAccount && isDescendant) {
  857. refeshListOfFilesFragment();
  858. }
  859. }
  860. }
  861. /**
  862. * Class waiting for broadcast events from the {@link FielDownloader} service.
  863. *
  864. * Updates the UI when a download is started or finished, provided that it is relevant for the
  865. * current folder.
  866. */
  867. private class DownloadFinishReceiver extends BroadcastReceiver {
  868. @Override
  869. public void onReceive(Context context, Intent intent) {
  870. boolean sameAccount = isSameAccount(context, intent);
  871. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  872. boolean isDescendant = isDescendant(downloadedRemotePath);
  873. if (sameAccount && isDescendant) {
  874. refeshListOfFilesFragment();
  875. refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
  876. }
  877. removeStickyBroadcast(intent);
  878. }
  879. private boolean isDescendant(String downloadedRemotePath) {
  880. OCFile currentDir = getCurrentDir();
  881. return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
  882. }
  883. private boolean isSameAccount(Context context, Intent intent) {
  884. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  885. return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
  886. }
  887. }
  888. /**
  889. * Class waiting for broadcast events from the {@link OperationsService}.
  890. *
  891. * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
  892. * operation performed in {@link OperationsService}.
  893. *
  894. * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
  895. * probably all the operations associated to the app model.
  896. */
  897. private class OperationsServiceReceiver extends BroadcastReceiver {
  898. @Override
  899. public void onReceive(Context context, Intent intent) {
  900. if (OperationsService.ACTION_OPERATION_ADDED.equals(intent.getAction())) {
  901. } else if (OperationsService.ACTION_OPERATION_FINISHED.equals(intent.getAction())) {
  902. //mRefreshSharesInProgress = false;
  903. Account account = intent.getParcelableExtra(OperationsService.EXTRA_ACCOUNT);
  904. RemoteOperationResult getSharesResult = (RemoteOperationResult)intent.getSerializableExtra(OperationsService.EXTRA_RESULT);
  905. if (getAccount() != null && account.name.equals(getAccount().name)
  906. && getStorageManager() != null
  907. ) {
  908. refeshListOfFilesFragment();
  909. }
  910. if ((getSharesResult != null) &&
  911. RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(getSharesResult.getCode())) {
  912. mLastSslUntrustedServerResult = getSharesResult;
  913. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  914. }
  915. //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
  916. }
  917. }
  918. }
  919. public void browseToRoot() {
  920. OCFileListFragment listOfFiles = getListOfFilesFragment();
  921. if (listOfFiles != null) { // should never be null, indeed
  922. while (mDirectories.getCount() > 1) {
  923. popDirname();
  924. }
  925. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  926. listOfFiles.listDirectory(root);
  927. setFile(listOfFiles.getCurrentFile());
  928. startSyncFolderOperation(root);
  929. }
  930. cleanSecondFragment();
  931. }
  932. public void browseTo(OCFile folder) {
  933. if (folder == null || !folder.isFolder()) {
  934. throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
  935. }
  936. OCFileListFragment listOfFiles = getListOfFilesFragment();
  937. if (listOfFiles != null) {
  938. setNavigationListWithFolder(folder);
  939. listOfFiles.listDirectory(folder);
  940. setFile(listOfFiles.getCurrentFile());
  941. startSyncFolderOperation(folder);
  942. } else {
  943. Log_OC.e(TAG, "Unexpected null when accessing list fragment");
  944. }
  945. cleanSecondFragment();
  946. }
  947. /**
  948. * {@inheritDoc}
  949. *
  950. * Updates action bar and second fragment, if in dual pane mode.
  951. */
  952. @Override
  953. public void onBrowsedDownTo(OCFile directory) {
  954. pushDirname(directory);
  955. cleanSecondFragment();
  956. // Sync Folder
  957. startSyncFolderOperation(directory);
  958. }
  959. /**
  960. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  961. *
  962. * @param file Image {@link OCFile} to show.
  963. */
  964. @Override
  965. public void startImagePreview(OCFile file) {
  966. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  967. showDetailsIntent.putExtra(EXTRA_FILE, file);
  968. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  969. startActivity(showDetailsIntent);
  970. }
  971. /**
  972. * Stars the preview of an already down media {@link OCFile}.
  973. *
  974. * @param file Media {@link OCFile} to preview.
  975. * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
  976. * @param autoplay When 'true', the playback will start without user interactions.
  977. */
  978. @Override
  979. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
  980. Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
  981. setSecondFragment(mediaFragment);
  982. updateFragmentsVisibility(true);
  983. updateNavigationElementsInActionBar(file);
  984. setFile(file);
  985. }
  986. /**
  987. * Requests the download of the received {@link OCFile} , updates the UI
  988. * to monitor the download progress and prepares the activity to preview
  989. * or open the file when the download finishes.
  990. *
  991. * @param file {@link OCFile} to download and preview.
  992. */
  993. @Override
  994. public void startDownloadForPreview(OCFile file) {
  995. Fragment detailFragment = new FileDetailFragment(file, getAccount());
  996. setSecondFragment(detailFragment);
  997. mWaitingToPreview = file;
  998. requestForDownload();
  999. updateFragmentsVisibility(true);
  1000. updateNavigationElementsInActionBar(file);
  1001. setFile(file);
  1002. }
  1003. /**
  1004. * Shows the information of the {@link OCFile} received as a
  1005. * parameter in the second fragment.
  1006. *
  1007. * @param file {@link OCFile} whose details will be shown
  1008. */
  1009. @Override
  1010. public void showDetails(OCFile file) {
  1011. Fragment detailFragment = new FileDetailFragment(file, getAccount());
  1012. setSecondFragment(detailFragment);
  1013. updateFragmentsVisibility(true);
  1014. updateNavigationElementsInActionBar(file);
  1015. setFile(file);
  1016. }
  1017. /**
  1018. * TODO
  1019. */
  1020. private void updateNavigationElementsInActionBar(OCFile chosenFile) {
  1021. ActionBar actionBar = getSupportActionBar();
  1022. if (chosenFile == null || mDualPane) {
  1023. // only list of files - set for browsing through folders
  1024. OCFile currentDir = getCurrentDir();
  1025. boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
  1026. actionBar.setDisplayHomeAsUpEnabled(noRoot);
  1027. actionBar.setDisplayShowTitleEnabled(!noRoot);
  1028. if (!noRoot) {
  1029. actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
  1030. }
  1031. actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
  1032. actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
  1033. } else {
  1034. actionBar.setDisplayHomeAsUpEnabled(true);
  1035. actionBar.setDisplayShowTitleEnabled(true);
  1036. actionBar.setTitle(chosenFile.getFileName());
  1037. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
  1038. }
  1039. }
  1040. /**
  1041. * {@inheritDoc}
  1042. */
  1043. @Override
  1044. public void onFileStateChanged() {
  1045. refeshListOfFilesFragment();
  1046. updateNavigationElementsInActionBar(getSecondFragment().getFile());
  1047. }
  1048. /**
  1049. * {@inheritDoc}
  1050. */
  1051. @Override
  1052. public FileDownloaderBinder getFileDownloaderBinder() {
  1053. return mDownloaderBinder;
  1054. }
  1055. /**
  1056. * {@inheritDoc}
  1057. */
  1058. @Override
  1059. public FileUploaderBinder getFileUploaderBinder() {
  1060. return mUploaderBinder;
  1061. }
  1062. /** Defines callbacks for service binding, passed to bindService() */
  1063. private class ListServiceConnection implements ServiceConnection {
  1064. @Override
  1065. public void onServiceConnected(ComponentName component, IBinder service) {
  1066. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1067. Log_OC.d(TAG, "Download service connected");
  1068. mDownloaderBinder = (FileDownloaderBinder) service;
  1069. if (mWaitingToPreview != null) {
  1070. requestForDownload();
  1071. }
  1072. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1073. Log_OC.d(TAG, "Upload service connected");
  1074. mUploaderBinder = (FileUploaderBinder) service;
  1075. } else {
  1076. return;
  1077. }
  1078. // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
  1079. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1080. if (listOfFiles != null) {
  1081. listOfFiles.listDirectory();
  1082. }
  1083. FileFragment secondFragment = getSecondFragment();
  1084. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  1085. FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
  1086. detailFragment.listenForTransferProgress();
  1087. detailFragment.updateFileDetails(false, false);
  1088. }
  1089. }
  1090. @Override
  1091. public void onServiceDisconnected(ComponentName component) {
  1092. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1093. Log_OC.d(TAG, "Download service disconnected");
  1094. mDownloaderBinder = null;
  1095. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1096. Log_OC.d(TAG, "Upload service disconnected");
  1097. mUploaderBinder = null;
  1098. }
  1099. }
  1100. };
  1101. /**
  1102. * Launch an intent to request the PIN code to the user before letting him use the app
  1103. */
  1104. private void requestPinCode() {
  1105. boolean pinStart = false;
  1106. SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  1107. pinStart = appPrefs.getBoolean("set_pincode", false);
  1108. if (pinStart) {
  1109. Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
  1110. i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
  1111. startActivity(i);
  1112. }
  1113. }
  1114. @Override
  1115. public void onSavedCertificate() {
  1116. startSyncFolderOperation(getCurrentDir());
  1117. }
  1118. @Override
  1119. public void onFailedSavingCertificate() {
  1120. showDialog(DIALOG_CERT_NOT_SAVED);
  1121. }
  1122. /**
  1123. * Updates the view associated to the activity after the finish of some operation over files
  1124. * in the current account.
  1125. *
  1126. * @param operation Removal operation performed.
  1127. * @param result Result of the removal.
  1128. */
  1129. @Override
  1130. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1131. super.onRemoteOperationFinish(operation, result);
  1132. if (operation instanceof RemoveFileOperation) {
  1133. onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
  1134. } else if (operation instanceof RenameFileOperation) {
  1135. onRenameFileOperationFinish((RenameFileOperation)operation, result);
  1136. } else if (operation instanceof SynchronizeFileOperation) {
  1137. onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
  1138. } else if (operation instanceof CreateFolderOperation) {
  1139. onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
  1140. } else if (operation instanceof CreateShareOperation) {
  1141. onCreateShareOperationFinish((CreateShareOperation) operation, result);
  1142. } else if (operation instanceof UnshareLinkOperation) {
  1143. onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
  1144. }
  1145. }
  1146. private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
  1147. if (result.isSuccess()) {
  1148. refreshShowDetails();
  1149. refeshListOfFilesFragment();
  1150. }
  1151. }
  1152. private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
  1153. if (result.isSuccess()) {
  1154. refreshShowDetails();
  1155. refeshListOfFilesFragment();
  1156. } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
  1157. cleanSecondFragment();
  1158. refeshListOfFilesFragment();
  1159. }
  1160. }
  1161. private void refreshShowDetails() {
  1162. FileFragment details = getSecondFragment();
  1163. if (details != null) {
  1164. OCFile file = details.getFile();
  1165. if (file != null) {
  1166. file = getStorageManager().getFileByPath(file.getRemotePath());
  1167. if (details instanceof PreviewMediaFragment) {
  1168. // Refresh OCFile of the fragment
  1169. ((PreviewMediaFragment) details).updateFile(file);
  1170. } else {
  1171. showDetails(file);
  1172. }
  1173. }
  1174. invalidateOptionsMenu();
  1175. }
  1176. }
  1177. /**
  1178. * Updates the view associated to the activity after the finish of an operation trying to remove a
  1179. * file.
  1180. *
  1181. * @param operation Removal operation performed.
  1182. * @param result Result of the removal.
  1183. */
  1184. private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
  1185. dismissLoadingDialog();
  1186. if (result.isSuccess()) {
  1187. Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
  1188. msg.show();
  1189. OCFile removedFile = operation.getFile();
  1190. getSecondFragment();
  1191. FileFragment second = getSecondFragment();
  1192. if (second != null && removedFile.equals(second.getFile())) {
  1193. cleanSecondFragment();
  1194. }
  1195. if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
  1196. refeshListOfFilesFragment();
  1197. }
  1198. } else {
  1199. Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
  1200. msg.show();
  1201. if (result.isSslRecoverableException()) {
  1202. mLastSslUntrustedServerResult = result;
  1203. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1204. }
  1205. }
  1206. }
  1207. /**
  1208. * Updates the view associated to the activity after the finish of an operation trying create a new folder
  1209. *
  1210. * @param operation Creation operation performed.
  1211. * @param result Result of the creation.
  1212. */
  1213. private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
  1214. if (result.isSuccess()) {
  1215. dismissLoadingDialog();
  1216. refeshListOfFilesFragment();
  1217. } else {
  1218. dismissLoadingDialog();
  1219. if (result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME) {
  1220. Toast.makeText(FileDisplayActivity.this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG).show();
  1221. } else {
  1222. try {
  1223. Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
  1224. msg.show();
  1225. } catch (NotFoundException e) {
  1226. Log_OC.e(TAG, "Error while trying to show fail message " , e);
  1227. }
  1228. }
  1229. }
  1230. }
  1231. /**
  1232. * Updates the view associated to the activity after the finish of an operation trying to rename a
  1233. * file.
  1234. *
  1235. * @param operation Renaming operation performed.
  1236. * @param result Result of the renaming.
  1237. */
  1238. private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
  1239. dismissLoadingDialog();
  1240. OCFile renamedFile = operation.getFile();
  1241. if (result.isSuccess()) {
  1242. if (mDualPane) {
  1243. FileFragment details = getSecondFragment();
  1244. if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
  1245. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1246. }
  1247. }
  1248. if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
  1249. refeshListOfFilesFragment();
  1250. }
  1251. } else {
  1252. if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
  1253. Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
  1254. msg.show();
  1255. // TODO throw again the new rename dialog
  1256. } if (result.getCode().equals(ResultCode.INVALID_CHARACTER_IN_NAME)) {
  1257. Toast msg = Toast.makeText(this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG);
  1258. msg.show();
  1259. } else {
  1260. Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
  1261. msg.show();
  1262. if (result.isSslRecoverableException()) {
  1263. mLastSslUntrustedServerResult = result;
  1264. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1265. }
  1266. }
  1267. }
  1268. }
  1269. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
  1270. dismissLoadingDialog();
  1271. OCFile syncedFile = operation.getLocalFile();
  1272. if (!result.isSuccess()) {
  1273. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  1274. Intent i = new Intent(this, ConflictsResolveActivity.class);
  1275. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
  1276. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
  1277. startActivity(i);
  1278. }
  1279. } else {
  1280. if (operation.transferWasRequested()) {
  1281. refeshListOfFilesFragment();
  1282. onTransferStateChanged(syncedFile, true, true);
  1283. } else {
  1284. Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
  1285. msg.show();
  1286. }
  1287. }
  1288. }
  1289. /**
  1290. * {@inheritDoc}
  1291. */
  1292. @Override
  1293. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1294. if (mDualPane) {
  1295. FileFragment details = getSecondFragment();
  1296. if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
  1297. if (downloading || uploading) {
  1298. ((FileDetailFragment)details).updateFileDetails(file, getAccount());
  1299. } else {
  1300. ((FileDetailFragment)details).updateFileDetails(false, true);
  1301. }
  1302. }
  1303. }
  1304. }
  1305. public void onDismiss(EditNameDialog dialog) {
  1306. if (dialog.getResult()) {
  1307. String newDirectoryName = dialog.getNewFilename().trim();
  1308. Log_OC.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
  1309. if (newDirectoryName.length() > 0) {
  1310. String path = getCurrentDir().getRemotePath();
  1311. // Create directory
  1312. path += newDirectoryName + OCFile.PATH_SEPARATOR;
  1313. RemoteOperation operation = new CreateFolderOperation(path, false, getStorageManager());
  1314. operation.execute( getAccount(),
  1315. FileDisplayActivity.this,
  1316. FileDisplayActivity.this,
  1317. getHandler(),
  1318. FileDisplayActivity.this);
  1319. showLoadingDialog();
  1320. }
  1321. }
  1322. }
  1323. private void requestForDownload() {
  1324. Account account = getAccount();
  1325. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1326. Intent i = new Intent(this, FileDownloader.class);
  1327. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1328. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1329. startService(i);
  1330. }
  1331. }
  1332. private OCFile getCurrentDir() {
  1333. OCFile file = getFile();
  1334. if (file != null) {
  1335. if (file.isFolder()) {
  1336. return file;
  1337. } else if (getStorageManager() != null) {
  1338. String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
  1339. return getStorageManager().getFileByPath(parentPath);
  1340. }
  1341. }
  1342. return null;
  1343. }
  1344. public void startSyncFolderOperation(OCFile folder) {
  1345. long currentSyncTime = System.currentTimeMillis();
  1346. mSyncInProgress = true;
  1347. // perform folder synchronization
  1348. RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
  1349. currentSyncTime,
  1350. false,
  1351. getFileOperationsHelper().isSharedSupported(this),
  1352. getStorageManager(),
  1353. getAccount(),
  1354. getApplicationContext()
  1355. );
  1356. synchFolderOp.execute(getAccount(), this, null, null, this);
  1357. setSupportProgressBarIndeterminateVisibility(true);
  1358. }
  1359. /*
  1360. private void startGetShares() {
  1361. // Get shared files/folders
  1362. Intent intent = new Intent(this, OperationsService.class);
  1363. intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
  1364. startService(intent);
  1365. mRefreshSharesInProgress = true;
  1366. }
  1367. */
  1368. /**
  1369. * Show untrusted cert dialog
  1370. */
  1371. public void showUntrustedCertDialog(RemoteOperationResult result) {
  1372. // Show a dialog with the certificate info
  1373. SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstance(result, this);
  1374. FragmentManager fm = getSupportFragmentManager();
  1375. FragmentTransaction ft = fm.beginTransaction();
  1376. dialog.show(ft, DIALOG_UNTRUSTED_CERT);
  1377. }
  1378. /**
  1379. * Dismiss untrusted cert dialog
  1380. */
  1381. public void dismissUntrustedCertDialog(){
  1382. Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_UNTRUSTED_CERT);
  1383. if (frag != null) {
  1384. SslUntrustedCertDialog dialog = (SslUntrustedCertDialog) frag;
  1385. dialog.dismiss();
  1386. }
  1387. }
  1388. @Override
  1389. public void onCancelCertificate() {
  1390. // TODO Auto-generated method stub
  1391. }
  1392. }