ReceiveExternalFilesActivity.java 48 KB

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