ReceiveExternalFilesActivity.java 48 KB

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