Halo 開源專案學習(四):釋出文章與頁面

John同學發表於2022-04-26

基本介紹

部落格最基本的功能就是讓作者能夠自由釋出自己的文章,分享自己觀點,記錄學習的過程。Halo 為使用者提供了釋出文章和展示自定義頁面的功能,下面我們分析一下這些功能的實現過程。

管理員釋出文章

Halo 專案中,文章和頁面的實體類分別為 Post 和 Sheet,二者都是 BasePost 的子類。BasePost 對應資料庫中的 posts 表,posts 表既儲存了文章的資料,又儲存了頁面的資料,那麼專案中是如何區分文章和頁面的呢?下面是 BasePost 類的原始碼(僅展示部分程式碼):

@Data
@Entity(name = "BasePost")
@Table(name = "posts", indexes = {
    @Index(name = "posts_type_status", columnList = "type, status"),
    @Index(name = "posts_create_time", columnList = "create_time")})
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.INTEGER,
    columnDefinition = "int default 0")
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class BasePost extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id")
    @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support"
        + ".CustomIdGenerator")
    private Integer id;

    /**
     * Post title.
     */
    @Column(name = "title", nullable = false)
    private String title;

    /**
     * Post status.
     */
    @Column(name = "status")
    @ColumnDefault("1")
    private PostStatus status;
    // 此處省略部分程式碼
}

我們知道,Halo 使用 JPA 來建立資料表、儲存和獲取表中的資訊。上述程式碼中,註解 @DiscriminatorColumn 是之前文章中沒有介紹過的,@DiscriminatorColumn 屬於 JPA 註解,它的作用是當多個實體類對應同一個資料表時,可使用一個欄位進行區分。name 指定該欄位的名稱,discriminatorType 是該欄位的型別,columnDefinition 設定該欄位的預設值。由此可知,欄位 type 是區分文章和頁面的依據,下面是 Post 類和 Sheet 類的原始碼:

// Post
@Entity(name = "Post")
@DiscriminatorValue(value = "0")
public class Post extends BasePost {

}

// Sheet
@Entity(name = "Sheet")
@DiscriminatorValue("1")
public class Sheet extends BasePost {

}

Post 和 Sheet 都沒有定義額外的屬性,二者的區別僅在於註解 @DiscriminatorValue 設定的 value 不同。上文提到,@DiscriminatorColumn 指明瞭用作區分的欄位,而 @DiscriminatorValue 的作用就是指明該欄位的具體值。也就是說,type 為 0 時表示文章,為 1 時表示頁面。另外,這裡也簡單介紹一下 @Index 註解,該註解用於宣告表中的索引,例如 @Index(name = "posts_type_status", columnList = "type, status") 表示在 posts 表中建立 type 和 status 的複合索引,索引名稱為 posts_type_status。

下面我們繼續分析文章是如何釋出的,首先進入到管理員介面,然後點選 "文章" -> "寫文章",之後就可以填寫內容了:

為了全面瞭解文章釋出的過程,我們儘量將能填的資訊都填上。點選 "釋出",觸發 /api/admin/posts 請求:

api/admin/posts 請求在 PostController 中定義:

@PostMapping
@ApiOperation("Creates a post")
public PostDetailVO createBy(@Valid @RequestBody PostParam postParam,
    @RequestParam(value = "autoSave", required = false, defaultValue = "false") Boolean autoSave
) {
    // 將 PostParam 物件轉化為 Post 物件
    // Convert to
    Post post = postParam.convertTo();
    // 根據引數建立文章
    return postService.createBy(post, postParam.getTagIds(), postParam.getCategoryIds(),
        postParam.getPostMetas(), autoSave);
}

該請求接收兩個引數,即 postParam 和 autoSave。postParam 儲存我們填寫的文章資訊,autoSave 是與系統日誌有關的引數,預設為 false。伺服器收到請求後,首先將接收到的 PostParam 物件轉化為 Post 物件,然後從 PostParam 中提取出文章標籤、分類、後設資料等,接著呼叫 createBy 方法建立文章,createBy 方法的處理邏輯為:

