ReceiveExternalFilesActivity.java 50 KB

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