ui: markdown: add support for @[bilibili](BVxxx)

This commit is contained in:
undefined committed 2022-05-22 01:13:26 +08:00
1 parent 025636d7f2
commit 53bde9c966
3 files changed
+62 -55

No files matched your search

@@ -1,38 +1,39 @@
/* eslint-disable max-len */
/* eslint-disable prefer-destructuring */
const { randomUUID } = require('crypto');
const { escapeHtml } = require('markdown-it/lib/common/utils');
import { randomUUID } from 'crypto';
import MarkdownIt from 'markdown-it';
const allowFullScreen = ' webkitallowfullscreen mozallowfullscreen allowfullscreen';
/* eslint-disable no-restricted-properties */
const ytRegex = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
function youtubeParser(url) {
function youtubeParser(url: string) {
const match = url.match(ytRegex);
return match && match[7].length === 11 ? match[7] : url;
}
const vimeoRegex = /https?:\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/;
function vimeoParser(url) {
function vimeoParser(url: string) {
const match = url.match(vimeoRegex);
return match && typeof match[3] === 'string' ? match[3] : url;
}
const vineRegex = /^http(?:s?):\/\/(?:www\.)?vine\.co\/v\/([a-zA-Z0-9]{1,13}).*/;
function vineParser(url) {
function vineParser(url: string) {
const match = url.match(vineRegex);
return match && match[1].length === 11 ? match[1] : url;
}
const preziRegex = /^https:\/\/prezi.com\/(.[^/]+)/;
function preziParser(url) {
function preziParser(url: string) {
const match = url.match(preziRegex);
return match ? match[1] : url;
}
// TODO: Write regex for staging and local servers.
const mfrRegex = /^http(?:s?):\/\/(?:www\.)?mfr\.osf\.io\/render\?url=http(?:s?):\/\/osf\.io\/([a-zA-Z0-9]{1,5})\/\?action=download/;
function mfrParser(url) {
function mfrParser(url: string) {
const match = url.match(mfrRegex);
return match ? match[1] : url;
}
const EMBED_REGEX = /@\[([a-zA-Z].+?)]\((.*?)[)]/im;
function extractVideoParameters(url) {
function extractVideoParameters(url: string) {
const parameterMap = new Map();
const params = url.replace(/&/gi, '&').split(/[#?&]/);
if (params.length > 1) {
@@ -43,7 +44,7 @@ function extractVideoParameters(url) {
}
return parameterMap;
}
function videoUrl(service, videoID, url, options) {
function resourceUrl(service: string, src: string, url: string, options) {
if (service === 'youtube') {
const parameters = extractVideoParameters(url);
if (options.youtube.parameters) {
@@ -57,7 +58,7 @@ function videoUrl(service, videoID, url, options) {
const timeParts = timeParameter.match(/[0-9]+/g);
let j = 0;
while (timeParts.length > 0) {
startTime += Number(timeParts.pop()) * Math.pow(60, j);
startTime += Number(timeParts.pop()) * (60 ** j);
j += 1;
}
parameters.set('start', startTime);
@@ -67,58 +68,68 @@ function videoUrl(service, videoID, url, options) {
parameters.delete('feature');
parameters.delete('origin');
const parameterArray = Array.from(parameters, (p) => p.join('='));
const parameterPos = videoID.indexOf('?');
const parameterPos = src.indexOf('?');
let finalUrl = 'https://www.youtube';
if (options.youtube.nocookie || url.indexOf('youtube-nocookie.com') > -1) finalUrl += '-nocookie';
finalUrl += `.com/embed/${parameterPos > -1 ? videoID.substr(0, parameterPos) : videoID}`;
finalUrl += `.com/embed/${parameterPos > -1 ? src.substr(0, parameterPos) : src}`;
if (parameterArray.length > 0) finalUrl += `?${parameterArray.join('&')}`;
return finalUrl;
}
if (service === 'vimeo') return `https://player.vimeo.com/video/${videoID}`;
if (service === 'vine') return `https://vine.co/v/${videoID}/embed/${options.vine.embed}`;
if (service === 'vimeo') return `https://player.vimeo.com/video/${src}`;
if (service === 'vine') return `https://vine.co/v/${src}/embed/${options.vine.embed}`;
if (service === 'prezi') {
return `https://prezi.com/embed/${videoID}/?bgcolor=ffffff&lock_to_path=0&autoplay=0&autohide_ctrls=0&`
return `https://prezi.com/embed/${src}/?bgcolor=ffffff&lock_to_path=0&autoplay=0&autohide_ctrls=0&`
+ 'landing_data=bHVZZmNaNDBIWnNjdEVENDRhZDFNZGNIUE43MHdLNWpsdFJLb2ZHanI5N1lQVHkxSHFxazZ0UUNCRHloSXZROHh3PT0&'
+ 'landing_sign=1kD6c0N6aYpMUS0wxnQjxzSqZlEB8qNFdxtdjYhwSuI';
}
if (service === 'osf') return `https://mfr.osf.io/render?url=https://osf.io/${videoID}/?action=download`;
return videoID;
if (service === 'osf') return `https://mfr.osf.io/render?url=https://osf.io/${src}/?action=download`;
return src;
}
module.exports = function videoPlugin(md) {
// eslint-disable-next-line import/prefer-default-export
export function Media(md: MarkdownIt) {
const options = {
url: videoUrl,
video: videoUrl,
url: resourceUrl,
video: resourceUrl,
youtube: { width: 640, height: 390, nocookie: false },
vimeo: { width: 500, height: 281 },
vine: { width: 600, height: 600, embed: 'simple' },
prezi: { width: 550, height: 400 },
osf: { width: '100%', height: '100%' },
pdf: videoUrl,
pdf: resourceUrl,
};
md.renderer.rules.video = function tokenizeReturn(tokens, idx) {
let videoID = md.utils.escapeHtml(tokens[idx].videoID);
const service = md.utils.escapeHtml(tokens[idx].service).toLowerCase();
let src = md.utils.escapeHtml(tokens[idx].attrGet('src'));
const service = md.utils.escapeHtml(tokens[idx].attrGet('service')).toLowerCase();
const checkUrl = /http(?:s?):\/\/(?:www\.)?[a-zA-Z0-9-:.]{1,}\/render(?:\/)?[a-zA-Z0-9.&;?=:%]{1,}url=http(?:s?):\/\/[a-zA-Z0-9 -:.]{1,}\/[a-zA-Z0-9]{1,5}\/\?[a-zA-Z0-9.=:%]{1,}/;
let num;
if (service === 'osf' && videoID) {
if (service === 'osf' && src) {
num = Math.random() * 0x10000;
if (videoID.match(checkUrl)) {
if (src.match(checkUrl)) {
return `<div id="${num}" class="mfr mfr-file"></div><script>`
+ `$(document).ready(function () {new mfr.Render("${num}", "${videoID}");`
+ `$(document).ready(function () {new mfr.Render("${num}", "${src}");`
+ ' }); </script>';
}
return `<div id="${num}" class="mfr mfr-file"></div><script>`
+ `$(document).ready(function () {new mfr.Render("${num}", "https://mfr.osf.io/`
+ `render?url=https://osf.io/${videoID}/?action=download%26mode=render");`
+ `render?url=https://osf.io/${src}/?action=download%26mode=render");`
+ ' }); </script>';
}
if (service === 'bilibili') {
if (src.startsWith('http')) src = src.split('/').pop();
if (src.toLowerCase().startsWith('av')) src = src.toLowerCase().split('av')[1];
src = src.split('?')[0];
return `\
<iframe src="//player.bilibili.com/player.html?${src.startsWith('BV') ? 'bvid' : 'aid'}=${src}"
scrolling="no" border="0" frameborder="no" framespacing="0" width="100%" style="min-height:500px" ${allowFullScreen}></iframe>
`;
}
if (service === 'pdf') {
if (videoID.startsWith('file://')) videoID += videoID.includes('?') ? '&noDisposition=1' : '?noDisposition=1';
if (src.startsWith('file://')) src += src.includes('?') ? '&noDisposition=1' : '?noDisposition=1';
return `\
<object classid="clsid:${randomUUID().toUpperCase()}">
<param name="SRC" value="${videoID}" >
<embed width="100%" style="min-height: 100vh;border: none;" fullscreen="yes" src="${videoID}">
<param name="SRC" value="${src}" >
<embed width="100%" style="min-height: 100vh;border: none;" fullscreen="yes" src="${src}">
<noembed></noembed>
</embed>
</object>`;
@@ -126,7 +137,7 @@ module.exports = function videoPlugin(md) {
if (['url', 'video'].includes(service)) {
return `\
<video width="100%" controls>
<source src="${videoID}" type="${videoID.endsWith('ogg') ? 'video/ogg' : 'video/mp4'}">
<source src="${src}" type="${src.endsWith('ogg') ? 'video/ogg' : 'video/mp4'}">
Your browser doesn't support video tag.
</video>`;
}
@@ -134,14 +145,12 @@ module.exports = function videoPlugin(md) {
return `<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item ${service}-player" type="text/html" width="${options[service].width || 640}"\
height="${options[service].height || 390}"\
src="${options.url(service, videoID, tokens[idx].url, options)}"
frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>`;
src="${options.url(service, src, tokens[idx].attrGet('url'), options)}"
frameborder="0"${allowFullScreen}></iframe></div>`;
}
return `<div data-${service}>${escapeHtml(videoID)}</div>`;
return `<div data-${service}>${md.utils.escapeHtml(src)}</div>`;
};
md.inline.ruler.before('emphasis', 'video', (state, silent) => {
let token;
let videoID;
const theState = state;
const oldPos = state.pos;
if (state.src.charCodeAt(oldPos) !== 0x40
@@ -150,29 +159,26 @@ module.exports = function videoPlugin(md) {
}
const match = EMBED_REGEX.exec(state.src.slice(state.pos, state.src.length));
if (!match || match.length < 3) return false;
const service = match[1];
videoID = match[2];
const serviceLower = service.toLowerCase();
if (serviceLower === 'youtube') videoID = youtubeParser(videoID);
else if (serviceLower === 'vimeo') videoID = vimeoParser(videoID);
else if (serviceLower === 'vine') videoID = vineParser(videoID);
else if (serviceLower === 'prezi') videoID = preziParser(videoID);
else if (serviceLower === 'osf') videoID = mfrParser(videoID);
if (videoID === ')') videoID = '';
let [, service, src] = match;
service = service.toLowerCase();
if (service === 'youtube') src = youtubeParser(src);
else if (service === 'vimeo') src = vimeoParser(src);
else if (service === 'vine') src = vineParser(src);
else if (service === 'prezi') src = preziParser(src);
else if (service === 'osf') src = mfrParser(src);
if (src === ')') src = '';
const serviceStart = oldPos + 2;
const serviceEnd = md.helpers.parseLinkLabel(state, oldPos + 1, false);
if (!silent) {
theState.pos = serviceStart;
theState.service = theState.src.slice(serviceStart, serviceEnd);
const newState = new theState.md.inline.State(service, theState.md, theState.env, []);
newState.md.inline.tokenize(newState);
token = theState.push('video', '');
token.videoID = videoID;
token.service = service;
token.url = match[2];
const token = theState.push('video', '', undefined);
token.attrPush(['src', src]);
token.attrPush(['service', service]);
token.attrPush(['url', match[2]]);
token.level = theState.level;
}
theState.pos += theState.src.indexOf(')', theState.pos);
return true;
});
};
}
+1 -1
View File
@@ -22,7 +22,7 @@ const MergeCells = require('markdown-it-merge-cells');
// @[url](videourl)
// @[youtube](https://youtube.com/watch?v=xxx)
// @[pdf](https://foo.com/bar.pdf)
const Media = require('./markdown-it-media');
const { Media } = require('./markdown-it-media');
const Katex = require('./markdown-it-katex');
const { xssProtector } = require('./markdown-it-xss');
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hydrooj/ui-default",
"version": "4.37.9",
"version": "4.37.10",
"author": "undefined <i@undefined.moe>",
"license": "AGPL-3.0",
"main": "hydro.js",
@@ -24,6 +24,7 @@
"@types/jquery": "^3.5.14",
"@types/json-schema": "^7.0.11",
"@types/katex": "^0.14.0",
"@types/markdown-it": "^12.2.3",
"@types/qrcode": "^1.4.2",
"@types/react-dom": "^18.0.4",
"@types/redux-logger": "^3.0.9",