| 1 |
package ezvcard.io.scribe; |
| 2 |
|
| 3 |
import ezvcard.io.CannotParseException; |
| 4 |
import ezvcard.io.ParseContext; |
| 5 |
import ezvcard.io.html.HCardElement; |
| 6 |
import ezvcard.parameter.SoundType; |
| 7 |
import ezvcard.property.Sound; |
| 8 |
import ezvcard.util.DataUri; |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
public class SoundScribe extends BinaryPropertyScribe<Sound, SoundType> { |
| 40 |
public SoundScribe() { |
| 41 |
super(Sound.class, "SOUND"); |
| 42 |
} |
| 43 |
|
| 44 |
@Override |
| 45 |
protected SoundType _mediaTypeFromTypeParameter(String type) { |
| 46 |
return SoundType.get(type, null, null); |
| 47 |
} |
| 48 |
|
| 49 |
@Override |
| 50 |
protected SoundType _mediaTypeFromMediaTypeParameter(String mediaType) { |
| 51 |
return SoundType.get(null, mediaType, null); |
| 52 |
} |
| 53 |
|
| 54 |
@Override |
| 55 |
protected SoundType _mediaTypeFromFileExtension(String extension) { |
| 56 |
return SoundType.find(null, null, extension); |
| 57 |
} |
| 58 |
|
| 59 |
@Override |
| 60 |
protected Sound _newInstance(String uri, SoundType contentType) { |
| 61 |
return new Sound(uri, contentType); |
| 62 |
} |
| 63 |
|
| 64 |
@Override |
| 65 |
protected Sound _newInstance(byte[] data, SoundType contentType) { |
| 66 |
return new Sound(data, contentType); |
| 67 |
} |
| 68 |
|
| 69 |
@Override |
| 70 |
protected Sound _parseHtml(HCardElement element, ParseContext context) { |
| 71 |
String elementName = element.tagName(); |
| 72 |
if (!"audio".equals(elementName) && !"source".equals(elementName)) { |
| 73 |
return super._parseHtml(element, context); |
| 74 |
} |
| 75 |
|
| 76 |
if ("audio".equals(elementName)) { |
| 77 |
|
| 78 |
org.jsoup.nodes.Element source = element.getElement().getElementsByTag("source").first(); |
| 79 |
if (source == null) { |
| 80 |
throw new CannotParseException(16); |
| 81 |
} |
| 82 |
|
| 83 |
element = new HCardElement(source); |
| 84 |
} |
| 85 |
|
| 86 |
String src = element.absUrl("src"); |
| 87 |
if (src.isEmpty()) { |
| 88 |
throw new CannotParseException(17); |
| 89 |
} |
| 90 |
|
| 91 |
String type = element.attr("type"); |
| 92 |
SoundType mediaType = type.isEmpty() ? null : _mediaTypeFromMediaTypeParameter(type); |
| 93 |
|
| 94 |
try { |
| 95 |
DataUri uri = DataUri.parse(src); |
| 96 |
mediaType = _mediaTypeFromMediaTypeParameter(uri.getContentType()); |
| 97 |
return new Sound(uri.getData(), mediaType); |
| 98 |
} catch (IllegalArgumentException e) { |
| 99 |
|
| 100 |
if (mediaType == null) { |
| 101 |
String extension = getFileExtension(src); |
| 102 |
mediaType = (extension == null) ? null : _mediaTypeFromFileExtension(extension); |
| 103 |
} |
| 104 |
return new Sound(src, mediaType); |
| 105 |
} |
| 106 |
} |
| 107 |
} |