feat: change the commenter avatar link. (#53)

* feat: add new comment user merge service.

* feat: better hide the commenter email.
This commit is contained in:
Yufan Sheng 2024-06-23 23:01:02 +08:00
parent 992d8f857e
commit c37ce2b820
Signed by: syhily
GPG Key ID: 9D18A22A7DCD5A9B
22 changed files with 728 additions and 143 deletions

3
.gitignore vendored
View File

@ -27,3 +27,6 @@ pnpm-debug.log*
# Hide the SQL session
*.session.sql
# Blog Tools
./tools

View File

@ -5,3 +5,4 @@ public/images
# The MDX files
*.mdx
*.md

View File

@ -106,6 +106,7 @@
"recma",
"redmi",
"regclass",
"rivo",
"sauvignon",
"sheng",
"shiki",
@ -120,6 +121,7 @@
"timestamptz",
"toolsmp",
"tsconfigs",
"tview",
"ultrahtml",
"unpic",
"unsharp",

View File

@ -58,7 +58,7 @@ The default username is `your system username`, with no password.
Create and initialize the database and user with these commands:
```sql
```postgresql
-- Create a database.
CREATE DATABASE <db>;
@ -76,23 +76,25 @@ GRANT ALL PRIVILEGES ON DATABASE <db> TO <db_user>;
GRANT ALL ON SCHEMA public TO <db_user>;
```
Most tables are created by the Artalk. [Execute the Artalk](https://artalk.js.org/guide/deploy.html) to create the tables.
Most tables are created by the Artalk. [Execute the Artalk](https://artalk.js.org/guide/deploy.html) to create the
tables.
The like table should be created manually. Execute the SQL below.
```sql
```postgresql
-- Sequence and defined type
CREATE SEQUENCE IF NOT EXISTS atk_likes_id_seq;
-- Table Definition
CREATE TABLE "public"."atk_likes" (
"id" int8 NOT NULL DEFAULT nextval('atk_likes_id_seq'::regclass),
"created_at" timestamptz,
"updated_at" timestamptz,
"deleted_at" timestamptz,
"token" varchar(255),
"page_key" varchar(255),
PRIMARY KEY ("id")
CREATE TABLE "public"."atk_likes"
(
"id" int8 NOT NULL DEFAULT nextval('atk_likes_id_seq'::regclass),
"created_at" timestamptz,
"updated_at" timestamptz,
"deleted_at" timestamptz,
"token" varchar(255),
"page_key" varchar(255),
PRIMARY KEY ("id")
);
-- Create table index
@ -101,8 +103,9 @@ CREATE INDEX IF NOT EXISTS "idx_atk_likes_token" ON "public"."atk_likes" ("token
### Comments Integration
This weblog use artalk as its backend comment service. But since artalk didn't provide the latest comments API.
We decide to query it directly from Postgres database. So the comments and fav clicks are living in the same database.
This weblog uses artalk as its backend comment service. But since artalk didn't provide the latest comments API.
We decide to query it directly from the Postgres database. So the comments and fav clicks are living in the same
database.
## Writing
@ -125,7 +128,7 @@ date: 2013/7/13 20:46:25
### Post Front Matter Settings
| Setting | Description | Required | Default |
| ----------- | ------------------------------------ | -------- | -------------------- |
|-------------|--------------------------------------|----------|----------------------|
| `id` | ID (unique), used as the permalink | true | Filename |
| `title` | Title | true | Filename |
| `date` | Published date | true | |
@ -140,7 +143,7 @@ date: 2013/7/13 20:46:25
### Pages Front Matter Settings
| Setting | Description | Required | Default |
| ----------- | ------------------------------------ | -------- | -------------- |
|-------------|--------------------------------------|----------|----------------|
| `id` | ID (unique), used as the permalink | true | Filename |
| `title` | Title | true | Filename |
| `date` | Published date | true | |
@ -168,25 +171,27 @@ to get it worked everywhere.
This weblog is deployed on the [zeabur](https://zeabur.com) platform.
You can check their documents and get your own weblog to be published without any budget at first.
Or you can host on your own machine. Use [Dockerfile](./Dockerfile) to build a image and run it locally.
Or you can host on your own machine. Use [Dockerfile](./Dockerfile) to build an image and run it locally.
The comment system is leverage the [Artalk](https://artalk.js.org), a self-hosted comment system.
You should host it on your own machine.
But it can be modified and changed to any other comment solutions.
For instance, the [giscus](https://giscus.app) is an opinionated choice.
## TODO Checklist
- [ ] Check article grammar errors by using ChatGPT. Remain **54** posts.
- [ ] Add music to the articles. Remain **54** posts.
- [ ] External the article inner links with different target.
- [ ] External article inner links with different targets.
- [ ] Slide share components integration.
### Long Term Goals
### Comments TODO Checklist
- [ ] Support modification after commenting in 60 minutes even if you have refreshed the page.
- [ ] Use self-developed duoshuo as the comment's solution.
### Long-Term Goals
- [ ] Add han.js support for better typography.
- [ ] Drop bootstrap, in favor of tailwind css.
- [ ] Use self developed duoshuo as the comments solution.
## License
@ -194,7 +199,7 @@ The source code of this blog is licensed under the [MIT](LICENSE) license,
feel to free to use it without any legal risks.
The [content](src/content) of this blog's posts is licensed under the
[CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) license.
[CC BY-NC-SA 4.0](src/content/LICENSE) license.
### Logo Fonts License
@ -204,23 +209,16 @@ and [Iroha Mochi](https://modi.jpn.org/font_iroha-mochi.php) with [license](lice
They are the fonts that can be used in business without any charge.
### Article Font License
The [OPPOSans 3.0](https://www.coloros.com/article/A00000050) is used for reading in my weblog.
It can be used in business scenarios without any modification.
I just placed it under the [opposans](src/assets/styles/opposans/) directory for better integration.
The license file is [here](licenses/LICENSE.oppo-sans.txt)
### Open Graph Font License
The [Noto Sans Simplified Chinese](https://fonts.google.com/noto/specimen/Noto+Sans+SC)
is used for rendering the open graph image in my weblog.
It can be used in business scenarios without any modification.
The license file is [here](LICENSE.noto-sans-sc.txt)
The license file is [here](licenses/LICENSE.noto-sans-sc.txt)
### Third Party Codes License
Some codes in this project is copied from other project. I have add the comments in the files's header.
Some codes in this project are copied from other projects. I have added the comments in the files' header.
The source codes used from third party projects are:

View File

@ -64,9 +64,6 @@ export default defineConfig({
vite: {
// Add this for avoiding the needless import optimize in Vite.
optimizeDeps: { exclude: ['@napi-rs/canvas'] },
esbuild: {
drop: ['console', 'debugger'],
},
},
build: {
assets: 'cats',

View File

@ -1,6 +0,0 @@
* OPPO Sans含中文及西文3 款字重)允许个人或企业免费使用,含商业用途,版权归 OPPO 广东移动通信有限公司所有。
您应遵守以下条款,违者将会被追究法律责任:
1. 不对字体进行改编或二次开发;
2. 不对外售卖字体;
3. 不向他方提供其他下载渠道;
4. 不用于违法用途。

View File

@ -65,6 +65,11 @@ const Options = z
comments: z.object({
server: z.string().url().readonly(),
admins: z.array(z.number()),
size: z.number().default(10).readonly(),
avatar: z.object({
mirror: z.string().url().readonly(),
size: z.number(),
}),
}),
}),
thumbnail: z
@ -175,6 +180,11 @@ const options: z.input<typeof Options> = {
comments: {
server: 'https://comment.yufan.me',
admins: [3],
size: 10,
avatar: {
mirror: 'https://weavatar.com/avatar',
size: 80,
},
},
},
thumbnail: ({ src, width, height }) => {

View File

@ -1,13 +1,12 @@
import Comment from '@/components/comment/Comment.astro';
import CommentItem from '@/components/comment/CommentItem.astro';
import { commentConfig, createComment, loadComments } from '@/components/comment/artalk';
import { createComment, loadComments } from '@/components/comment/artalk';
import { partialRender } from '@/helpers/container';
import { decreaseLikes, increaseLikes, queryLikes } from '@/helpers/db/query';
import { decreaseLikes, increaseLikes, queryLikes, queryUserId } from '@/helpers/db/query';
import { pages, posts } from '@/helpers/schema';
import { urlJoin } from '@/helpers/tools';
import { encodedEmail, urlJoin } from '@/helpers/tools';
import { z } from 'astro/zod';
import { ActionError, defineAction } from 'astro:actions';
import crypto from 'node:crypto';
const keys = [...posts.map((post) => post.permalink), ...pages.map((page) => page.permalink)];
const CommentConnectError = new ActionError({
@ -48,13 +47,9 @@ export const server = {
accept: 'json',
input: z.object({ email: z.string().email() }),
handler: async ({ email }) => {
const config = await commentConfig();
if (config === null) {
throw CommentConnectError;
}
const hash = crypto.createHash('md5').update(email.trim().toLowerCase()).digest('hex');
return { avatar: urlJoin(config.frontend_conf.gravatar.mirror, `${hash}?d=mm&s=80`) };
const id = await queryUserId(email);
const hash = id === null ? encodedEmail(email) : `${id}`;
return { avatar: urlJoin(import.meta.env.SITE, 'avatar', `${hash}.png`) };
},
}),
comment: defineAction({
@ -76,9 +71,8 @@ export const server = {
});
}
const config = await commentConfig();
const content = await partialRender(CommentItem, {
props: { depth: resp.rid === 0 ? 1 : 2, comment: resp, pending: resp.is_pending, config: config },
props: { depth: resp.rid === 0 ? 1 : 2, comment: resp, pending: resp.is_pending },
});
return { content };
@ -91,17 +85,12 @@ export const server = {
offset: z.number(),
}),
handler: async ({ page_key, offset }) => {
const config = await commentConfig();
if (config === null) {
throw CommentConnectError;
}
const comments = await loadComments(page_key, null, Number(offset), config);
const comments = await loadComments(page_key, null, Number(offset));
if (comments === null) {
throw CommentConnectError;
}
const content = await partialRender(Comment, { props: { comments: comments, config: config } });
const content = await partialRender(Comment, { props: { comments: comments } });
return { content };
},

View File

@ -4,15 +4,14 @@
*/
import CommentItem from '@/components/comment/CommentItem.astro';
import { parseComments } from '@/components/comment/artalk';
import type { CommentConfig, Comments } from '@/components/comment/types';
import type { Comments } from '@/components/comment/types';
interface Props {
comments: Comments;
config: CommentConfig;
}
const { comments, config } = Astro.props;
const { comments } = Astro.props;
const parsedComments = await parseComments(comments.comments);
---
{parsedComments.map((item) => <CommentItem comment={item} config={config} depth={1} />)}
{parsedComments.map((item) => <CommentItem comment={item} depth={1} />)}

View File

@ -1,16 +1,15 @@
---
import type { CommentConfig, CommentItem } from '@/components/comment/types';
import type { CommentItem } from '@/components/comment/types';
import { formatLocalDate } from '@/helpers/formatter';
import { urlJoin } from '@/helpers/tools';
interface Props {
depth: number;
comment: CommentItem;
config: CommentConfig;
pending?: false;
}
const { comment, config, depth, pending } = Astro.props;
const { comment, depth, pending } = Astro.props;
---
<li id={`atk-comment-${comment.id}`} class="comment odd alt thread-odd thread-alt" data-depth={depth}>
@ -18,7 +17,7 @@ const { comment, config, depth, pending } = Astro.props;
<div class="comment-avatar flex-avatar">
<img
alt={comment.nick}
src={urlJoin(config.frontend_conf.gravatar.mirror, `${comment.email_encrypted}?s=80&d=mm&r=g`)}
src={urlJoin(import.meta.env.SITE, 'avatar', `${comment.user_id}.png`)}
class="avatar avatar-40 photo"
height="40"
width="40"
@ -52,7 +51,7 @@ const { comment, config, depth, pending } = Astro.props;
comment.children && depth === 1 && (
<ul class="children">
{comment.children.map((childComment) => (
<Astro.self comment={childComment} config={config} depth={depth + 1} />
<Astro.self comment={childComment} depth={depth + 1} />
))}
</ul>
)
@ -62,7 +61,7 @@ const { comment, config, depth, pending } = Astro.props;
comment.children && depth !== 1 && (
<>
{comment.children.map((childComment) => (
<Astro.self comment={childComment} config={config} depth={depth + 1} />
<Astro.self comment={childComment} depth={depth + 1} />
))}
</>
)

View File

@ -1,5 +1,5 @@
---
import { commentConfig, loadComments } from '@/components/comment/artalk';
import { loadComments } from '@/components/comment/artalk';
import Comment from '@/components/comment/Comment.astro';
import { urlJoin } from '@/helpers/tools';
import options from '@/options';
@ -11,13 +11,12 @@ interface Props {
}
const { commentKey, title } = Astro.props;
const config = await commentConfig();
const comments = config != null ? await loadComments(commentKey, title, 0, config) : null;
const comments = await loadComments(commentKey, title, 0);
---
<div id="comments" class="comments py-5">
{
comments != null && config != null ? (
comments != null ? (
<>
<div class="h5 mb-4 comment-total-count">
评论 <small class="font-theme text-sm">({comments.count})</small>
@ -60,15 +59,15 @@ const comments = config != null ? await loadComments(commentKey, title, 0, confi
</form>
</div>
<ul class="comment-list">
<Comment comments={comments} config={config} />
<Comment comments={comments} />
</ul>
{comments.roots_count > config.frontend_conf.pagination.pageSize && (
{comments.roots_count > options.settings.comments.size && (
<div class="text-center mt-3 mt-md-4">
<button
id="comments-next-button"
data-key={commentKey}
data-size={config.frontend_conf.pagination.pageSize}
data-offset={config.frontend_conf.pagination.pageSize}
data-size={options.settings.comments.size}
data-offset={options.settings.comments.size}
class="btn btn-light"
>
加载更多

View File

@ -1,12 +1,4 @@
import type {
Comment,
CommentConfig,
CommentItem,
CommentReq,
CommentResp,
Comments,
ErrorResp,
} from '@/components/comment/types';
import type { Comment, CommentItem, CommentReq, CommentResp, Comments, ErrorResp } from '@/components/comment/types';
import { increaseViews } from '@/helpers/db/query';
import { urlJoin } from '@/helpers/tools';
import options from '@/options';
@ -20,24 +12,9 @@ import sanitize from 'ultrahtml/transformers/sanitize';
// Access the artalk in internal docker host when it was deployed on zeabur.
const server = options.isProd() ? `http://${ARTALK_HOST}:23366` : options.settings.comments.server;
export const commentConfig = async (): Promise<CommentConfig | null> => {
const data = await fetch(urlJoin(server, '/api/v2/conf'))
.then((response) => response.json())
.catch((e) => {
console.log(e);
return null;
});
return data != null ? (data as CommentConfig) : data;
};
export const loadComments = async (
key: string,
title: string | null,
offset: number,
config: CommentConfig,
): Promise<Comments | null> => {
export const loadComments = async (key: string, title: string | null, offset: number): Promise<Comments | null> => {
let params: Record<string, string | number | boolean> = {
limit: config.frontend_conf.pagination.pageSize,
limit: options.settings.comments.size,
offset: offset,
flat_mode: false,
page_key: key,

View File

@ -1,23 +1,9 @@
// The configuration in artalk.
export interface CommentConfig {
frontend_conf: {
flatMode: boolean;
gravatar: {
mirror: string;
params: string;
};
pagination: {
pageSize: number;
};
};
}
// The single comment.
export interface Comment {
id: number;
content: string;
nick: string;
email_encrypted: string;
user_id: number;
link: string;
date: string;
rid: number;

438
src/content/LICENSE Normal file
View File

@ -0,0 +1,438 @@
Attribution-NonCommercial-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International Public License
("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
l. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

View File

@ -11,6 +11,38 @@ export interface Comment {
permalink: string;
}
export const queryEmail = async (id: number): Promise<string | null> => {
const results = await db
.select({
email: atk_users.email,
})
.from(atk_users)
.where(eq(atk_users.id, sql`${id}`))
.limit(1);
if (results.length === 0) {
return null;
}
return results[0].email;
};
export const queryUserId = async (email: string): Promise<bigint | null> => {
const results = await db
.select({
id: atk_users.id,
})
.from(atk_users)
.where(eq(atk_users.email, sql`${email}`))
.limit(1);
if (results.length === 0) {
return null;
}
return results[0].id;
};
export const latestComments = async (): Promise<Comment[]> => {
const results = await db
.select({

View File

@ -1,3 +1,5 @@
import crypto from 'node:crypto';
export const makeToken = (
length: number,
characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
@ -17,3 +19,6 @@ export const urlJoin = (base: string, ...paths: string[]): string => {
.reduce((left, right) => left + (left.endsWith('/') || right.startsWith('/') ? '' : '/') + right)
.replace(/([^:]\/)\/+/g, '$1');
};
export const encodedEmail = (email: string): string =>
crypto.createHash('md5').update(email.trim().toLowerCase()).digest('hex');

View File

@ -0,0 +1,41 @@
import { queryEmail } from '@/helpers/db/query';
import { encodedEmail, urlJoin } from '@/helpers/tools';
import options from '@/options';
import type { APIRoute } from 'astro';
const defaultAvatar = (): string => {
return urlJoin(options.assetsPrefix(), '/images/default-avatar.png');
};
function isNumeric(str: string) {
return !Number.isNaN(str) && !Number.isNaN(Number.parseFloat(str));
}
const avatarImage = async (hash: string): Promise<Response> => {
const link = urlJoin(
options.settings.comments.avatar.mirror,
`${hash}.png?s=${options.settings.comments.avatar.size}&d=${defaultAvatar()}`,
);
console.log(link);
return new Response(Buffer.from(await (await fetch(link)).arrayBuffer()), {
headers: { 'Content-Type': 'image/png' },
});
};
export const GET: APIRoute = async ({ params, redirect }) => {
const { hash } = params;
if (!hash) {
return redirect(defaultAvatar());
}
// This is a existed user.
if (isNumeric(hash)) {
const email = await queryEmail(Number(hash));
if (email === null) {
return redirect(defaultAvatar());
}
return avatarImage(encodedEmail(email));
}
return avatarImage(hash);
};

View File

@ -4,18 +4,5 @@ This is a directory for serving the useful tools for my weblog writing.
## Tools list
Image process with resize, compress and convert to JPG.
```
tools image -h
A tool for processing images to my desired format, size and naming
Usage:
tools image [flags]
Flags:
-h, --help help for image
--output string The output path
--source string The image file path (absolute of relative) that you want to process
--width int The compressed width for the given image (default 1280)
```
1. Image process with resize, compress and convert to JPG.
2. Artalk user merge tool. Deduplicate the users with the same Email.

121
tools/cmd/artalk.go Normal file
View File

@ -0,0 +1,121 @@
package cmd
import (
"fmt"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/spf13/cobra"
"log"
"time"
)
var (
artalkCmd = &cobra.Command{
Use: "artalk",
Short: "A tool for merging the duplicated users",
Run: func(cmd *cobra.Command, args []string) {
mergeUsers()
},
}
host = ""
port = 0
database = ""
username = ""
password = ""
)
func init() {
artalkCmd.Flags().StringVarP(&host, "host", "", "", "The database host")
artalkCmd.Flags().IntVarP(&port, "port", "", 0, "The database port")
artalkCmd.Flags().StringVarP(&database, "database", "", "", "The database name")
artalkCmd.Flags().StringVarP(&username, "username", "", "", "The database username")
artalkCmd.Flags().StringVarP(&password, "password", "", "", "The database password")
_ = artalkCmd.MarkFlagRequired("host")
_ = artalkCmd.MarkFlagRequired("port")
_ = artalkCmd.MarkFlagRequired("database")
_ = artalkCmd.MarkFlagRequired("username")
_ = artalkCmd.MarkFlagRequired("password")
rootCmd.AddCommand(artalkCmd)
}
type UserStatistic struct {
Email string `db:"email"`
Counts int32 `db:"counts"`
}
type User struct {
ID int64 `db:"id"`
Email string `db:"email"`
Name string `db:"name"`
Link string `db:"link"`
UpdatedAt time.Time `db:"updated_at"`
}
func mergeUsers() {
log.Println("Try to connect to the database.")
connStr := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", username, password, host, port, database)
db, err := sqlx.Connect("postgres", connStr)
if err != nil {
log.Fatal(err)
}
if err = db.Ping(); err != nil {
log.Fatal(err)
}
log.Println("Try to query the duplicated users.")
var duplicatedUsers []UserStatistic
err = db.Select(&duplicatedUsers, "SELECT email, count(email) AS counts FROM atk_users GROUP BY email HAVING count(email) > 1 ORDER BY count(email) DESC;")
if err != nil {
log.Fatal(err)
}
if duplicatedUsers != nil && len(duplicatedUsers) > 0 {
log.Printf("Find %d duplicated users.", len(duplicatedUsers))
} else {
log.Println("No duplicated users find, exit.")
}
for _, user := range duplicatedUsers {
deleteDuplicateUsers(db, user)
}
}
func deleteDuplicateUsers(db *sqlx.DB, user UserStatistic) {
var users []User
err := db.Select(&users, "SELECT id, email, name, link, updated_at FROM atk_users WHERE email = $1", user.Email)
if err != nil {
log.Fatal(err)
}
if len(users) <= 1 {
fmt.Println("No duplicated users find.")
return
}
fmt.Println("Start to remove duplicated user", user.Email)
for i, u := range users {
fmt.Println("Index", i)
fmt.Printf("name: %s link: %s update: %s\n\n", u.Name, u.Link, u.UpdatedAt)
}
fmt.Println("Input the index to choose the user to keep, other users will be merged into the selected user.")
var index = -1
_, _ = fmt.Scanln(&index)
for index < 0 || index >= len(users) {
fmt.Printf("Invalid index number. It should in range [0, %d)\n", len(users))
_, _ = fmt.Scanln(&index)
}
keptID := users[index].ID
for i, u := range users {
if i == index {
continue
}
// Delete the user.
db.MustExec("UPDATE atk_comments SET user_id = $1 WHERE user_id = $2", keptID, u.ID)
db.MustExec("DELETE FROM atk_users WHERE id = $1", u.ID)
}
}

View File

@ -28,10 +28,10 @@ var (
},
}
width = 1280
source = ""
output = executablePath()
localDate = time.Now().Format("20060102")
width = 1280
source = ""
output = executablePath()
localDate = time.Now().Format("20060102")
localDatePattern = regexp.MustCompile("^\\d{8}$")
)

View File

@ -4,6 +4,8 @@ go 1.22
require (
github.com/disintegration/imaging v1.6.2
github.com/jmoiron/sqlx v1.4.0
github.com/lib/pq v1.10.9
github.com/spf13/cobra v1.8.1
)

View File

@ -1,19 +1,24 @@
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.16.0 h1:9kloLAKhUufZhA12l5fwnx2NZW39/we1UhBesW433jw=
golang.org/x/image v0.16.0/go.mod h1:ugSZItdV4nOxyqp56HmXwH0Ry0nBCpjnZdpDaIHdoPs=
golang.org/x/image v0.17.0 h1:nTRVVdajgB8zCMZVsViyzhnMKPwYeroEERRC64JuLco=
golang.org/x/image v0.17.0/go.mod h1:4yyo5vMFQjVjUcVk4jEQcU9MGy/rulF5WvUILseCM2E=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=