Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -167,16 +167,14 @@ public void share(PluginCall call) {
private void shareFiles(JSArray files, Intent intent, PluginCall call) {
List<Object> filesList;
ArrayList<Uri> fileUris = new ArrayList<>();
String sharedType = null;
try {
filesList = files.toList();
for (int i = 0; i < filesList.size(); i++) {
String file = (String) filesList.get(i);
if (isFileUrl(file)) {
String type = getMimeType(file);
if (type == null || filesList.size() > 1) {
type = "*/*";
}
intent.setType(type);
sharedType = i == 0 ? getMimeType(file) : getCommonMimeType(sharedType, getMimeType(file));
intent.setType(sharedType != null ? sharedType : "*/*");

Uri fileUrl = FileProvider.getUriForFile(
getActivity(),
Expand Down Expand Up @@ -227,6 +225,24 @@ private String getMimeType(String url) {
return type;
}

/**
* Returns the most specific MIME type that covers both types: the type itself when they match,
* {@code type/*} when only the top-level type matches, and {@code null} otherwise.
*/
static String getCommonMimeType(String first, String second) {
if (first == null || second == null) {
return null;
}
if (first.equals(second)) {
return first;
}
int slash = first.indexOf('/');
if (slash > 0 && slash == second.indexOf('/') && first.regionMatches(0, second, 0, slash)) {
return first.substring(0, slash) + "/*";
}
return null;
}

private boolean isFileUrl(String url) {
return url.startsWith("file:");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.capacitorjs.plugins.share;

import static org.junit.Assert.*;

import org.junit.Test;

public class SharePluginTest {

@Test
public void getCommonMimeType_keepsMatchingType() {
assertEquals("image/jpeg", SharePlugin.getCommonMimeType("image/jpeg", "image/jpeg"));
}

@Test
public void getCommonMimeType_usesWildcardSubtypeForSameTopLevelType() {
assertEquals("image/*", SharePlugin.getCommonMimeType("image/jpeg", "image/png"));
assertEquals("image/*", SharePlugin.getCommonMimeType("image/*", "image/png"));
assertEquals("video/*", SharePlugin.getCommonMimeType("video/mp4", "video/webm"));
}

@Test
public void getCommonMimeType_returnsNullForDifferentOrUnknownTypes() {
assertNull(SharePlugin.getCommonMimeType("image/jpeg", "video/mp4"));
assertNull(SharePlugin.getCommonMimeType("image/jpeg", null));
assertNull(SharePlugin.getCommonMimeType(null, "image/jpeg"));
assertNull(SharePlugin.getCommonMimeType("imagex/png", "image/png"));
}
}