public PostDetailVO createBy(Post postToCreate, Set<Integer> tagIds, Set<Integer> categoryIds,
    Set<PostMeta> metas, boolean autoSave) {
    // 建立或更新文章
    PostDetailVO createdPost = createOrUpdate(postToCreate, tagIds, categoryIds, metas);
    if (!autoSave) {
        // 記錄系統日誌
        // Log the creation
        LogEvent logEvent = new LogEvent(this, createdPost.getId().toString(),
            LogType.POST_PUBLISHED, createdPost.getTitle());
        eventPublisher.publishEvent(logEvent);
    }
    return createdPost;
}

該方法會呼叫 createOrUpdate 方法建立文章,由於 autoSave 為 false,所以文章建立完成後會記錄一條關於文章釋出的系統日誌。繼續進入 createOrUpdate 方法,檢視建立文章的具體過程:

private PostDetailVO createOrUpdate(@NonNull Post post, Set<Integer> tagIds,
        Set<Integer> categoryIds, Set<PostMeta> metas) {
    Assert.notNull(post, "Post param must not be null");

    // 檢視建立或更新的文章是否為私密文章
    // Create or update post
    Boolean needEncrypt = Optional.ofNullable(categoryIds)
        .filter(HaloUtils::isNotEmpty)
        .map(categoryIdSet -> {
            for (Integer categoryId : categoryIdSet) {
                // 文章分類是否設有密碼
                if (categoryService.categoryHasEncrypt(categoryId)) {
                    return true;
                }
            }
            return false;
        }).orElse(Boolean.FALSE);

    // 如果文章的密碼不為空或者所屬分類設有密碼, 那麼該文章就屬於私密文章
    // if password is not empty or parent category has encrypt, change status to intimate
    if (post.getStatus() != PostStatus.DRAFT
        && (StringUtils.isNotEmpty(post.getPassword()) || needEncrypt)
    ) {
        post.setStatus(PostStatus.INTIMATE);
    }

    // 格式化文章的內容, 檢查文章的別名是否有重複, 都沒問題就建立文章
    post = super.createOrUpdateBy(post);

    // 移除文章原先繫結的標籤
    postTagService.removeByPostId(post.getId());

    // 移除文章原先繫結的分類
    postCategoryService.removeByPostId(post.getId());

    // 新設定的標籤
    // List all tags
    List<Tag> tags = tagService.listAllByIds(tagIds);

    // 新設定的分類
    // List all categories
    List<Category> categories = categoryService.listAllByIds(categoryIds, true);

    // Create post tags
    List<PostTag> postTags = postTagService.mergeOrCreateByIfAbsent(post.getId(),
        ServiceUtils.fetchProperty(tags, Tag::getId));

    log.debug("Created post tags: [{}]", postTags);

    // Create post categories
    List<PostCategory> postCategories =
        postCategoryService.mergeOrCreateByIfAbsent(post.getId(),
            ServiceUtils.fetchProperty(categories, Category::getId));

    log.debug("Created post categories: [{}]", postCategories);

    // 移除文章原有的後設資料並將新設定的後設資料繫結到該文章
    // Create post meta data
    List<PostMeta> postMetaList = postMetaService
        .createOrUpdateByPostId(post.getId(), metas);
    log.debug("Created post metas: [{}]", postMetaList);

    // 當文章建立或更新時清除對所有客戶端的授權
    // Remove authorization every time an post is created or updated.
    authorizationService.deletePostAuthorization(post.getId());

    // 返回文章的資訊, 便於管理員介面展示
    // Convert to post detail vo
    return convertTo(post, tags, categories, postMetaList);
}
  1. 檢查當前建立或更新的文章是否為私密文章,如果文章設有密碼,或者文章所屬的分類設有密碼,那麼就將文章的狀態改為 INTIMATE,表示該文章屬於私密文章。

  2. 對文章的內容進行格式化,也就是將原始內容轉化為能夠在前端展示的帶有 HTML 標籤的內容。然後檢查文章的別名是否有重複,檢查無誤後在 posts 表中建立該文章。

  3. 移除文章原先繫結的所有標籤和分類。

  4. 為文章重新繫結標籤和分類,以標籤為例,繫結的邏輯為:首先查詢出文章原先繫結的標籤,記為集合 A,然後將新設定的標籤記為集合 B,之後在 post_tags 表中刪除集合 A 中存在但集合 B 中不存在的記錄,並建立集合 B 中不存在而集合 A 中存在的記錄。步驟 4 其實和步驟 3 是有衝突的,因為步驟 3 將文章原先繫結的標籤刪除了,所以集合 A 中的元素總是為 0,實際上步驟 3 中的操作是多餘的,可以將其註釋掉。

  5. 移除文章原有的後設資料,將新設定的後設資料繫結到該文章。

  6. 刪除對所有客戶端的文章授權,文章授權是針對私密文章設定的,在下節中我們會分析一下文章授權的作用。

  7. 返回文章的具體資訊,供管理員頁面展示。

