ReceiveExternalFilesActivity.java 50 KB

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