ReceiveExternalFilesActivity.java 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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.app.Activity;
  28. import android.app.Dialog;
  29. import android.content.BroadcastReceiver;
  30. import android.content.Context;
  31. import android.content.Intent;
  32. import android.content.IntentFilter;
  33. import android.content.res.Resources.NotFoundException;
  34. import android.graphics.PorterDuff;
  35. import android.graphics.drawable.ColorDrawable;
  36. import android.graphics.drawable.Drawable;
  37. import android.os.Bundle;
  38. import android.os.Handler;
  39. import android.os.Looper;
  40. import android.os.Parcelable;
  41. import android.support.annotation.DrawableRes;
  42. import android.support.annotation.NonNull;
  43. import android.support.annotation.Nullable;
  44. import android.support.annotation.StringRes;
  45. import android.support.v4.app.DialogFragment;
  46. import android.support.v4.app.FragmentManager;
  47. import android.support.v4.content.ContextCompat;
  48. import android.support.v4.graphics.drawable.DrawableCompat;
  49. import android.support.v4.view.MenuItemCompat;
  50. import android.support.v7.app.ActionBar;
  51. import android.support.v7.app.AlertDialog;
  52. import android.support.v7.app.AlertDialog.Builder;
  53. import android.support.v7.widget.SearchView;
  54. import android.text.format.DateFormat;
  55. import android.view.LayoutInflater;
  56. import android.view.Menu;
  57. import android.view.MenuInflater;
  58. import android.view.MenuItem;
  59. import android.view.View;
  60. import android.view.WindowManager.LayoutParams;
  61. import android.widget.AdapterView;
  62. import android.widget.AdapterView.OnItemClickListener;
  63. import android.widget.ArrayAdapter;
  64. import android.widget.Button;
  65. import android.widget.EditText;
  66. import android.widget.ImageView;
  67. import android.widget.LinearLayout;
  68. import android.widget.ListView;
  69. import android.widget.ProgressBar;
  70. import android.widget.Spinner;
  71. import android.widget.TextView;
  72. import com.owncloud.android.MainApp;
  73. import com.owncloud.android.R;
  74. import com.owncloud.android.datamodel.OCFile;
  75. import com.owncloud.android.db.PreferenceManager;
  76. import com.owncloud.android.files.services.FileUploader;
  77. import com.owncloud.android.lib.common.operations.RemoteOperation;
  78. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  79. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  80. import com.owncloud.android.lib.common.utils.Log_OC;
  81. import com.owncloud.android.operations.CreateFolderOperation;
  82. import com.owncloud.android.operations.RefreshFolderOperation;
  83. import com.owncloud.android.operations.UploadFileOperation;
  84. import com.owncloud.android.syncadapter.FileSyncAdapter;
  85. import com.owncloud.android.ui.adapter.AccountListAdapter;
  86. import com.owncloud.android.ui.adapter.AccountListItem;
  87. import com.owncloud.android.ui.adapter.UploaderAdapter;
  88. import com.owncloud.android.ui.asynctasks.CopyAndUploadContentUrisTask;
  89. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  90. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  91. import com.owncloud.android.ui.dialog.SortingOrderDialogFragment;
  92. import com.owncloud.android.ui.fragment.TaskRetainerFragment;
  93. import com.owncloud.android.ui.helpers.UriUploader;
  94. import com.owncloud.android.utils.DataHolderUtil;
  95. import com.owncloud.android.utils.DisplayUtils;
  96. import com.owncloud.android.utils.ErrorMessageAdapter;
  97. import com.owncloud.android.utils.FileSortOrder;
  98. import com.owncloud.android.utils.MimeType;
  99. import com.owncloud.android.utils.ThemeUtils;
  100. import java.io.File;
  101. import java.io.FileWriter;
  102. import java.io.IOException;
  103. import java.io.UnsupportedEncodingException;
  104. import java.lang.reflect.Method;
  105. import java.util.ArrayList;
  106. import java.util.Arrays;
  107. import java.util.Calendar;
  108. import java.util.HashMap;
  109. import java.util.LinkedList;
  110. import java.util.List;
  111. import java.util.Stack;
  112. import java.util.Vector;
  113. import static com.owncloud.android.db.PreferenceManager.getSortOrder;
  114. /**
  115. * This can be used to upload things to an ownCloud instance.
  116. */
  117. public class ReceiveExternalFilesActivity extends FileActivity
  118. implements OnItemClickListener, View.OnClickListener, CopyAndUploadContentUrisTask.OnCopyTmpFilesTaskListener,
  119. SortingOrderDialogFragment.OnSortingOrderListener {
  120. private static final String TAG = ReceiveExternalFilesActivity.class.getSimpleName();
  121. private static final String FTAG_ERROR_FRAGMENT = "ERROR_FRAGMENT";
  122. public static final String TEXT_FILE_SUFFIX = ".txt";
  123. public static final String URL_FILE_SUFFIX = ".url";
  124. public static final String WEBLOC_FILE_SUFFIX = ".webloc";
  125. public static final String DESKTOP_FILE_SUFFIX = ".desktop";
  126. public static final int SINGLE_PARENT = 1;
  127. private AccountManager mAccountManager;
  128. private Stack<String> mParents = new Stack<>();
  129. private List<Parcelable> mStreamsToUpload;
  130. private String mUploadPath;
  131. private OCFile mFile;
  132. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  133. private boolean mSyncInProgress;
  134. private final static int REQUEST_CODE__SETUP_ACCOUNT = REQUEST_CODE__LAST_SHARED + 1;
  135. private final static String KEY_PARENTS = "PARENTS";
  136. private final static String KEY_FILE = "FILE";
  137. private boolean mUploadFromTmpFile;
  138. private String mSubjectText;
  139. private String mExtraText;
  140. private final static String FILENAME_ENCODING = "UTF-8";
  141. private LinearLayout mEmptyListContainer;
  142. private TextView mEmptyListMessage;
  143. private TextView mEmptyListHeadline;
  144. private ImageView mEmptyListIcon;
  145. private ProgressBar mEmptyListProgress;
  146. @Override
  147. protected void onCreate(Bundle savedInstanceState) {
  148. prepareStreamsToUpload();
  149. if (savedInstanceState != null) {
  150. String parentPath = savedInstanceState.getString(KEY_PARENTS);
  151. if (parentPath != null) {
  152. mParents.addAll(Arrays.asList(parentPath.split("/")));
  153. }
  154. mFile = savedInstanceState.getParcelable(KEY_FILE);
  155. }
  156. mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
  157. super.onCreate(savedInstanceState);
  158. // Listen for sync messages
  159. IntentFilter syncIntentFilter = new IntentFilter(RefreshFolderOperation.
  160. EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  161. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  162. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  163. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  164. // Init Fragment without UI to retain AsyncTask across configuration changes
  165. FragmentManager fm = getSupportFragmentManager();
  166. TaskRetainerFragment taskRetainerFragment =
  167. (TaskRetainerFragment) fm.findFragmentByTag(TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT);
  168. if (taskRetainerFragment == null) {
  169. taskRetainerFragment = new TaskRetainerFragment();
  170. fm.beginTransaction()
  171. .add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit();
  172. } // else, Fragment already created and retained across configuration change
  173. }
  174. @Override
  175. protected void setAccount(Account account, boolean savedAccount) {
  176. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAccountType(this));
  177. if (accounts.length == 0) {
  178. Log_OC.i(TAG, "No ownCloud account is available");
  179. DialogNoAccount dialog = new DialogNoAccount();
  180. dialog.show(getSupportFragmentManager(), null);
  181. } else if (!savedAccount) {
  182. setAccount(accounts[0]);
  183. }
  184. if (!somethingToUpload()) {
  185. showErrorDialog(
  186. R.string.uploader_error_message_no_file_to_upload,
  187. R.string.uploader_error_title_no_file_to_upload
  188. );
  189. }
  190. super.setAccount(account, savedAccount);
  191. }
  192. private void showAccountChooserDialog() {
  193. DialogMultipleAccount dialog = new DialogMultipleAccount();
  194. dialog.show(getSupportFragmentManager(), null);
  195. }
  196. private Activity getActivity() {
  197. return this;
  198. }
  199. @Override
  200. protected void onAccountSet(boolean stateWasRecovered) {
  201. super.onAccountSet(mAccountWasRestored);
  202. initTargetFolder();
  203. populateDirectoryList();
  204. }
  205. @Override
  206. protected void onSaveInstanceState(Bundle outState) {
  207. Log_OC.d(TAG, "onSaveInstanceState() start");
  208. super.onSaveInstanceState(outState);
  209. outState.putString(KEY_PARENTS, generatePath(mParents));
  210. outState.putParcelable(KEY_FILE, mFile);
  211. outState.putParcelable(FileActivity.EXTRA_ACCOUNT, getAccount());
  212. Log_OC.d(TAG, "onSaveInstanceState() end");
  213. }
  214. @Override
  215. protected void onDestroy() {
  216. if (mSyncBroadcastReceiver != null) {
  217. unregisterReceiver(mSyncBroadcastReceiver);
  218. }
  219. super.onDestroy();
  220. }
  221. @Override
  222. public void onSortingOrderChosen(FileSortOrder newSortOrder) {
  223. PreferenceManager.setSortOrder(getBaseContext(), mFile, newSortOrder);
  224. populateDirectoryList();
  225. }
  226. public static class DialogNoAccount extends DialogFragment {
  227. @NonNull
  228. @Override
  229. public Dialog onCreateDialog(Bundle savedInstanceState) {
  230. AlertDialog.Builder builder = new Builder(getActivity());
  231. builder.setIcon(R.drawable.ic_warning);
  232. builder.setTitle(R.string.uploader_wrn_no_account_title);
  233. builder.setMessage(String.format(getString(R.string.uploader_wrn_no_account_text),
  234. getString(R.string.app_name)));
  235. builder.setCancelable(false);
  236. builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, (dialog, which) -> {
  237. // using string value since in API7 this
  238. // constant is not defined
  239. // in API7 < this constant is defined in
  240. // Settings.ADD_ACCOUNT_SETTINGS
  241. // and Settings.EXTRA_AUTHORITIES
  242. Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
  243. intent.putExtra("authorities", new String[]{MainApp.getAuthTokenType()});
  244. startActivityForResult(intent, REQUEST_CODE__SETUP_ACCOUNT);
  245. });
  246. builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, (dialog, which) -> getActivity().finish());
  247. return builder.create();
  248. }
  249. }
  250. public static class DialogMultipleAccount extends DialogFragment {
  251. private AccountListAdapter mAccountListAdapter;
  252. private Drawable mTintedCheck;
  253. @NonNull
  254. @Override
  255. public Dialog onCreateDialog(Bundle savedInstanceState) {
  256. final ReceiveExternalFilesActivity parent = (ReceiveExternalFilesActivity) getActivity();
  257. AlertDialog.Builder builder = new Builder(parent);
  258. mTintedCheck = DrawableCompat.wrap(ContextCompat.getDrawable(parent, R.drawable.account_circle_white));
  259. int tint = ThemeUtils.primaryColor(getContext());
  260. DrawableCompat.setTint(mTintedCheck, tint);
  261. mAccountListAdapter = new AccountListAdapter(parent, getAccountListItems(parent), mTintedCheck);
  262. builder.setTitle(R.string.common_choose_account);
  263. builder.setAdapter(mAccountListAdapter, (dialog, which) -> {
  264. final ReceiveExternalFilesActivity parent1 = (ReceiveExternalFilesActivity) getActivity();
  265. parent1.setAccount(parent1.mAccountManager.getAccountsByType(
  266. MainApp.getAccountType(getActivity()))[which], false);
  267. parent1.onAccountSet(parent1.mAccountWasRestored);
  268. dialog.dismiss();
  269. });
  270. builder.setCancelable(true);
  271. return builder.create();
  272. }
  273. /**
  274. * creates the account list items list including the add-account action in case multiaccount_support is enabled.
  275. *
  276. * @return list of account list items
  277. */
  278. private List<AccountListItem> getAccountListItems(ReceiveExternalFilesActivity activity) {
  279. Account[] accountList = activity.mAccountManager.getAccountsByType(MainApp.getAccountType(getActivity()));
  280. List<AccountListItem> adapterAccountList = new ArrayList<>(accountList.length);
  281. for (Account account : accountList) {
  282. adapterAccountList.add(new AccountListItem(account));
  283. }
  284. return adapterAccountList;
  285. }
  286. }
  287. public static class DialogInputUploadFilename extends DialogFragment {
  288. private static final String KEY_SUBJECT_TEXT = "SUBJECT_TEXT";
  289. private static final String KEY_EXTRA_TEXT = "EXTRA_TEXT";
  290. private static final int CATEGORY_URL = 1;
  291. private static final int CATEGORY_MAPS_URL = 2;
  292. private static final int EXTRA_TEXT_LENGTH = 3;
  293. private static final int SINGLE_SPINNER_ENTRY = 1;
  294. private List<String> mFilenameBase;
  295. private List<String> mFilenameSuffix;
  296. private List<String> mText;
  297. private int mFileCategory;
  298. private Spinner mSpinner;
  299. public static DialogInputUploadFilename newInstance(String subjectText, String extraText) {
  300. DialogInputUploadFilename dialog = new DialogInputUploadFilename();
  301. Bundle args = new Bundle();
  302. args.putString(KEY_SUBJECT_TEXT, subjectText);
  303. args.putString(KEY_EXTRA_TEXT, extraText);
  304. dialog.setArguments(args);
  305. return dialog;
  306. }
  307. @NonNull
  308. @Override
  309. public Dialog onCreateDialog(Bundle savedInstanceState) {
  310. mFilenameBase = new ArrayList<>();
  311. mFilenameSuffix = new ArrayList<>();
  312. mText = new ArrayList<>();
  313. String subjectText = "";
  314. String extraText = "";
  315. if (getArguments() != null) {
  316. if (getArguments().getString(KEY_SUBJECT_TEXT) != null) {
  317. subjectText = getArguments().getString(KEY_SUBJECT_TEXT);
  318. }
  319. if (getArguments().getString(KEY_EXTRA_TEXT) != null) {
  320. extraText = getArguments().getString(KEY_EXTRA_TEXT);
  321. }
  322. }
  323. LayoutInflater layout = LayoutInflater.from(requireContext());
  324. View view = layout.inflate(R.layout.upload_file_dialog, null);
  325. ArrayAdapter<String> adapter
  326. = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item);
  327. adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  328. int selectPos = 0;
  329. String filename = renameSafeFilename(subjectText);
  330. if (filename == null) {
  331. filename = "";
  332. }
  333. adapter.add(getString(R.string.upload_file_dialog_filetype_snippet_text));
  334. mText.add(extraText);
  335. mFilenameBase.add(filename);
  336. mFilenameSuffix.add(TEXT_FILE_SUFFIX);
  337. if (isIntentStartWithUrl(extraText)) {
  338. String str = getString(R.string.upload_file_dialog_filetype_internet_shortcut);
  339. mText.add(internetShortcutUrlText(extraText));
  340. mFilenameBase.add(filename);
  341. mFilenameSuffix.add(URL_FILE_SUFFIX);
  342. adapter.add(String.format(str,URL_FILE_SUFFIX));
  343. mText.add(internetShortcutWeblocText(extraText));
  344. mFilenameBase.add(filename);
  345. mFilenameSuffix.add(WEBLOC_FILE_SUFFIX);
  346. adapter.add(String.format(str,WEBLOC_FILE_SUFFIX));
  347. mText.add(internetShortcutDesktopText(extraText, filename));
  348. mFilenameBase.add(filename);
  349. mFilenameSuffix.add(DESKTOP_FILE_SUFFIX);
  350. adapter.add(String.format(str,DESKTOP_FILE_SUFFIX));
  351. selectPos = PreferenceManager.getUploadUrlFileExtensionUrlSelectedPos(getActivity());
  352. mFileCategory = CATEGORY_URL;
  353. } else if (isIntentFromGoogleMap(subjectText, extraText)) {
  354. String str = getString(R.string.upload_file_dialog_filetype_googlemap_shortcut);
  355. String texts[] = extraText.split("\n");
  356. mText.add(internetShortcutUrlText(texts[2]));
  357. mFilenameBase.add(texts[0]);
  358. mFilenameSuffix.add(URL_FILE_SUFFIX);
  359. adapter.add(String.format(str,URL_FILE_SUFFIX));
  360. mText.add(internetShortcutWeblocText(texts[2]));
  361. mFilenameBase.add(texts[0]);
  362. mFilenameSuffix.add(WEBLOC_FILE_SUFFIX);
  363. adapter.add(String.format(str,WEBLOC_FILE_SUFFIX));
  364. mText.add(internetShortcutDesktopText(texts[2], texts[0]));
  365. mFilenameBase.add(texts[0]);
  366. mFilenameSuffix.add(DESKTOP_FILE_SUFFIX);
  367. adapter.add(String.format(str,DESKTOP_FILE_SUFFIX));
  368. selectPos = PreferenceManager.getUploadMapFileExtensionUrlSelectedPos(getActivity());
  369. mFileCategory = CATEGORY_MAPS_URL;
  370. }
  371. final EditText userInput = view.findViewById(R.id.user_input);
  372. setFilename(userInput, selectPos);
  373. userInput.requestFocus();
  374. final Spinner spinner = view.findViewById(R.id.file_type);
  375. setupSpinner(adapter, selectPos, userInput, spinner);
  376. if (adapter.getCount() == SINGLE_SPINNER_ENTRY) {
  377. view.findViewById(R.id.label_file_type).setVisibility(View.GONE);
  378. spinner.setVisibility(View.GONE);
  379. }
  380. mSpinner = spinner;
  381. Dialog filenameDialog = createFilenameDialog(view, userInput, spinner);
  382. if (filenameDialog.getWindow() != null) {
  383. filenameDialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
  384. }
  385. return filenameDialog;
  386. }
  387. private void setupSpinner(ArrayAdapter<String> adapter, int selectPos, final EditText userInput, Spinner spinner) {
  388. spinner.setAdapter(adapter);
  389. spinner.setSelection(selectPos, false);
  390. spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  391. @Override
  392. public void onItemSelected(AdapterView parent, View view, int position, long id) {
  393. Spinner spinner = (Spinner) parent;
  394. int selectPos = spinner.getSelectedItemPosition();
  395. setFilename(userInput, selectPos);
  396. saveSelection(selectPos);
  397. }
  398. @Override
  399. public void onNothingSelected(AdapterView<?> parent) {
  400. // nothing to do
  401. }
  402. });
  403. }
  404. @NonNull
  405. private Dialog createFilenameDialog(View view, final EditText userInput, final Spinner spinner) {
  406. Builder builder = new Builder(requireActivity());
  407. builder.setView(view);
  408. builder.setTitle(R.string.upload_file_dialog_title);
  409. builder.setPositiveButton(R.string.common_ok, (dialog, id) -> {
  410. int selectPos = spinner.getSelectedItemPosition();
  411. // verify if file name has suffix
  412. String filename = userInput.getText().toString();
  413. String suffix = mFilenameSuffix.get(selectPos);
  414. if (!filename.endsWith(suffix)) {
  415. filename += suffix;
  416. }
  417. File file = createTempFile(mText.get(selectPos));
  418. if (file == null) {
  419. getActivity().finish();
  420. } else {
  421. String tmpName = file.getAbsolutePath();
  422. ((ReceiveExternalFilesActivity) getActivity()).uploadFile(tmpName, filename);
  423. }
  424. });
  425. builder.setNegativeButton(R.string.common_cancel, (dialog, id) -> dialog.cancel());
  426. return builder.create();
  427. }
  428. public void onPause() {
  429. hideSpinnerDropDown(mSpinner);
  430. super.onPause();
  431. }
  432. private void saveSelection(int selectPos) {
  433. switch (mFileCategory) {
  434. case CATEGORY_URL:
  435. PreferenceManager.setUploadUrlFileExtensionUrlSelectedPos(getActivity(), selectPos);
  436. break;
  437. case CATEGORY_MAPS_URL:
  438. PreferenceManager.setUploadMapFileExtensionUrlSelectedPos(getActivity(), selectPos);
  439. break;
  440. default:
  441. Log_OC.d(TAG, "Simple text snippet only: no selection to be persisted");
  442. break;
  443. }
  444. }
  445. private void hideSpinnerDropDown(Spinner spinner) {
  446. try {
  447. Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
  448. method.setAccessible(true);
  449. method.invoke(spinner);
  450. } catch (Exception e) {
  451. Log_OC.e(TAG, "onDetachedFromWindow", e);
  452. }
  453. }
  454. private void setFilename(EditText inputText, int selectPos)
  455. {
  456. String filename = mFilenameBase.get(selectPos) + mFilenameSuffix.get(selectPos);
  457. inputText.setText(filename);
  458. int selectionStart = 0;
  459. int extensionStart = filename.lastIndexOf(".");
  460. int selectionEnd = extensionStart >= 0 ? extensionStart : filename.length();
  461. if (selectionEnd >= 0) {
  462. inputText.setSelection(
  463. Math.min(selectionStart, selectionEnd),
  464. Math.max(selectionStart, selectionEnd));
  465. }
  466. }
  467. private boolean isIntentFromGoogleMap(String subjectText, String extraText) {
  468. String texts[] = extraText.split("\n");
  469. if (texts.length != EXTRA_TEXT_LENGTH) {
  470. return false;
  471. }
  472. if (texts[0].length() == 0 || !subjectText.equals(texts[0])) {
  473. return false;
  474. }
  475. return texts[2].startsWith("https://goo.gl/maps/");
  476. }
  477. private boolean isIntentStartWithUrl(String extraText) {
  478. return extraText.startsWith("http://") || extraText.startsWith("https://");
  479. }
  480. @Nullable
  481. private String renameSafeFilename(String filename) {
  482. String safeFilename = filename;
  483. safeFilename = safeFilename.replaceAll("[?]", "_");
  484. safeFilename = safeFilename.replaceAll("\"", "_");
  485. safeFilename = safeFilename.replaceAll("/", "_");
  486. safeFilename = safeFilename.replaceAll("<", "_");
  487. safeFilename = safeFilename.replaceAll(">", "_");
  488. safeFilename = safeFilename.replaceAll("[*]", "_");
  489. safeFilename = safeFilename.replaceAll("[|]", "_");
  490. safeFilename = safeFilename.replaceAll(";", "_");
  491. safeFilename = safeFilename.replaceAll("=", "_");
  492. safeFilename = safeFilename.replaceAll(",", "_");
  493. try {
  494. int maxLength = 128;
  495. if (safeFilename.getBytes(FILENAME_ENCODING).length > maxLength) {
  496. safeFilename = new String(safeFilename.getBytes(FILENAME_ENCODING), 0, maxLength, FILENAME_ENCODING);
  497. }
  498. } catch (UnsupportedEncodingException e) {
  499. Log_OC.e(TAG, "rename failed ", e);
  500. return null;
  501. }
  502. return safeFilename;
  503. }
  504. private String internetShortcutUrlText(String url) {
  505. return "[InternetShortcut]\r\n" +
  506. "URL=" + url + "\r\n";
  507. }
  508. private String internetShortcutWeblocText(String url) {
  509. return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
  510. "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" +
  511. "<plist version=\"1.0\">\n" +
  512. "<dict>\n" +
  513. "<key>URL</key>\n" +
  514. "<string>" + url + "</string>\n" +
  515. "</dict>\n" +
  516. "</plist>\n";
  517. }
  518. private String internetShortcutDesktopText(String url, String filename) {
  519. return "[Desktop Entry]\n" +
  520. "Encoding=UTF-8\n" +
  521. "Name=" + filename + "\n" +
  522. "Type=Link\n" +
  523. "URL=" + url + "\n" +
  524. "Icon=text-html";
  525. }
  526. @Nullable
  527. private File createTempFile(String text) {
  528. File file = new File(getActivity().getCacheDir(), "tmp.tmp");
  529. FileWriter fw = null;
  530. try {
  531. fw = new FileWriter(file);
  532. fw.write(text);
  533. } catch (IOException e) {
  534. Log_OC.d(TAG, "Error ", e);
  535. return null;
  536. } finally {
  537. if (fw != null) {
  538. try {
  539. fw.close();
  540. } catch (IOException e) {
  541. Log_OC.d(TAG, "Error closing file writer ", e);
  542. }
  543. }
  544. }
  545. return file;
  546. }
  547. }
  548. @Override
  549. public void onBackPressed() {
  550. if (mParents.size() <= SINGLE_PARENT) {
  551. super.onBackPressed();
  552. } else {
  553. mParents.pop();
  554. String full_path = generatePath(mParents);
  555. startSyncFolderOperation(getStorageManager().getFileByPath(full_path));
  556. populateDirectoryList();
  557. }
  558. }
  559. @Override
  560. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  561. // click on folder in the list
  562. Log_OC.d(TAG, "on item click");
  563. List<OCFile> tmpFiles = getStorageManager().getFolderContent(mFile, false);
  564. tmpFiles = sortFileList(tmpFiles);
  565. if (tmpFiles.isEmpty()) {
  566. return;
  567. }
  568. // filter on dirtype
  569. Vector<OCFile> files = new Vector<>();
  570. files.addAll(tmpFiles);
  571. if (files.size() < position) {
  572. throw new IndexOutOfBoundsException("Incorrect item selected");
  573. }
  574. if (files.get(position).isFolder()){
  575. OCFile folderToEnter = files.get(position);
  576. startSyncFolderOperation(folderToEnter);
  577. mParents.push(folderToEnter.getFileName());
  578. populateDirectoryList();
  579. }
  580. }
  581. @Override
  582. public void onClick(View v) {
  583. // click on button
  584. switch (v.getId()) {
  585. case R.id.uploader_choose_folder:
  586. mUploadPath = ""; // first element in mParents is root dir, represented by "";
  587. // init mUploadPath with "/" results in a "//" prefix
  588. for (String p : mParents) {
  589. mUploadPath += p + OCFile.PATH_SEPARATOR;
  590. }
  591. if (mUploadFromTmpFile) {
  592. DialogInputUploadFilename dialog = DialogInputUploadFilename.newInstance(mSubjectText, mExtraText);
  593. dialog.show(getSupportFragmentManager(), null);
  594. } else {
  595. Log_OC.d(TAG, "Uploading file to dir " + mUploadPath);
  596. uploadFiles();
  597. }
  598. break;
  599. case R.id.uploader_cancel:
  600. finish();
  601. break;
  602. default:
  603. throw new IllegalArgumentException("Wrong element clicked");
  604. }
  605. }
  606. @Override
  607. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  608. super.onActivityResult(requestCode, resultCode, data);
  609. Log_OC.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
  610. if (requestCode == REQUEST_CODE__SETUP_ACCOUNT) {
  611. if (resultCode == RESULT_CANCELED) {
  612. finish();
  613. }
  614. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAuthTokenType());
  615. if (accounts.length == 0) {
  616. DialogNoAccount dialog = new DialogNoAccount();
  617. dialog.show(getSupportFragmentManager(), null);
  618. } else {
  619. // there is no need for checking for is there more then one
  620. // account at this point
  621. // since account setup can set only one account at time
  622. setAccount(accounts[0]);
  623. populateDirectoryList();
  624. }
  625. }
  626. }
  627. private void setupActionBarSubtitle() {
  628. if (isHaveMultipleAccount()) {
  629. ActionBar actionBar = getSupportActionBar();
  630. if (actionBar != null) {
  631. actionBar.setSubtitle(getAccount().name);
  632. }
  633. }
  634. }
  635. private void populateDirectoryList() {
  636. setContentView(R.layout.uploader_layout);
  637. setupEmptyList();
  638. setupToolbar();
  639. ActionBar actionBar = getSupportActionBar();
  640. setupActionBarSubtitle();
  641. ListView mListView = findViewById(android.R.id.list);
  642. String current_dir = mParents.peek();
  643. boolean notRoot = mParents.size() > 1;
  644. if (actionBar != null) {
  645. if ("".equals(current_dir)) {
  646. ThemeUtils.setColoredTitle(actionBar, R.string.uploader_top_message, this);
  647. } else {
  648. ThemeUtils.setColoredTitle(actionBar, current_dir, this);
  649. }
  650. actionBar.setDisplayHomeAsUpEnabled(notRoot);
  651. actionBar.setHomeButtonEnabled(notRoot);
  652. }
  653. String full_path = generatePath(mParents);
  654. Log_OC.d(TAG, "Populating view with content of : " + full_path);
  655. mFile = getStorageManager().getFileByPath(full_path);
  656. if (mFile != null) {
  657. List<OCFile> files = getStorageManager().getFolderContent(mFile, false);
  658. if (files.isEmpty()) {
  659. setMessageForEmptyList(R.string.file_list_empty_headline, R.string.empty,
  660. R.drawable.ic_list_empty_upload);
  661. } else {
  662. mEmptyListContainer.setVisibility(View.GONE);
  663. files = sortFileList(files);
  664. List<HashMap<String, Object>> data = new LinkedList<>();
  665. for (OCFile f : files) {
  666. HashMap<String, Object> h = new HashMap<>();
  667. h.put("dirname", f);
  668. data.add(h);
  669. }
  670. UploaderAdapter sa = new UploaderAdapter(this,
  671. data,
  672. R.layout.uploader_list_item_layout,
  673. new String[]{"dirname"},
  674. new int[]{R.id.filename},
  675. getStorageManager(), getAccount());
  676. mListView.setAdapter(sa);
  677. }
  678. Button btnChooseFolder = findViewById(R.id.uploader_choose_folder);
  679. btnChooseFolder.setOnClickListener(this);
  680. btnChooseFolder.getBackground().setColorFilter(ThemeUtils.primaryColor(getAccount(), true, this),
  681. PorterDuff.Mode.SRC_ATOP);
  682. btnChooseFolder.setTextColor(ThemeUtils.fontColor(this));
  683. if (getSupportActionBar() != null) {
  684. getSupportActionBar().setBackgroundDrawable(new ColorDrawable(
  685. ThemeUtils.primaryColor(getAccount(), false, this)));
  686. }
  687. ThemeUtils.colorStatusBar(this, ThemeUtils.primaryDarkColor(getAccount(), this));
  688. ThemeUtils.colorToolbarProgressBar(this, ThemeUtils.primaryColor(getAccount(), false, this));
  689. Drawable backArrow = getResources().getDrawable(R.drawable.ic_arrow_back);
  690. if (actionBar != null) {
  691. actionBar.setHomeAsUpIndicator(ThemeUtils.tintDrawable(backArrow, ThemeUtils.fontColor(this)));
  692. }
  693. Button btnNewFolder = findViewById(R.id.uploader_cancel);
  694. btnNewFolder.setOnClickListener(this);
  695. mListView.setOnItemClickListener(this);
  696. }
  697. }
  698. protected void setupEmptyList() {
  699. mEmptyListContainer = findViewById(R.id.empty_list_view);
  700. mEmptyListMessage = findViewById(R.id.empty_list_view_text);
  701. mEmptyListHeadline = findViewById(R.id.empty_list_view_headline);
  702. mEmptyListIcon = findViewById(R.id.empty_list_icon);
  703. mEmptyListProgress = findViewById(R.id.empty_list_progress);
  704. mEmptyListProgress.getIndeterminateDrawable().setColorFilter(ThemeUtils.primaryColor(this),
  705. PorterDuff.Mode.SRC_IN);
  706. }
  707. public void setMessageForEmptyList(@StringRes final int headline, @StringRes final int message,
  708. @DrawableRes final int icon) {
  709. new Handler(Looper.getMainLooper()).post(() -> {
  710. if (mEmptyListContainer != null && mEmptyListMessage != null) {
  711. mEmptyListHeadline.setText(headline);
  712. mEmptyListMessage.setText(message);
  713. mEmptyListIcon.setImageDrawable(ThemeUtils.tintDrawable(icon, ThemeUtils.primaryColor(this, true)));
  714. mEmptyListIcon.setVisibility(View.VISIBLE);
  715. mEmptyListProgress.setVisibility(View.GONE);
  716. mEmptyListMessage.setVisibility(View.VISIBLE);
  717. }
  718. });
  719. }
  720. @Override
  721. public void onSavedCertificate() {
  722. startSyncFolderOperation(getCurrentDir());
  723. }
  724. private void startSyncFolderOperation(OCFile folder) {
  725. long currentSyncTime = System.currentTimeMillis();
  726. mSyncInProgress = true;
  727. // perform folder synchronization
  728. RemoteOperation syncFolderOp = new RefreshFolderOperation(folder,
  729. currentSyncTime,
  730. false,
  731. false,
  732. getStorageManager(),
  733. getAccount(),
  734. getApplicationContext()
  735. );
  736. syncFolderOp.execute(getAccount(), this, null, null);
  737. }
  738. private List<OCFile> sortFileList(List<OCFile> files) {
  739. FileSortOrder sortOrder = getSortOrder(this, mFile);
  740. return sortOrder.sortCloudFiles(files);
  741. }
  742. private String generatePath(Stack<String> dirs) {
  743. String full_path = "";
  744. for (String a : dirs) {
  745. full_path += a + "/";
  746. }
  747. return full_path;
  748. }
  749. private void prepareStreamsToUpload() {
  750. Intent intent = getIntent();
  751. if (Intent.ACTION_SEND.equals(intent.getAction())) {
  752. mStreamsToUpload = new ArrayList<>();
  753. mStreamsToUpload.add(intent.getParcelableExtra(Intent.EXTRA_STREAM));
  754. } else if (Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction())) {
  755. mStreamsToUpload = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
  756. }
  757. if (mStreamsToUpload == null || mStreamsToUpload.isEmpty() || mStreamsToUpload.get(0) == null) {
  758. mStreamsToUpload = null;
  759. saveTextsFromIntent(intent);
  760. }
  761. }
  762. private void saveTextsFromIntent(Intent intent) {
  763. if (!MimeType.TEXT_PLAIN.equals(intent.getType())) {
  764. return;
  765. }
  766. mUploadFromTmpFile = true;
  767. mSubjectText = intent.getStringExtra(Intent.EXTRA_SUBJECT);
  768. if (mSubjectText == null) {
  769. mSubjectText = intent.getStringExtra(Intent.EXTRA_TITLE);
  770. if (mSubjectText == null) {
  771. mSubjectText = DateFormat.format("yyyyMMdd_kkmmss", Calendar.getInstance()).toString();
  772. }
  773. }
  774. mExtraText = intent.getStringExtra(Intent.EXTRA_TEXT);
  775. }
  776. private boolean somethingToUpload() {
  777. return (mStreamsToUpload != null && mStreamsToUpload.size() > 0 && mStreamsToUpload.get(0) != null ||
  778. mUploadFromTmpFile);
  779. }
  780. public void uploadFile(String tmpName, String filename) {
  781. FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
  782. requester.uploadNewFile(
  783. getBaseContext(),
  784. getAccount(),
  785. tmpName,
  786. mFile.getRemotePath() + filename,
  787. FileUploader.LOCAL_BEHAVIOUR_COPY,
  788. null,
  789. true,
  790. UploadFileOperation.CREATED_BY_USER,
  791. false,
  792. false
  793. );
  794. finish();
  795. }
  796. public void uploadFiles() {
  797. UriUploader uploader = new UriUploader(
  798. this,
  799. mStreamsToUpload,
  800. mUploadPath,
  801. getAccount(),
  802. FileUploader.LOCAL_BEHAVIOUR_FORGET,
  803. true, // Show waiting dialog while file is being copied from private storage
  804. this // Copy temp task listener
  805. );
  806. UriUploader.UriUploaderResultCode resultCode = uploader.uploadUris();
  807. // Save the path to shared preferences; even if upload is not possible, user chose the folder
  808. PreferenceManager.setLastUploadPath(this, mUploadPath);
  809. if (resultCode == UriUploader.UriUploaderResultCode.OK) {
  810. finish();
  811. } else {
  812. int messageResTitle = R.string.uploader_error_title_file_cannot_be_uploaded;
  813. int messageResId = R.string.common_error_unknown;
  814. if (resultCode == UriUploader.UriUploaderResultCode.ERROR_NO_FILE_TO_UPLOAD) {
  815. messageResId = R.string.uploader_error_message_no_file_to_upload;
  816. messageResTitle = R.string.uploader_error_title_no_file_to_upload;
  817. } else if (resultCode == UriUploader.UriUploaderResultCode.ERROR_READ_PERMISSION_NOT_GRANTED) {
  818. messageResId = R.string.uploader_error_message_read_permission_not_granted;
  819. } else if (resultCode == UriUploader.UriUploaderResultCode.ERROR_UNKNOWN) {
  820. messageResId = R.string.common_error_unknown;
  821. }
  822. showErrorDialog(
  823. messageResId,
  824. messageResTitle
  825. );
  826. }
  827. }
  828. @Override
  829. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  830. super.onRemoteOperationFinish(operation, result);
  831. if (operation instanceof CreateFolderOperation) {
  832. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  833. }
  834. }
  835. /**
  836. * Updates the view associated to the activity after the finish of an operation
  837. * trying create a new folder
  838. *
  839. * @param operation Creation operation performed.
  840. * @param result Result of the creation.
  841. */
  842. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  843. RemoteOperationResult result) {
  844. if (result.isSuccess()) {
  845. String remotePath = operation.getRemotePath().substring(0, operation.getRemotePath().length() - 1);
  846. String newFolder = remotePath.substring(remotePath.lastIndexOf('/') + 1);
  847. mParents.push(newFolder);
  848. populateDirectoryList();
  849. } else {
  850. try {
  851. DisplayUtils.showSnackMessage(
  852. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  853. );
  854. } catch (NotFoundException e) {
  855. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  856. }
  857. }
  858. }
  859. /**
  860. * Loads the target folder initialize shown to the user.
  861. * <p/>
  862. * The target account has to be chosen before this method is called.
  863. */
  864. private void initTargetFolder() {
  865. if (getStorageManager() == null) {
  866. throw new IllegalStateException("Do not call this method before initializing mStorageManager");
  867. }
  868. if (mParents.empty()) {
  869. String lastPath = PreferenceManager.getLastUploadPath(this);
  870. // "/" equals root-directory
  871. if ("/".equals(lastPath)) {
  872. mParents.add("");
  873. } else {
  874. String[] dir_names = lastPath.split("/");
  875. mParents.clear();
  876. mParents.addAll(Arrays.asList(dir_names));
  877. }
  878. }
  879. // make sure that path still exists, if it doesn't pop the stack and try the previous path
  880. while (!getStorageManager().fileExists(generatePath(mParents)) && mParents.size() > 1) {
  881. mParents.pop();
  882. }
  883. }
  884. private boolean isHaveMultipleAccount() {
  885. return mAccountManager.getAccountsByType(MainApp.getAccountType(this)).length > 1;
  886. }
  887. @Override
  888. public boolean onCreateOptionsMenu(Menu menu) {
  889. MenuInflater inflater = getMenuInflater();
  890. inflater.inflate(R.menu.receive_file_menu, menu);
  891. if (!isHaveMultipleAccount()) {
  892. MenuItem switchAccountMenu = menu.findItem(R.id.action_switch_account);
  893. switchAccountMenu.setVisible(false);
  894. }
  895. // tint search event
  896. final MenuItem item = menu.findItem(R.id.action_search);
  897. SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
  898. // hacky as no default way is provided
  899. int fontColor = ThemeUtils.fontColor(this);
  900. EditText editText = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
  901. editText.setHintTextColor(fontColor);
  902. editText.setTextColor(fontColor);
  903. ImageView searchClose = searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
  904. searchClose.setColorFilter(ThemeUtils.fontColor(this));
  905. ImageView searchButton = searchView.findViewById(android.support.v7.appcompat.R.id.search_button);
  906. searchButton.setColorFilter(ThemeUtils.fontColor(this));
  907. return true;
  908. }
  909. @Override
  910. public boolean onOptionsItemSelected(MenuItem item) {
  911. boolean retval = true;
  912. switch (item.getItemId()) {
  913. case R.id.action_create_dir:
  914. CreateFolderDialogFragment dialog = CreateFolderDialogFragment.newInstance(mFile);
  915. dialog.show(getSupportFragmentManager(), CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT);
  916. break;
  917. case android.R.id.home:
  918. if (mParents.size() > SINGLE_PARENT) {
  919. onBackPressed();
  920. }
  921. break;
  922. case R.id.action_switch_account:
  923. showAccountChooserDialog();
  924. break;
  925. case R.id.action_sort:
  926. SortingOrderDialogFragment mSortingOrderDialogFragment = SortingOrderDialogFragment.newInstance(
  927. getSortOrder(this, mFile));
  928. mSortingOrderDialogFragment.show(getSupportFragmentManager(),
  929. SortingOrderDialogFragment.SORTING_ORDER_FRAGMENT);
  930. break;
  931. default:
  932. retval = super.onOptionsItemSelected(item);
  933. break;
  934. }
  935. return retval;
  936. }
  937. private OCFile getCurrentFolder(){
  938. OCFile file = mFile;
  939. if (file != null) {
  940. if (file.isFolder()) {
  941. return file;
  942. } else if (getStorageManager() != null) {
  943. return getStorageManager().getFileByPath(file.getParentRemotePath());
  944. }
  945. }
  946. return null;
  947. }
  948. private void browseToRoot() {
  949. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  950. mFile = root;
  951. startSyncFolderOperation(root);
  952. }
  953. private class SyncBroadcastReceiver extends BroadcastReceiver {
  954. /**
  955. * {@link BroadcastReceiver} to enable syncing feedback in UI
  956. */
  957. @Override
  958. public void onReceive(Context context, Intent intent) {
  959. try {
  960. String event = intent.getAction();
  961. Log_OC.d(TAG, "Received broadcast " + event);
  962. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  963. String syncFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  964. RemoteOperationResult syncResult = (RemoteOperationResult)
  965. DataHolderUtil.getInstance().retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  966. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name)
  967. && getStorageManager() != null;
  968. if (sameAccount) {
  969. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  970. mSyncInProgress = true;
  971. } else {
  972. OCFile currentFile = (mFile == null) ? null :
  973. getStorageManager().getFileByPath(mFile.getRemotePath());
  974. OCFile currentDir = (getCurrentFolder() == null) ? null :
  975. getStorageManager().getFileByPath(getCurrentFolder().getRemotePath());
  976. if (currentDir == null) {
  977. // current folder was removed from the server
  978. DisplayUtils.showSnackMessage(
  979. getActivity(),
  980. R.string.sync_current_folder_was_removed,
  981. getCurrentFolder().getFileName()
  982. );
  983. browseToRoot();
  984. } else {
  985. if (currentFile == null && !mFile.isFolder()) {
  986. // currently selected file was removed in the server, and now we know it
  987. currentFile = currentDir;
  988. }
  989. if (currentDir.getRemotePath().equals(syncFolderRemotePath)) {
  990. populateDirectoryList();
  991. }
  992. mFile = currentFile;
  993. }
  994. mSyncInProgress = !FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  995. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event);
  996. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.equals(event)
  997. /// TODO refactor and make common
  998. && syncResult != null && !syncResult.isSuccess()) {
  999. if (syncResult.getCode() == ResultCode.UNAUTHORIZED ||
  1000. (syncResult.isException() && syncResult.getException()
  1001. instanceof AuthenticatorException)) {
  1002. requestCredentialsUpdate(context);
  1003. } else if (RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(syncResult.getCode())) {
  1004. showUntrustedCertDialog(syncResult);
  1005. }
  1006. }
  1007. }
  1008. removeStickyBroadcast(intent);
  1009. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  1010. }
  1011. } catch (RuntimeException e) {
  1012. // avoid app crashes after changing the serial id of RemoteOperationResult
  1013. // in owncloud library with broadcast notifications pending to process
  1014. removeStickyBroadcast(intent);
  1015. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1016. }
  1017. }
  1018. }
  1019. /**
  1020. * Process the result of CopyAndUploadContentUrisTask
  1021. */
  1022. @Override
  1023. public void onTmpFilesCopied(ResultCode result) {
  1024. dismissLoadingDialog();
  1025. finish();
  1026. }
  1027. /**
  1028. * Show an error dialog, forcing the user to click a single button to exit the activity
  1029. *
  1030. * @param messageResId Resource id of the message to show in the dialog.
  1031. * @param messageResTitle Resource id of the title to show in the dialog. 0 to show default alert message.
  1032. * -1 to show no title.
  1033. */
  1034. private void showErrorDialog(int messageResId, int messageResTitle) {
  1035. ConfirmationDialogFragment errorDialog = ConfirmationDialogFragment.newInstance(
  1036. messageResId,
  1037. new String[]{getString(R.string.app_name)}, // see uploader_error_message_* in strings.xml
  1038. messageResTitle,
  1039. R.string.common_back,
  1040. -1,
  1041. -1
  1042. );
  1043. errorDialog.setCancelable(false);
  1044. errorDialog.setOnConfirmationListener(
  1045. new ConfirmationDialogFragment.ConfirmationDialogFragmentListener() {
  1046. @Override
  1047. public void onConfirmation(String callerTag) {
  1048. finish();
  1049. }
  1050. @Override
  1051. public void onNeutral(String callerTag) {
  1052. // not used at the moment
  1053. }
  1054. @Override
  1055. public void onCancel(String callerTag) {
  1056. // not used at the moment
  1057. }
  1058. }
  1059. );
  1060. errorDialog.show(getSupportFragmentManager(), FTAG_ERROR_FRAGMENT);
  1061. }
  1062. }