執行完以上步驟,一篇文章就建立或更新完成了:

使用者端訪問文章

本節介紹使用者(普通使用者,非管理員)訪問文章的具體過程,上文中,我們在建立文章時為文章設定了密碼,因此該文章屬於私密文章。Halo 為私密文章設定了的 "授權" 機制,授權指的是當使用者首次訪問私密文章時,需要填寫訪問密碼,伺服器收到請求後,會檢查使用者的密碼是否正確。如果正確,那麼服務端會對客戶端進行授權,這樣當使用者在短時間內再次訪問該文章時可以不用重複輸入密碼。

預設情況下私密文章是不會在部落格首頁展示的,為了測試,我們修改 PostModel 中的 list 方法,首先將下面的程式碼註釋掉:

Page<Post> postPage = postService.pageBy(PostStatus.PUBLISHED, pageable);

然後新增如下程式碼:

PostQuery query = new PostQuery();
query.setStatuses(new HashSet<>(Arrays.asList(PostStatus.PUBLISHED, PostStatus.INTIMATE)));
Page<Post> postPage = postService.pageBy(query, pageable);

這樣,部落格主頁就可以展示狀態為 "已釋出" 和 "私密" 的文章了:

點選 "我的第一篇文章",觸發 /archives/first 請求,first 為文章的別名 slug,該請求由 ContentContentController 的 content 方法處理(僅展示部分程式碼):

@GetMapping("{prefix}/{slug}")
public String content(@PathVariable("prefix") String prefix,
    @PathVariable("slug") String slug,
    @RequestParam(value = "token", required = false) String token,
    Model model) {
    PostPermalinkType postPermalinkType = optionService.getPostPermalinkType();
    if (optionService.getArchivesPrefix().equals(prefix)) {
        if (postPermalinkType.equals(PostPermalinkType.DEFAULT)) {
            // 根據 slug 查詢出文章的
            Post post = postService.getBySlug(slug);
            return postModel.content(post, token, model);
        }
        // 省略部分程式碼
    }
}

上述方法首先根據 slug 查詢出 title 為 "我的第一篇文章" 的文章,然後呼叫 postModel.content 方法封裝文章的資訊,postModel.content 方法的處理邏輯如下:

