Simplify Media Identification Function

Rebased from LBRY/lbry-app PR# 1304 with corrections requested by Codacy (Though may still complain regarding spacing).

This just makes the code for finding documents a lot easier. the regex patterns and the media type are converted into keypairs, [regex, mediatype] which is then reduced to a single value, which will either be the original filename if there are no matching extensions, or the mediatype. So long as the mediatype does not contain an extension at the end of the string, this system should work far more simply.

This will also allow for easier addition of new extensions to the function, so long as they all follow the same pattern for the regex:
^ = Start of string
.+ = 1 or more characters of any type
. = A literal dot
(a|b|c) = A list of ORed extensions within a capture group '( )'
$ = End of string, so it is certain this is the actual extension of the filename

Won't be hard to add things like Archives, Executables, etc with just a single extra line now.
This commit is contained in:
ProfessorDey 2018-04-19 17:59:24 +00:00 committed by GitHub
parent 800083dc24
commit 40ae42c5f6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -112,20 +112,16 @@ Lbry.getMediaType = (contentType, fileName) => {
if (contentType) {
return /^[^/]+/.exec(contentType)[0];
} else if (fileName) {
const dotIndex = fileName.lastIndexOf('.');
if (dotIndex === -1) {
return 'unknown';
}
const ext = fileName.substr(dotIndex + 1);
if (/^mp4|m4v|webm|flv|f4v|ogv$/i.test(ext)) {
return 'video';
} else if (/^mp3|m4a|aac|wav|flac|ogg|opus$/i.test(ext)) {
return 'audio';
} else if (/^html|htm|xml|pdf|odf|doc|docx|md|markdown|txt|epub|org$/i.test(ext)) {
return 'document';
}
return 'unknown';
const formats = [
[/^.+\.(mp4|m4v|webm|flv|f4v|ogv)$/i, 'video'],
[/^.+\.(mp3|m4a|aac|wav|flac|ogg|opus)$/i, 'audio'],
[/^.+\.(html|htm|xml|pdf|odf|doc|docx|md|markdown|txt|epub|org)$/i, 'document']];
const res = formats.reduce(function extensionMatch(ret, testpair) {
switch (testpair[0].test(ret)) {
case true: return testpair[1];
default: return ret; }
}, fileName);
return res === fileName ? 'unknown' : res;
}
return 'unknown';
};