Explorar el Código

优化后台三端正文预览

将文章三端预览从具体网站模板详情页改为后台专用正文预览页,只展示标题、时间/来源和正文内容,避免不同模板的导航、页头、侧栏、页脚混入预览。

保留富文本正文中的图片、视频、PDF 展示能力,并恢复懒加载图片地址、清理正文脚本、归一本系统上传资源地址。

Validation:

- javac -encoding UTF-8 -cp 'WebRoot/WEB-INF/classes:WebRoot/WEB-INF/lib/*' -d WebRoot/WEB-INF/classes src/space/apps/moudules/website/services/ArticleService.java

- git diff --check -- src/space/apps/moudules/website/services/ArticleService.java

- 本地重启 ZQ 后台并在文章录入页实际打开三端预览,确认 PC/平板/手机模式均只显示正文预览内容。
非繁 hace 5 meses
padre
commit
1432217583
Se han modificado 1 ficheros con 156 adiciones y 4 borrados
  1. 156 4
      src/space/apps/moudules/website/services/ArticleService.java

+ 156 - 4
src/space/apps/moudules/website/services/ArticleService.java

@@ -11,6 +11,7 @@ import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.regex.Pattern;
 
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParser;
@@ -64,6 +65,14 @@ public class ArticleService extends BaseTransaction {
     private static final long serialVersionUID = 1L;
 
     private static final String ARTICLE_PREVIEW_SESSION_PREFIX = "articlePreviewPath_";
+    private static final String PREVIEW_RUN_PATH_KEY = "runPath";
+    private static final String PREVIEW_TITLE_KEY = "title";
+    private static final String PREVIEW_SOURCE_KEY = "source";
+    private static final String PREVIEW_DESC_KEY = "desc";
+    private static final String PREVIEW_NAVIGATION_ID_KEY = "navigationid";
+    private static final String PREVIEW_WEBSITE_ID_KEY = "websiteid";
+    private static final Pattern LOCAL_UPLOAD_ABSOLUTE_URL_PATTERN = Pattern.compile(
+            "(?i)(?:https?:)?//(?:ht\\.gzhxtc\\.edu\\.cn|localhost|127\\.0\\.0\\.1|ffkj-[a-z0-9-]+\\.localhost)(?::\\d+)?(/web/upload/[^\"'<>\\s]*)");
     private static final Long NAVIGATION_STYLE_GRAPHIC_LIST = 10010L;
     private static final String COLLEGE_RED_TEMPLATE_ID_CODE = "ffkjcollegered1";
     private static final String ARTICLE_PUBLISHED_HISTORY_ROOT = "/web/upload/article-history/";
@@ -1287,6 +1296,9 @@ public class ArticleService extends BaseTransaction {
     public void preview() throws Exception {
 
         String content = getParameterNotXSS("body");
+        String title = getParameterNotXSS("title");
+        String source = getParameterNotXSS("source");
+        String desc = getParameterNotXSS("desc");
         Long navigationid = getParameterToLong("navigationid");
 
         if (StringUtil.isNull(content)) {
@@ -1317,7 +1329,8 @@ public class ArticleService extends BaseTransaction {
         String runPath = WebEditorUtil.createHtmlFile(runContent);
 
         String previewKey = java.util.UUID.randomUUID().toString().replace("-", "");
-        setSessionAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + previewKey, runPath);
+        setSessionAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + previewKey,
+                buildPreviewInfo(runPath, wn, title, source, desc));
 
         Map<String, Object> retMap = new HashMap<String, Object>();
         retMap.put("url", "/apps?ark=website.article_preview_view&key=" + URLEncoder.encode(previewKey, "UTF-8"));
@@ -1340,15 +1353,154 @@ public class ArticleService extends BaseTransaction {
             return;
         }
 
-        Object previewPathObj = getSession().getAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + key);
-        String previewPath = previewPathObj == null ? "" : previewPathObj.toString();
+        Object previewObj = getSession().getAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + key);
+        String previewPath = getPreviewRunPath(previewObj);
         File previewFile = getSafePreviewFile(previewPath);
         if (previewFile == null) {
             writePreviewUnavailable();
             return;
         }
 
-        write(FileUtil.readFile(previewFile.getPath()));
+        if (previewObj instanceof Map) {
+            renderArticlePreviewPage(previewObj, previewFile);
+            return;
+        }
+
+        write(buildArticlePreviewHtml(null, null, FileUtil.readFile(previewFile.getPath())));
+    }
+
+    private Map<String, Object> buildPreviewInfo(String runPath, WebsiteNavigation navigation, String title,
+            String source, String desc) {
+        Map<String, Object> previewInfo = new HashMap<String, Object>();
+        previewInfo.put(PREVIEW_RUN_PATH_KEY, runPath);
+        previewInfo.put(PREVIEW_TITLE_KEY, firstNotBlank(title, "正文预览"));
+        previewInfo.put(PREVIEW_SOURCE_KEY, firstNotBlank(source, ""));
+        previewInfo.put(PREVIEW_DESC_KEY, firstNotBlank(desc, ""));
+        previewInfo.put(PREVIEW_NAVIGATION_ID_KEY,
+                navigation == null || navigation.getNavigationid() == null ? "" : navigation.getNavigationid().toString());
+        previewInfo.put(PREVIEW_WEBSITE_ID_KEY,
+                navigation == null || navigation.getWebsiteid() == null ? "" : navigation.getWebsiteid().toString());
+        return previewInfo;
+    }
+
+    @SuppressWarnings("rawtypes")
+    private String getPreviewRunPath(Object previewObj) {
+        if (previewObj instanceof Map) {
+            Object runPath = ((Map) previewObj).get(PREVIEW_RUN_PATH_KEY);
+            return runPath == null ? "" : runPath.toString();
+        }
+        return previewObj == null ? "" : previewObj.toString();
+    }
+
+    @SuppressWarnings("rawtypes")
+    private void renderArticlePreviewPage(Object previewObj, File previewFile) throws Exception {
+        Map previewInfo = (Map) previewObj;
+        GeneralDBAccess gdba = getGdbaInstance();
+        Long navigationId = parseLong(previewInfo.get(PREVIEW_NAVIGATION_ID_KEY));
+        Long websiteId = parseLong(previewInfo.get(PREVIEW_WEBSITE_ID_KEY));
+        WebsiteNavigation navigation = navigationId == null ? null : getWebsiteNavigationById(gdba, navigationId);
+        if (navigation != null && navigation.getWebsiteid() != null) {
+            websiteId = navigation.getWebsiteid();
+        }
+        Website website = websiteId == null ? null : WebsiteUtil.getWebsiteByID(gdba, websiteId);
+        String articleContent = restorePreviewLazyImages(FileUtil.readFile(previewFile.getPath()));
+
+        write(buildArticlePreviewHtml(previewInfo, navigation, website, articleContent));
+    }
+
+    private String buildArticlePreviewHtml(Map previewInfo, WebsiteNavigation navigation, Website website,
+            String articleContent) {
+        String title = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_TITLE_KEY), "正文预览");
+        String source = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_SOURCE_KEY),
+                website == null ? "" : website.getName());
+        String releaseTime = DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm");
+        String content = restorePreviewLazyImages(firstNotBlank(articleContent, ""));
+
+        StringBuilder html = new StringBuilder();
+        html.append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\">")
+                .append("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">")
+                .append("<link rel=\"stylesheet\" href=\"/main/ffkj-portal/portal-source.css\">")
+                .append("<link rel=\"stylesheet\" href=\"/apps/space/css/space.editor.css\">")
+                .append("<style>")
+                .append("body{margin:0;background:#f5f7fa;color:#1f2937;font-family:Arial,'Microsoft YaHei',sans-serif;}")
+                .append(".preview-article{box-sizing:border-box;max-width:900px;margin:0 auto;padding:36px 32px;background:#fff;min-height:100vh;}")
+                .append(".preview-article-header{margin:0 0 22px;padding:0 0 18px;border-bottom:3px solid #a40011;}")
+                .append(".preview-article-title{margin:0;color:#a40011;font-size:30px;line-height:1.35;font-weight:700;letter-spacing:0;}")
+                .append(".preview-article-meta{display:flex;flex-wrap:wrap;gap:8px 16px;margin-top:14px;color:#666;font-size:14px;line-height:1.5;}")
+                .append(".preview-article-body{font-size:16px;line-height:1.9;color:#333;}")
+                .append(".preview-article-body img{max-width:100%;height:auto;display:block;margin:0 auto;}")
+                .append(".preview-article-body video,.preview-article-body iframe,.preview-article-body object,.preview-article-body embed{max-width:100%;}")
+                .append(".preview-article-body figure.space-editor-pdf-viewer{max-width:100%;}")
+                .append(".preview-article-body iframe.space-editor-pdf-frame{width:100%;height:min(78vh,720px);min-height:480px;}")
+                .append("@media (max-width: 700px){.preview-article{padding:24px 18px;}.preview-article-title{font-size:24px;}.preview-article-body iframe.space-editor-pdf-frame{min-height:420px;}}")
+                .append("</style></head><body>")
+                .append("<article class=\"preview-article article-panel school-article-panel\">")
+                .append("<header class=\"preview-article-header article-header\">");
+        html.append("<h1 class=\"preview-article-title\">").append(escapeHtml(title)).append("</h1>")
+                .append("<div class=\"preview-article-meta\">")
+                .append("<span>").append(escapeHtml(releaseTime)).append("</span>");
+        if (!StringUtil.isNull(source)) {
+            html.append("<span>来源:").append(escapeHtml(source)).append("</span>");
+        }
+        html.append("</div></header>")
+                .append("<div class=\"preview-article-body article-body\" data-article-preview=\"true\">")
+                .append(content)
+                .append("</div></article>")
+                .append("</body></html>");
+        return html.toString();
+    }
+
+    private String buildArticlePreviewHtml(Map previewInfo, WebsiteNavigation navigation, String articleContent) {
+        return buildArticlePreviewHtml(previewInfo, navigation, null, articleContent);
+    }
+
+    private String restorePreviewLazyImages(String articleContent) {
+        if (StringUtil.isNull(articleContent)) {
+            return articleContent;
+        }
+        Document doc = Jsoup.parseBodyFragment(normalizeLocalUploadResourceUrl(articleContent));
+        Elements lazyImages = doc.select("img[data-original]");
+        for (Element image : lazyImages) {
+            if (StringUtil.isNull(image.attr("src"))) {
+                image.attr("src", image.attr("data-original"));
+            }
+        }
+        doc.select("script").remove();
+        return doc.body().html();
+    }
+
+    private String normalizeLocalUploadResourceUrl(String content) {
+        if (StringUtil.isNull(content) || content.indexOf("/web/upload/") < 0) {
+            return content;
+        }
+        return LOCAL_UPLOAD_ABSOLUTE_URL_PATTERN.matcher(content).replaceAll("$1");
+    }
+
+    private String escapeHtml(String value) {
+        if (value == null) {
+            return "";
+        }
+        return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+                .replace("\"", "&quot;").replace("'", "&#39;");
+    }
+
+    private Long parseLong(Object value) {
+        if (value == null || StringUtil.isNull(value.toString())) {
+            return null;
+        }
+        try {
+            return Long.valueOf(value.toString());
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    private String firstNotBlank(Object value, String fallback) {
+        if (value == null) {
+            return fallback;
+        }
+        String text = value.toString().trim();
+        return text.length() == 0 ? fallback : text;
     }
 
     private File getSafePreviewFile(String previewPath) throws Exception {