public String content(Post post, String token, Model model) {
    // 文章在回收站
    if (PostStatus.RECYCLE.equals(post.getStatus())) {
        // Articles in the recycle bin are not allowed to be accessed.
        throw new NotFoundException("查詢不到該文章的資訊");
    } else if (StringUtils.isNotBlank(token)) {
        // If the token is not empty, it means it is an admin request,
        // then verify the token.

        // verify token
        String cachedToken = cacheStore.getAny(token, String.class)
            .orElseThrow(() -> new ForbiddenException("您沒有該文章的訪問許可權"));
        if (!cachedToken.equals(token)) {
            throw new ForbiddenException("您沒有該文章的訪問許可權");
        }
        // 手稿
    } else if (PostStatus.DRAFT.equals(post.getStatus())) {
        // Drafts are not allowed bo be accessed by outsiders.
        throw new NotFoundException("查詢不到該文章的資訊");
        //
    } else if (PostStatus.INTIMATE.equals(post.getStatus())
        && !authenticationService.postAuthentication(post, null)
    ) {
        // Encrypted articles must has the correct password before they can be accessed.

        model.addAttribute("slug", post.getSlug());
        model.addAttribute("type", EncryptTypeEnum.POST.getName());
        // 如果啟用的主題定義了輸入密碼頁面
        if (themeService.templateExists(POST_PASSWORD_TEMPLATE + SUFFIX_FTL)) {
            return themeService.render(POST_PASSWORD_TEMPLATE);
        }
        // 進入輸入密碼頁面
        return "common/template/" + POST_PASSWORD_TEMPLATE;
    }

    post = postService.getById(post.getId());

    if (post.getEditorType().equals(PostEditorType.MARKDOWN)) {
        post.setFormatContent(MarkdownUtils.renderHtml(post.getOriginalContent()));
    } else {
        post.setFormatContent(post.getOriginalContent());
    }

    postService.publishVisitEvent(post.getId());

    postService.getPrevPost(post).ifPresent(
        prevPost -> model.addAttribute("prevPost", postService.convertToDetailVo(prevPost)));
    postService.getNextPost(post).ifPresent(
        nextPost -> model.addAttribute("nextPost", postService.convertToDetailVo(nextPost)));

    List<Category> categories = postCategoryService.listCategoriesBy(post.getId(), false);
    List<Tag> tags = postTagService.listTagsBy(post.getId());
    List<PostMeta> metas = postMetaService.listBy(post.getId());

    // Generate meta keywords.
    if (StringUtils.isNotEmpty(post.getMetaKeywords())) {
        model.addAttribute("meta_keywords", post.getMetaKeywords());
    } else {
        model.addAttribute("meta_keywords",
            tags.stream().map(Tag::getName).collect(Collectors.joining(",")));
    }

    // Generate meta description.
    if (StringUtils.isNotEmpty(post.getMetaDescription())) {
        model.addAttribute("meta_description", post.getMetaDescription());
    } else {
        model.addAttribute("meta_description",
            postService.generateDescription(post.getFormatContent()));
    }

    model.addAttribute("is_post", true);
    model.addAttribute("post", postService.convertToDetailVo(post));
    model.addAttribute("categories", categoryService.convertTo(categories));
    model.addAttribute("tags", tagService.convertTo(tags));
    model.addAttribute("metas", postMetaService.convertToMap(metas));

    if (themeService.templateExists(
        ThemeService.CUSTOM_POST_PREFIX + post.getTemplate() + SUFFIX_FTL)) {
        return themeService.render(ThemeService.CUSTOM_POST_PREFIX + post.getTemplate());
    }

    return themeService.render("post");
}
  1. 如果文章狀態為 "草稿" 或 "位於回收站",那麼向前端反饋無文章資訊。如果請求的 Query 中存在 token,那麼該請求為一個 admin 請求(與管理員在後臺瀏覽文章時傳送的請求是類似的,只不過在管理員介面訪問文章時 token 儲存在請求的 Header 中,這裡的 token 儲存在請求的 Query 引數中),此時檢查 token 是否有效。如果文章狀態為 "私密" 且客戶端並未獲得 "授權",那麼重定向到密碼輸入頁面,否則執行如下步驟。

  2. 對文章內容進行格式化,記錄文章被訪問的系統日誌。

  3. 在 model 中封裝文章的內容、標籤、分類、後設資料、前一篇文章、後一篇文章等資訊,然後利用 FreeMaker 基於 post.ftl 檔案(已啟用主題的)生成 HTML 頁面。

