RichDocumentsWebView.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Tobias Kaminsky
  5. * Copyright (C) 2018 Tobias Kaminsky
  6. * Copyright (C) 2018 Nextcloud GmbH.
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. */
  21. package com.owncloud.android.ui.activity;
  22. import android.accounts.Account;
  23. import android.annotation.SuppressLint;
  24. import android.content.ActivityNotFoundException;
  25. import android.content.Intent;
  26. import android.graphics.Bitmap;
  27. import android.net.Uri;
  28. import android.os.AsyncTask;
  29. import android.os.Build;
  30. import android.os.Bundle;
  31. import android.os.Handler;
  32. import android.text.TextUtils;
  33. import android.view.View;
  34. import android.webkit.JavascriptInterface;
  35. import android.webkit.ValueCallback;
  36. import android.webkit.WebChromeClient;
  37. import android.webkit.WebView;
  38. import android.widget.ImageView;
  39. import android.widget.ProgressBar;
  40. import android.widget.TextView;
  41. import android.widget.Toast;
  42. import com.bumptech.glide.Glide;
  43. import com.google.android.material.snackbar.Snackbar;
  44. import com.owncloud.android.R;
  45. import com.owncloud.android.authentication.AccountUtils;
  46. import com.owncloud.android.datamodel.OCFile;
  47. import com.owncloud.android.datamodel.Template;
  48. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  49. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  50. import com.owncloud.android.lib.common.utils.Log_OC;
  51. import com.owncloud.android.operations.RichDocumentsCreateAssetOperation;
  52. import com.owncloud.android.operations.RichDocumentsUrlOperation;
  53. import com.owncloud.android.ui.fragment.OCFileListFragment;
  54. import com.owncloud.android.utils.DisplayUtils;
  55. import com.owncloud.android.utils.MimeTypeUtil;
  56. import com.owncloud.android.utils.glide.CustomGlideStreamLoader;
  57. import org.parceler.Parcels;
  58. import java.lang.ref.WeakReference;
  59. import androidx.annotation.RequiresApi;
  60. import butterknife.BindView;
  61. import butterknife.ButterKnife;
  62. import butterknife.Unbinder;
  63. /**
  64. * Opens document for editing via Richdocuments app in a web view
  65. */
  66. @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  67. public class RichDocumentsWebView extends ExternalSiteWebView {
  68. private static final String TAG = RichDocumentsWebView.class.getSimpleName();
  69. private static final int REQUEST_REMOTE_FILE = 100;
  70. public static final int REQUEST_LOCAL_FILE = 101;
  71. public static final int MINIMUM_API = Build.VERSION_CODES.LOLLIPOP;
  72. private Unbinder unbinder;
  73. private OCFile file;
  74. public ValueCallback<Uri[]> uploadMessage;
  75. @BindView(R.id.progressBar2)
  76. ProgressBar progressBar;
  77. @BindView(R.id.thumbnail)
  78. ImageView thumbnail;
  79. @BindView(R.id.filename)
  80. TextView fileName;
  81. @SuppressLint("AddJavascriptInterface") // suppress warning as webview is only used >= Lollipop
  82. @Override
  83. protected void onCreate(Bundle savedInstanceState) {
  84. showToolbar = false;
  85. webViewLayout = R.layout.richdocuments_webview;
  86. super.onCreate(savedInstanceState);
  87. unbinder = ButterKnife.bind(this);
  88. file = getIntent().getParcelableExtra(EXTRA_FILE);
  89. // TODO make file nullable
  90. if (file == null) {
  91. fileName.setText(R.string.create_file_from_template);
  92. Template template = Parcels.unwrap(getIntent().getParcelableExtra(EXTRA_TEMPLATE));
  93. int placeholder;
  94. switch (template.getType()) {
  95. case "document":
  96. placeholder = R.drawable.file_doc;
  97. break;
  98. case "spreadsheet":
  99. placeholder = R.drawable.file_xls;
  100. break;
  101. case "presentation":
  102. placeholder = R.drawable.file_ppt;
  103. break;
  104. default:
  105. placeholder = R.drawable.file;
  106. break;
  107. }
  108. Glide.with(this).using(new CustomGlideStreamLoader()).load(template.getThumbnailLink())
  109. .placeholder(placeholder)
  110. .error(placeholder)
  111. .into(thumbnail);
  112. } else {
  113. setThumbnail(file, thumbnail);
  114. fileName.setText(file.getFileName());
  115. }
  116. webview.addJavascriptInterface(new RichDocumentsMobileInterface(), "RichDocumentsMobileInterface");
  117. webview.setWebChromeClient(new WebChromeClient() {
  118. RichDocumentsWebView activity = RichDocumentsWebView.this;
  119. @Override
  120. public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
  121. FileChooserParams fileChooserParams) {
  122. if (uploadMessage != null) {
  123. uploadMessage.onReceiveValue(null);
  124. uploadMessage = null;
  125. }
  126. activity.uploadMessage = filePathCallback;
  127. Intent intent = fileChooserParams.createIntent();
  128. intent.setType("image/*");
  129. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  130. try {
  131. activity.startActivityForResult(intent, REQUEST_LOCAL_FILE);
  132. } catch (ActivityNotFoundException e) {
  133. uploadMessage = null;
  134. Toast.makeText(getBaseContext(), "Cannot open file chooser", Toast.LENGTH_LONG).show();
  135. return false;
  136. }
  137. return true;
  138. }
  139. });
  140. // load url in background
  141. url = getIntent().getStringExtra(EXTRA_URL);
  142. if (TextUtils.isEmpty(url)) {
  143. new LoadUrl(this, getAccount()).execute(file.getLocalId());
  144. } else {
  145. webview.loadUrl(url);
  146. }
  147. }
  148. private void setThumbnail(OCFile file, ImageView thumbnailView) {
  149. // Todo minimize: only icon by mimetype
  150. if (file.isFolder()) {
  151. thumbnailView.setImageDrawable(MimeTypeUtil.getFolderTypeIcon(file.isSharedWithMe() ||
  152. file.isSharedWithSharee(), file.isSharedViaLink(), file.isEncrypted(), file.getMountType(),
  153. this));
  154. } else {
  155. if ((MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file)) && file.getRemoteId() != null) {
  156. // Thumbnail in cache?
  157. Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
  158. ThumbnailsCacheManager.PREFIX_THUMBNAIL + file.getRemoteId());
  159. if (thumbnail != null && !file.isUpdateThumbnailNeeded()) {
  160. if (MimeTypeUtil.isVideo(file)) {
  161. Bitmap withOverlay = ThumbnailsCacheManager.addVideoOverlay(thumbnail);
  162. thumbnailView.setImageBitmap(withOverlay);
  163. } else {
  164. thumbnailView.setImageBitmap(thumbnail);
  165. }
  166. } else {
  167. // generate new thumbnail
  168. if (ThumbnailsCacheManager.cancelPotentialThumbnailWork(file, thumbnailView)) {
  169. try {
  170. final ThumbnailsCacheManager.ThumbnailGenerationTask task =
  171. new ThumbnailsCacheManager.ThumbnailGenerationTask(thumbnailView,
  172. getStorageManager(), getAccount());
  173. if (thumbnail == null) {
  174. if (MimeTypeUtil.isVideo(file)) {
  175. thumbnail = ThumbnailsCacheManager.mDefaultVideo;
  176. } else {
  177. thumbnail = ThumbnailsCacheManager.mDefaultImg;
  178. }
  179. }
  180. final ThumbnailsCacheManager.AsyncThumbnailDrawable asyncDrawable =
  181. new ThumbnailsCacheManager.AsyncThumbnailDrawable(getResources(), thumbnail, task);
  182. thumbnailView.setImageDrawable(asyncDrawable);
  183. task.execute(new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file,
  184. file.getRemoteId()));
  185. } catch (IllegalArgumentException e) {
  186. Log_OC.d(TAG, "ThumbnailGenerationTask : " + e.getMessage());
  187. }
  188. }
  189. }
  190. if ("image/png".equalsIgnoreCase(file.getMimeType())) {
  191. thumbnailView.setBackgroundColor(getResources().getColor(R.color.background_color));
  192. }
  193. } else {
  194. thumbnailView.setImageDrawable(MimeTypeUtil.getFileTypeIcon(file.getMimeType(), file.getFileName(),
  195. getAccount(), this));
  196. }
  197. }
  198. }
  199. @Override
  200. protected void onNewIntent(Intent intent) {
  201. super.onNewIntent(intent);
  202. }
  203. private void openFileChooser() {
  204. Intent action = new Intent(this, FilePickerActivity.class);
  205. action.putExtra(OCFileListFragment.ARG_MIMETYPE, "image/");
  206. startActivityForResult(action, REQUEST_REMOTE_FILE);
  207. }
  208. private void openShareDialog() {
  209. Intent intent = new Intent(this, ShareActivity.class);
  210. intent.putExtra(FileActivity.EXTRA_FILE, file);
  211. intent.putExtra(FileActivity.EXTRA_ACCOUNT, getAccount());
  212. startActivity(intent);
  213. }
  214. @Override
  215. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  216. if (RESULT_OK != resultCode) {
  217. // TODO
  218. return;
  219. }
  220. switch (requestCode) {
  221. case REQUEST_LOCAL_FILE:
  222. handleLocalFile(data, resultCode);
  223. break;
  224. case REQUEST_REMOTE_FILE:
  225. handleRemoteFile(data);
  226. break;
  227. default:
  228. // unexpected, do nothing
  229. break;
  230. }
  231. super.onActivityResult(requestCode, resultCode, data);
  232. }
  233. private void handleLocalFile(Intent data, int resultCode) {
  234. if (uploadMessage == null) {
  235. return;
  236. }
  237. uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
  238. uploadMessage = null;
  239. }
  240. private void handleRemoteFile(Intent data) {
  241. OCFile file = data.getParcelableExtra(FolderPickerActivity.EXTRA_FILES);
  242. new Thread(() -> {
  243. Account account = AccountUtils.getCurrentOwnCloudAccount(this);
  244. RichDocumentsCreateAssetOperation operation = new RichDocumentsCreateAssetOperation(file.getRemotePath());
  245. RemoteOperationResult result = operation.execute(account, this);
  246. if (result.isSuccess()) {
  247. String asset = (String) result.getSingleData();
  248. runOnUiThread(() -> webview.evaluateJavascript("OCA.RichDocuments.documentsMain.postAsset('" +
  249. file.getFileName() + "', '" + asset + "');", null));
  250. } else {
  251. runOnUiThread(() -> DisplayUtils.showSnackMessage(this, "Inserting image failed!"));
  252. }
  253. }).start();
  254. }
  255. @Override
  256. protected void onSaveInstanceState(Bundle outState) {
  257. outState.putString(EXTRA_URL, url);
  258. super.onSaveInstanceState(outState);
  259. }
  260. @Override
  261. public void onRestoreInstanceState(Bundle savedInstanceState) {
  262. url = savedInstanceState.getString(EXTRA_URL);
  263. super.onRestoreInstanceState(savedInstanceState);
  264. }
  265. @Override
  266. protected void onDestroy() {
  267. unbinder.unbind();
  268. webview.destroy();
  269. super.onDestroy();
  270. }
  271. private void closeView() {
  272. webview.destroy();
  273. finish();
  274. }
  275. private void hideLoading() {
  276. thumbnail.setVisibility(View.GONE);
  277. fileName.setVisibility(View.GONE);
  278. progressBar.setVisibility(View.GONE);
  279. webview.setVisibility(View.VISIBLE);
  280. }
  281. private class RichDocumentsMobileInterface {
  282. @JavascriptInterface
  283. public void close() {
  284. runOnUiThread(RichDocumentsWebView.this::closeView);
  285. }
  286. @JavascriptInterface
  287. public void insertGraphic() {
  288. openFileChooser();
  289. }
  290. @JavascriptInterface
  291. public void share() {
  292. openShareDialog();
  293. }
  294. @JavascriptInterface
  295. public void documentLoaded() {
  296. runOnUiThread(RichDocumentsWebView.this::hideLoading);
  297. }
  298. }
  299. private static class LoadUrl extends AsyncTask<String, Void, String> {
  300. private Account account;
  301. private WeakReference<RichDocumentsWebView> richDocumentsWebViewWeakReference;
  302. LoadUrl(RichDocumentsWebView richDocumentsWebView, Account account) {
  303. this.account = account;
  304. this.richDocumentsWebViewWeakReference = new WeakReference<>(richDocumentsWebView);
  305. }
  306. @Override
  307. protected String doInBackground(String... fileId) {
  308. if (richDocumentsWebViewWeakReference.get() == null) {
  309. return "";
  310. }
  311. RichDocumentsUrlOperation richDocumentsUrlOperation = new RichDocumentsUrlOperation(fileId[0]);
  312. RemoteOperationResult result = richDocumentsUrlOperation.execute(account,
  313. richDocumentsWebViewWeakReference.get());
  314. if (!result.isSuccess()) {
  315. return "";
  316. }
  317. return (String) result.getData().get(0);
  318. }
  319. @Override
  320. protected void onPostExecute(String url) {
  321. RichDocumentsWebView richDocumentsWebView = richDocumentsWebViewWeakReference.get();
  322. if (richDocumentsWebView == null) {
  323. return;
  324. }
  325. if (!url.isEmpty()) {
  326. richDocumentsWebView.webview.loadUrl(url);
  327. new Handler().postDelayed(() -> {
  328. if (richDocumentsWebView.webview.getVisibility() != View.VISIBLE) {
  329. DisplayUtils.createSnackbar(richDocumentsWebView.findViewById(android.R.id.content),
  330. R.string.timeout_richDocuments, Snackbar.LENGTH_INDEFINITE)
  331. .setActionTextColor(richDocumentsWebView.getResources().getColor(R.color.primary_dark))
  332. .setAction(R.string.fallback_weblogin_back, v -> richDocumentsWebView.closeView()).show();
  333. }
  334. }, 10 * 1000);
  335. } else {
  336. Toast.makeText(richDocumentsWebView.getApplicationContext(),
  337. R.string.richdocuments_failed_to_load_document, Toast.LENGTH_LONG).show();
  338. richDocumentsWebView.finish();
  339. }
  340. }
  341. }
  342. }