RichDocumentsWebView.java 13 KB

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