對於 "已釋出" 和 "已獲得授權" 的文章,請求處理完成後使用者可直接看到文章的內容。由於 "我的第一篇文章" 屬於私密文章且並未對使用者進行授權,因此頁面發生了重定向:

輸入密碼後,點選 "驗證",觸發 content/post/first/authentication 請求,該請求由 ContentContentController 的 password 方法處理:

@PostMapping(value = "content/{type}/{slug:.*}/authentication")
@CacheLock(traceRequest = true, expired = 2)
public String password(@PathVariable("type") String type,
    @PathVariable("slug") String slug,
    @RequestParam(value = "password") String password) throws UnsupportedEncodingException {

    String redirectUrl;
    // 如果 type 為 post
    if (EncryptTypeEnum.POST.getName().equals(type)) {
        // 授權操作
        redirectUrl = doAuthenticationPost(slug, password);
    } else if (EncryptTypeEnum.CATEGORY.getName().equals(type)) {
        redirectUrl = doAuthenticationCategory(slug, password);
    } else {
        throw new UnsupportedException("未知的加密型別");
    }
    return "redirect:" + redirectUrl;
}

因為 URL 中的 type 為 post(我們訪問的是文章),因此由 doAuthenticationPost 方法為客戶端授權:

private String doAuthenticationPost(
    String slug, String password) throws UnsupportedEncodingException {
    Post post = postService.getBy(PostStatus.INTIMATE, slug);

    post.setSlug(URLEncoder.encode(post.getSlug(), StandardCharsets.UTF_8.name()));

    authenticationService.postAuthentication(post, password);

    BasePostMinimalDTO postMinimalDTO = postService.convertToMinimal(post);

    StringBuilder redirectUrl = new StringBuilder();

    if (!optionService.isEnabledAbsolutePath()) {
        redirectUrl.append(optionService.getBlogBaseUrl());
    }

    redirectUrl.append(postMinimalDTO.getFullPath());

    return redirectUrl.toString();
}

上述程式碼中,authenticationService.postAuthentication(post, password); 是為客戶端進行授權操作的,授權完成後伺服器會將請求重定向到 /archives/first,如果授權成功那麼使用者就可以看到文章的內容,如果授權失敗那麼仍然處於 "密碼輸入" 頁面。進入到 postAuthentication 方法檢視授權的具體過程(省略部分程式碼):

public boolean postAuthentication(Post post, String password) {
    // 從 cacheStore 中查詢出當前客戶端已獲得授權的文章 id
    Set<String> accessPermissionStore = authorizationService.getAccessPermissionStore();

    // 如果文章的密碼不為空
    if (StringUtils.isNotBlank(post.getPassword())) {
        // 如果已經受過權
        if (accessPermissionStore.contains(AuthorizationService.buildPostToken(post.getId()))) {
            return true;
        }
        // 如果密碼正確就為客戶端授權
        if (post.getPassword().equals(password)) {
            authorizationService.postAuthorization(post.getId());
            return true;
        }
        return false;
    }
    // 省略部分程式碼
}
  1. 首先利用 cacheStore 查詢出當前客戶端已獲得授權的文章 id,cacheStore 是一個以 ConcurrentHashMap 為容器的內部快取,該操作指的是從快取中查詢出 key 為 "ACCESS_PERMISSION: sessionId" 的 value(一個 Set 集合),其中 sessionId 是當前 session 的 id。我們在前一篇文章中介紹過 Halo 中的 3 個過濾器,使用者端(非管理員)傳送的瀏覽文章的請求會被 ContentFilter 攔截,且每次攔截後都會執行 doAuthenticate 方法,該方法中的 request.getSession(true); 保證了服務端一定會建立一個 session。session 建立完成後儲存在服務端,預設情況下服務端會為客戶端分配一個特殊的 cookie,名稱為 "JSESSIONID",其儲存的值就是 session 的 id。之後客戶端傳送請求時,服務端可以通過請求中的 cookie 查詢出儲存的 session,並根據 session 確定客戶端的身份。因此可以使用 "ACCESS_PERMISSION: sessionId" 作為 key 來儲存當前客戶端已獲得授權的文章 id。

  2. 判斷文章的密碼是否為空,不為空就表示文章本身屬於私密文章,為空表示文章屬於設有密碼的分類。因為文章設有密碼,所以繼續執行下面的步驟。

  3. 檢視 accessPermissionStore 中(步驟 1 查詢出的 Set 集合)是否包含正在訪問的文章的 id。如果包含,那麼就表示已為當前客戶端授權過,不包含的話繼續執行下面的步驟。

  4. 判斷使用者輸入的密碼與文章的密碼是否相同,相同的話就為客戶端授權,也就是在 accessPermissionStore 中儲存當前文章的 id。

