ReceiveExternalFilesActivity.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author masensio
  6. * @author Juan Carlos González Cabrero
  7. * @author David A. Velasco
  8. * Copyright (C) 2012 Bartek Przybylski
  9. * Copyright (C) 2016 ownCloud Inc.
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License version 2,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. package com.owncloud.android.ui.activity;
  24. import android.accounts.Account;
  25. import android.accounts.AccountManager;
  26. import android.accounts.AuthenticatorException;
  27. import android.annotation.SuppressLint;
  28. import android.app.Dialog;
  29. import android.content.BroadcastReceiver;
  30. import android.content.Context;
  31. import android.content.DialogInterface;
  32. import android.content.IntentFilter;
  33. import android.content.DialogInterface.OnCancelListener;
  34. import android.content.DialogInterface.OnClickListener;
  35. import android.content.Intent;
  36. import android.content.SharedPreferences;
  37. import android.content.res.Resources.NotFoundException;
  38. import android.os.Bundle;
  39. import android.os.Parcelable;
  40. import android.support.v4.app.FragmentManager;
  41. import android.support.v7.app.ActionBar;
  42. import android.support.v7.app.AlertDialog;
  43. import android.support.v7.app.AlertDialog.Builder;
  44. import android.view.Menu;
  45. import android.view.MenuInflater;
  46. import android.view.MenuItem;
  47. import android.view.View;
  48. import android.widget.AdapterView;
  49. import android.widget.AdapterView.OnItemClickListener;
  50. import android.widget.Button;
  51. import android.widget.ListView;
  52. import android.widget.Toast;
  53. import com.owncloud.android.MainApp;
  54. import com.owncloud.android.R;
  55. import com.owncloud.android.authentication.AccountAuthenticator;
  56. import com.owncloud.android.datamodel.OCFile;
  57. import com.owncloud.android.db.PreferenceManager;
  58. import com.owncloud.android.files.services.FileUploader;
  59. import com.owncloud.android.lib.common.operations.RemoteOperation;
  60. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  61. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  62. import com.owncloud.android.lib.common.utils.Log_OC;
  63. import com.owncloud.android.operations.CreateFolderOperation;
  64. import com.owncloud.android.operations.RefreshFolderOperation;
  65. import com.owncloud.android.syncadapter.FileSyncAdapter;
  66. import com.owncloud.android.ui.adapter.UploaderAdapter;
  67. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  68. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  69. import com.owncloud.android.ui.asynctasks.CopyAndUploadContentUrisTask;
  70. import com.owncloud.android.ui.fragment.TaskRetainerFragment;
  71. import com.owncloud.android.ui.helpers.UriUploader;
  72. import com.owncloud.android.utils.DisplayUtils;
  73. import com.owncloud.android.utils.ErrorMessageAdapter;
  74. import com.owncloud.android.utils.FileStorageUtils;
  75. import java.util.ArrayList;
  76. import java.util.HashMap;
  77. import java.util.LinkedList;
  78. import java.util.List;
  79. import java.util.Stack;
  80. import java.util.Vector;
  81. /**
  82. * This can be used to upload things to an ownCloud instance.
  83. */
  84. public class ReceiveExternalFilesActivity extends FileActivity
  85. implements OnItemClickListener, android.view.View.OnClickListener,
  86. CopyAndUploadContentUrisTask.OnCopyTmpFilesTaskListener {
  87. private static final String TAG = ReceiveExternalFilesActivity.class.getSimpleName();
  88. private static final String FTAG_ERROR_FRAGMENT = "ERROR_FRAGMENT";
  89. private AccountManager mAccountManager;
  90. private Stack<String> mParents;
  91. private ArrayList<Parcelable> mStreamsToUpload;
  92. private String mUploadPath;
  93. private OCFile mFile;
  94. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  95. private boolean mSyncInProgress = false;
  96. private boolean mAccountSelected;
  97. private boolean mAccountSelectionShowing;
  98. private final static int DIALOG_NO_ACCOUNT = 0;
  99. private final static int DIALOG_MULTIPLE_ACCOUNT = 1;
  100. private final static int REQUEST_CODE__SETUP_ACCOUNT = REQUEST_CODE__LAST_SHARED + 1;
  101. private final static String KEY_PARENTS = "PARENTS";
  102. private final static String KEY_FILE = "FILE";
  103. private final static String KEY_ACCOUNT_SELECTED = "ACCOUNT_SELECTED";
  104. private final static String KEY_ACCOUNT_SELECTION_SHOWING = "ACCOUNT_SELECTION_SHOWING";
  105. private static final String DIALOG_WAIT_COPY_FILE = "DIALOG_WAIT_COPY_FILE";
  106. @Override
  107. protected void onCreate(Bundle savedInstanceState) {
  108. prepareStreamsToUpload();
  109. if (savedInstanceState == null) {
  110. mParents = new Stack<>();
  111. mAccountSelected = false;
  112. mAccountSelectionShowing = false;
  113. } else {
  114. mParents = (Stack<String>) savedInstanceState.getSerializable(KEY_PARENTS);
  115. mFile = savedInstanceState.getParcelable(KEY_FILE);
  116. mAccountSelected = savedInstanceState.getBoolean(KEY_ACCOUNT_SELECTED);
  117. mAccountSelectionShowing = savedInstanceState.getBoolean(KEY_ACCOUNT_SELECTION_SHOWING);
  118. }
  119. super.onCreate(savedInstanceState);
  120. if (mAccountSelected) {
  121. setAccount((Account) savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT));
  122. }
  123. // Listen for sync messages
  124. IntentFilter syncIntentFilter = new IntentFilter(RefreshFolderOperation.
  125. EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  126. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  127. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  128. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  129. // Init Fragment without UI to retain AsyncTask across configuration changes
  130. FragmentManager fm = getSupportFragmentManager();
  131. TaskRetainerFragment taskRetainerFragment =
  132. (TaskRetainerFragment) fm.findFragmentByTag(TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT);
  133. if (taskRetainerFragment == null) {
  134. taskRetainerFragment = new TaskRetainerFragment();
  135. fm.beginTransaction()
  136. .add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit();
  137. } // else, Fragment already created and retained across configuration change
  138. }
  139. @Override
  140. protected void setAccount(Account account, boolean savedAccount) {
  141. if (somethingToUpload()) {
  142. mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
  143. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAccountType());
  144. if (accounts.length == 0) {
  145. Log_OC.i(TAG, "No ownCloud account is available");
  146. showDialog(DIALOG_NO_ACCOUNT);
  147. } else if (accounts.length > 1 && !mAccountSelected && !mAccountSelectionShowing) {
  148. Log_OC.i(TAG, "More than one ownCloud is available");
  149. showDialog(DIALOG_MULTIPLE_ACCOUNT);
  150. mAccountSelectionShowing = true;
  151. } else {
  152. if (!savedAccount) {
  153. setAccount(accounts[0]);
  154. }
  155. }
  156. } else if (getIntent().getStringExtra(Intent.EXTRA_TEXT) != null) {
  157. showErrorDialog(
  158. R.string.uploader_error_message_received_piece_of_text,
  159. R.string.uploader_error_title_no_file_to_upload
  160. );
  161. } else {
  162. showErrorDialog(
  163. R.string.uploader_error_message_no_file_to_upload,
  164. R.string.uploader_error_title_no_file_to_upload
  165. );
  166. }
  167. super.setAccount(account, savedAccount);
  168. }
  169. @Override
  170. protected void onAccountSet(boolean stateWasRecovered) {
  171. super.onAccountSet(mAccountWasRestored);
  172. initTargetFolder();
  173. populateDirectoryList();
  174. }
  175. @Override
  176. protected void onSaveInstanceState(Bundle outState) {
  177. Log_OC.d(TAG, "onSaveInstanceState() start");
  178. super.onSaveInstanceState(outState);
  179. outState.putSerializable(KEY_PARENTS, mParents);
  180. //outState.putParcelable(KEY_ACCOUNT, mAccount);
  181. outState.putParcelable(KEY_FILE, mFile);
  182. outState.putBoolean(KEY_ACCOUNT_SELECTED, mAccountSelected);
  183. outState.putBoolean(KEY_ACCOUNT_SELECTION_SHOWING, mAccountSelectionShowing);
  184. outState.putParcelable(FileActivity.EXTRA_ACCOUNT, getAccount());
  185. Log_OC.d(TAG, "onSaveInstanceState() end");
  186. }
  187. @Override
  188. protected void onDestroy(){
  189. if (mSyncBroadcastReceiver != null) {
  190. unregisterReceiver(mSyncBroadcastReceiver);
  191. }
  192. super.onDestroy();
  193. }
  194. @Override
  195. protected Dialog onCreateDialog(final int id) {
  196. final AlertDialog.Builder builder = new Builder(this);
  197. switch (id) {
  198. case DIALOG_NO_ACCOUNT:
  199. builder.setIcon(R.drawable.ic_warning);
  200. builder.setTitle(R.string.uploader_wrn_no_account_title);
  201. builder.setMessage(String.format(
  202. getString(R.string.uploader_wrn_no_account_text),
  203. getString(R.string.app_name)));
  204. builder.setCancelable(false);
  205. builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {
  206. @Override
  207. public void onClick(DialogInterface dialog, int which) {
  208. if (android.os.Build.VERSION.SDK_INT >
  209. android.os.Build.VERSION_CODES.ECLAIR_MR1) {
  210. // using string value since in API7 this
  211. // constatn is not defined
  212. // in API7 < this constatant is defined in
  213. // Settings.ADD_ACCOUNT_SETTINGS
  214. // and Settings.EXTRA_AUTHORITIES
  215. Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
  216. intent.putExtra("authorities", new String[]{MainApp.getAuthTokenType()});
  217. startActivityForResult(intent, REQUEST_CODE__SETUP_ACCOUNT);
  218. } else {
  219. // since in API7 there is no direct call for
  220. // account setup, so we need to
  221. // show our own AccountSetupAcricity, get
  222. // desired results and setup
  223. // everything for ourself
  224. Intent intent = new Intent(getBaseContext(), AccountAuthenticator.class);
  225. startActivityForResult(intent, REQUEST_CODE__SETUP_ACCOUNT);
  226. }
  227. }
  228. });
  229. builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, new OnClickListener() {
  230. @Override
  231. public void onClick(DialogInterface dialog, int which) {
  232. finish();
  233. }
  234. });
  235. return builder.create();
  236. case DIALOG_MULTIPLE_ACCOUNT:
  237. CharSequence ac[] = new CharSequence[
  238. mAccountManager.getAccountsByType(MainApp.getAccountType()).length];
  239. for (int i = 0; i < ac.length; ++i) {
  240. ac[i] = DisplayUtils.convertIdn(
  241. mAccountManager.getAccountsByType(MainApp.getAccountType())[i].name, false);
  242. }
  243. builder.setTitle(R.string.common_choose_account);
  244. builder.setItems(ac, new OnClickListener() {
  245. @Override
  246. public void onClick(DialogInterface dialog, int which) {
  247. setAccount(mAccountManager.getAccountsByType(MainApp.getAccountType())[which]);
  248. onAccountSet(mAccountWasRestored);
  249. dialog.dismiss();
  250. mAccountSelected = true;
  251. mAccountSelectionShowing = false;
  252. }
  253. });
  254. builder.setCancelable(true);
  255. builder.setOnCancelListener(new OnCancelListener() {
  256. @Override
  257. public void onCancel(DialogInterface dialog) {
  258. mAccountSelectionShowing = false;
  259. dialog.cancel();
  260. finish();
  261. }
  262. });
  263. return builder.create();
  264. default:
  265. throw new IllegalArgumentException("Unknown dialog id: " + id);
  266. }
  267. }
  268. @Override
  269. public void onBackPressed() {
  270. if (mParents.size() <= 1) {
  271. super.onBackPressed();
  272. } else {
  273. mParents.pop();
  274. String full_path = generatePath(mParents);
  275. startSyncFolderOperation(getStorageManager().getFileByPath(full_path));
  276. populateDirectoryList();
  277. }
  278. }
  279. @Override
  280. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  281. // click on folder in the list
  282. Log_OC.d(TAG, "on item click");
  283. // TODO Enable when "On Device" is recovered ?
  284. Vector<OCFile> tmpfiles = getStorageManager().getFolderContent(mFile /*, false*/);
  285. tmpfiles = sortFileList(tmpfiles);
  286. if (tmpfiles.size() <= 0) return;
  287. // filter on dirtype
  288. Vector<OCFile> files = new Vector<>();
  289. for (OCFile f : tmpfiles)
  290. files.add(f);
  291. if (files.size() < position) {
  292. throw new IndexOutOfBoundsException("Incorrect item selected");
  293. }
  294. if (files.get(position).isFolder()){
  295. OCFile folderToEnter = files.get(position);
  296. startSyncFolderOperation(folderToEnter);
  297. mParents.push(folderToEnter.getFileName());
  298. populateDirectoryList();
  299. }
  300. }
  301. @Override
  302. public void onClick(View v) {
  303. // click on button
  304. switch (v.getId()) {
  305. case R.id.uploader_choose_folder:
  306. mUploadPath = ""; // first element in mParents is root dir, represented by "";
  307. // init mUploadPath with "/" results in a "//" prefix
  308. for (String p : mParents) {
  309. mUploadPath += p + OCFile.PATH_SEPARATOR;
  310. }
  311. Log_OC.d(TAG, "Uploading file to dir " + mUploadPath);
  312. uploadFiles();
  313. break;
  314. case R.id.uploader_cancel:
  315. finish();
  316. break;
  317. default:
  318. throw new IllegalArgumentException("Wrong element clicked");
  319. }
  320. }
  321. @Override
  322. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  323. super.onActivityResult(requestCode, resultCode, data);
  324. Log_OC.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
  325. if (requestCode == REQUEST_CODE__SETUP_ACCOUNT) {
  326. dismissDialog(DIALOG_NO_ACCOUNT);
  327. if (resultCode == RESULT_CANCELED) {
  328. finish();
  329. }
  330. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAuthTokenType());
  331. if (accounts.length == 0) {
  332. showDialog(DIALOG_NO_ACCOUNT);
  333. } else {
  334. // there is no need for checking for is there more then one
  335. // account at this point
  336. // since account setup can set only one account at time
  337. setAccount(accounts[0]);
  338. populateDirectoryList();
  339. }
  340. }
  341. }
  342. private void populateDirectoryList() {
  343. setContentView(R.layout.uploader_layout);
  344. ListView mListView = (ListView) findViewById(android.R.id.list);
  345. ActionBar actionBar = getSupportActionBar();
  346. String current_dir = mParents.peek();
  347. if (current_dir.equals("")) {
  348. actionBar.setTitle(getString(R.string.uploader_top_message));
  349. } else {
  350. actionBar.setTitle(current_dir);
  351. }
  352. boolean notRoot = (mParents.size() > 1);
  353. actionBar.setDisplayHomeAsUpEnabled(notRoot);
  354. actionBar.setHomeButtonEnabled(notRoot);
  355. String full_path = generatePath(mParents);
  356. Log_OC.d(TAG, "Populating view with content of : " + full_path);
  357. mFile = getStorageManager().getFileByPath(full_path);
  358. if (mFile != null) {
  359. // TODO Enable when "On Device" is recovered ?
  360. Vector<OCFile> files = getStorageManager().getFolderContent(mFile/*, false*/);
  361. files = sortFileList(files);
  362. List<HashMap<String, Object>> data = new LinkedList<>();
  363. for (OCFile f : files) {
  364. HashMap<String, Object> h = new HashMap<>();
  365. h.put("dirname", f);
  366. data.add(h);
  367. }
  368. UploaderAdapter sa = new UploaderAdapter(this,
  369. data,
  370. R.layout.uploader_list_item_layout,
  371. new String[] {"dirname"},
  372. new int[] {R.id.filename},
  373. getStorageManager(), getAccount());
  374. mListView.setAdapter(sa);
  375. Button btnChooseFolder = (Button) findViewById(R.id.uploader_choose_folder);
  376. btnChooseFolder.setOnClickListener(this);
  377. Button btnNewFolder = (Button) findViewById(R.id.uploader_cancel);
  378. btnNewFolder.setOnClickListener(this);
  379. mListView.setOnItemClickListener(this);
  380. }
  381. }
  382. @Override
  383. public void onSavedCertificate() {
  384. startSyncFolderOperation(getCurrentDir());
  385. }
  386. private void startSyncFolderOperation(OCFile folder) {
  387. long currentSyncTime = System.currentTimeMillis();
  388. mSyncInProgress = true;
  389. // perform folder synchronization
  390. RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
  391. currentSyncTime,
  392. false,
  393. false,
  394. false,
  395. getStorageManager(),
  396. getAccount(),
  397. getApplicationContext()
  398. );
  399. synchFolderOp.execute(getAccount(), this, null, null);
  400. }
  401. private Vector<OCFile> sortFileList(Vector<OCFile> files) {
  402. // Read sorting order, default to sort by name ascending
  403. FileStorageUtils.mSortOrder = PreferenceManager.getSortOrder(this);
  404. FileStorageUtils.mSortAscending = PreferenceManager.getSortAscending(this);
  405. files = FileStorageUtils.sortFolder(files);
  406. return files;
  407. }
  408. private String generatePath(Stack<String> dirs) {
  409. String full_path = "";
  410. for (String a : dirs)
  411. full_path += a + "/";
  412. return full_path;
  413. }
  414. private void prepareStreamsToUpload() {
  415. if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
  416. mStreamsToUpload = new ArrayList<>();
  417. mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
  418. } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
  419. mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
  420. }
  421. }
  422. private boolean somethingToUpload() {
  423. return (mStreamsToUpload != null && mStreamsToUpload.get(0) != null);
  424. }
  425. @SuppressLint("NewApi")
  426. public void uploadFiles() {
  427. UriUploader uploader = new UriUploader(
  428. this,
  429. mStreamsToUpload,
  430. mUploadPath,
  431. getAccount(),
  432. FileUploader.LOCAL_BEHAVIOUR_FORGET,
  433. true, // Show waiting dialog while file is being copied from private storage
  434. this // Copy temp task listener
  435. );
  436. UriUploader.UriUploaderResultCode resultCode = uploader.uploadUris();
  437. // Save the path to shared preferences; even if upload is not possible, user chose the folder
  438. PreferenceManager.setLastUploadPath(mUploadPath, this);
  439. if (resultCode == UriUploader.UriUploaderResultCode.OK) {
  440. finish();
  441. } else {
  442. int messageResTitle = R.string.uploader_error_title_file_cannot_be_uploaded;
  443. int messageResId = R.string.common_error_unknown;
  444. if (resultCode == UriUploader.UriUploaderResultCode.ERROR_NO_FILE_TO_UPLOAD) {
  445. messageResId = R.string.uploader_error_message_no_file_to_upload;
  446. messageResTitle = R.string.uploader_error_title_no_file_to_upload;
  447. } else if (resultCode == UriUploader.UriUploaderResultCode.ERROR_READ_PERMISSION_NOT_GRANTED) {
  448. messageResId = R.string.uploader_error_message_read_permission_not_granted;
  449. } else if (resultCode == UriUploader.UriUploaderResultCode.ERROR_UNKNOWN) {
  450. messageResId = R.string.common_error_unknown;
  451. }
  452. showErrorDialog(
  453. messageResId,
  454. messageResTitle
  455. );
  456. }
  457. }
  458. @Override
  459. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  460. super.onRemoteOperationFinish(operation, result);
  461. if (operation instanceof CreateFolderOperation) {
  462. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  463. }
  464. }
  465. /**
  466. * Updates the view associated to the activity after the finish of an operation
  467. * trying create a new folder
  468. *
  469. * @param operation Creation operation performed.
  470. * @param result Result of the creation.
  471. */
  472. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  473. RemoteOperationResult result) {
  474. if (result.isSuccess()) {
  475. populateDirectoryList();
  476. } else {
  477. try {
  478. Toast msg = Toast.makeText(this,
  479. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  480. Toast.LENGTH_LONG);
  481. msg.show();
  482. } catch (NotFoundException e) {
  483. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  484. }
  485. }
  486. }
  487. /**
  488. * Loads the target folder initialize shown to the user.
  489. * <p/>
  490. * The target account has to be chosen before this method is called.
  491. */
  492. private void initTargetFolder() {
  493. if (getStorageManager() == null) {
  494. throw new IllegalStateException("Do not call this method before " +
  495. "initializing mStorageManager");
  496. }
  497. String lastPath = PreferenceManager.getLastUploadPath(this);
  498. // "/" equals root-directory
  499. if (lastPath.equals("/")) {
  500. mParents.add("");
  501. } else {
  502. String[] dir_names = lastPath.split("/");
  503. mParents.clear();
  504. for (String dir : dir_names)
  505. mParents.add(dir);
  506. }
  507. //Make sure that path still exists, if it doesn't pop the stack and try the previous path
  508. while (!getStorageManager().fileExists(generatePath(mParents)) && mParents.size() > 1) {
  509. mParents.pop();
  510. }
  511. }
  512. @Override
  513. public boolean onCreateOptionsMenu(Menu menu) {
  514. MenuInflater inflater = getMenuInflater();
  515. inflater.inflate(R.menu.main_menu, menu);
  516. menu.findItem(R.id.action_sort).setVisible(false);
  517. menu.findItem(R.id.action_switch_view).setVisible(false);
  518. menu.findItem(R.id.action_sync_account).setVisible(false);
  519. return true;
  520. }
  521. @Override
  522. public boolean onOptionsItemSelected(MenuItem item) {
  523. boolean retval = true;
  524. switch (item.getItemId()) {
  525. case R.id.action_create_dir:
  526. CreateFolderDialogFragment dialog = CreateFolderDialogFragment.newInstance(mFile);
  527. dialog.show(
  528. getSupportFragmentManager(),
  529. CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT);
  530. break;
  531. case android.R.id.home:
  532. if ((mParents.size() > 1)) {
  533. onBackPressed();
  534. }
  535. break;
  536. default:
  537. retval = super.onOptionsItemSelected(item);
  538. }
  539. return retval;
  540. }
  541. private OCFile getCurrentFolder(){
  542. OCFile file = mFile;
  543. if (file != null) {
  544. if (file.isFolder()) {
  545. return file;
  546. } else if (getStorageManager() != null) {
  547. return getStorageManager().getFileByPath(file.getParentRemotePath());
  548. }
  549. }
  550. return null;
  551. }
  552. private void browseToRoot() {
  553. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  554. mFile = root;
  555. startSyncFolderOperation(root);
  556. }
  557. private class SyncBroadcastReceiver extends BroadcastReceiver {
  558. /**
  559. * {@link BroadcastReceiver} to enable syncing feedback in UI
  560. */
  561. @Override
  562. public void onReceive(Context context, Intent intent) {
  563. try {
  564. String event = intent.getAction();
  565. Log_OC.d(TAG, "Received broadcast " + event);
  566. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  567. String synchFolderRemotePath =
  568. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  569. RemoteOperationResult synchResult =
  570. (RemoteOperationResult) intent.getSerializableExtra(
  571. FileSyncAdapter.EXTRA_RESULT);
  572. boolean sameAccount = (getAccount() != null &&
  573. accountName.equals(getAccount().name) && getStorageManager() != null);
  574. if (sameAccount) {
  575. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  576. mSyncInProgress = true;
  577. } else {
  578. OCFile currentFile = (mFile == null) ? null :
  579. getStorageManager().getFileByPath(mFile.getRemotePath());
  580. OCFile currentDir = (getCurrentFolder() == null) ? null :
  581. getStorageManager().getFileByPath(getCurrentFolder().getRemotePath());
  582. if (currentDir == null) {
  583. // current folder was removed from the server
  584. Toast.makeText(context,
  585. String.format(
  586. getString(R.string.sync_current_folder_was_removed),
  587. getCurrentFolder().getFileName()),
  588. Toast.LENGTH_LONG)
  589. .show();
  590. browseToRoot();
  591. } else {
  592. if (currentFile == null && !mFile.isFolder()) {
  593. // currently selected file was removed in the server, and now we know it
  594. currentFile = currentDir;
  595. }
  596. if (synchFolderRemotePath != null &&
  597. currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  598. populateDirectoryList();
  599. }
  600. mFile = currentFile;
  601. }
  602. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  603. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
  604. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
  605. equals(event) &&
  606. /// TODO refactor and make common
  607. synchResult != null && !synchResult.isSuccess()) {
  608. if(synchResult.getCode() == ResultCode.UNAUTHORIZED ||
  609. (synchResult.isException() && synchResult.getException()
  610. instanceof AuthenticatorException)) {
  611. requestCredentialsUpdate(context);
  612. } else if(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(synchResult.getCode())) {
  613. showUntrustedCertDialog(synchResult);
  614. }
  615. }
  616. }
  617. removeStickyBroadcast(intent);
  618. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  619. }
  620. } catch (RuntimeException e) {
  621. // avoid app crashes after changing the serial id of RemoteOperationResult
  622. // in owncloud library with broadcast notifications pending to process
  623. removeStickyBroadcast(intent);
  624. }
  625. }
  626. }
  627. /**
  628. * Process the result of CopyAndUploadContentUrisTask
  629. */
  630. @Override
  631. public void onTmpFilesCopied(ResultCode result) {
  632. dismissLoadingDialog();
  633. finish();
  634. }
  635. /**
  636. * Show an error dialog, forcing the user to click a single button to exit the activity
  637. *
  638. * @param messageResId Resource id of the message to show in the dialog.
  639. * @param messageResTitle Resource id of the title to show in the dialog. 0 to show default alert message.
  640. * -1 to show no title.
  641. */
  642. private void showErrorDialog(int messageResId, int messageResTitle) {
  643. ConfirmationDialogFragment errorDialog = ConfirmationDialogFragment.newInstance(
  644. messageResId,
  645. new String[]{getString(R.string.app_name)}, // see uploader_error_message_* in strings.xml
  646. messageResTitle,
  647. R.string.common_back,
  648. -1,
  649. -1
  650. );
  651. errorDialog.setCancelable(false);
  652. errorDialog.setOnConfirmationListener(
  653. new ConfirmationDialogFragment.ConfirmationDialogFragmentListener() {
  654. @Override
  655. public void onConfirmation(String callerTag) {
  656. finish();
  657. }
  658. @Override
  659. public void onNeutral(String callerTag) {}
  660. @Override
  661. public void onCancel(String callerTag) {}
  662. }
  663. );
  664. errorDialog.show(getSupportFragmentManager(), FTAG_ERROR_FRAGMENT);
  665. }
  666. }