授權成功後,客戶端再次訪問該私密文章時,伺服器可以根據 cookie 得到 sessionId,然後從 cacheStore 中查詢出 key 為 "ACCESS_PERMISSION: sessionId" 的 value,判斷 value 中是否包含當前文章的 id。如果包含,那麼就表示客戶端已經獲得了文章的訪問許可權,伺服器可向前端返回文章內容,這個過程對應的是前文中 postModel.content 方法的處理邏輯。

瞭解了 Halo 中的 "文章授權" 機制後,我們就能明白為什麼伺服器在建立或更新文章時會刪除對所有客戶端的授權。因為此時文章的資訊發生了變化,密碼也可能重置,因此客戶端需要重新輸入密碼。結合前一篇文章我們可以得出結論:管理員訪問管理員介面上的功能時,伺服器根據 Request Headers 中的 token 來確定管理員的身份。普通使用者訪問私密文章時,伺服器根據 cookie 判斷使用者是否具有文章的訪問許可權,cookie 和 token 是兩種非常重要的身份認證方式。

客戶端(瀏覽器)儲存的cookie:

客戶端訪問文章時請求中攜帶 cookie:

後設資料

後設資料指的是描述資料屬性的資訊,Halo 中可為文章設定後設資料。建立或更新文章時,點選 "高階" 選項後即可新增後設資料,預設的主題 caicai_anatole 沒有提供可使用的後設資料,所以我們將更主題更換為 joe2.0(其它主題也可),為文章新增後設資料:

上圖中,我們為 "我的第一篇文章" 新增了一個後設資料,其中 meta_key 為 "enable_like",meta_value 為 "false",表示該文章不允許點贊。前文中介紹過,使用者訪問文章時,伺服器會將文章的資訊進行封裝,其中就包括文章的後設資料,封裝完成後,由 FreeMaker 基於 post.ftl 檔案生成用於瀏覽的 HTML 頁面。joe2.0 主題的 post.ftl 檔案會根據 "enable_like" 的值決定是否顯示點贊按鈕。

文章 "Hello Halo" 可以點贊:

"我的第一篇文章" 不可以點贊:

除了 "enable_like",還可以設定文章是否支援 mathjax 以及設定文章中圖片的寬度等。

自定義頁面

Halo 中除文章外,博主還可以對外分享自定義的頁面,例如部落格主頁的 "關於頁面" 就是系統在初始化部落格時為我們建立的頁面。頁面和文章的建立、檢視等操作是相似的,所以程式碼的具體執行過程就不再介紹了。頁面建立完成後,在管理員介面的依次點選 "外觀" -> "選單" -> "其他" -> "從系統預設連結新增" -> "自定義頁面" -> "新增" 即可在部落格主頁完成頁面的展示:

相關文章