Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
x1jumping committed Sep 28, 2023
1 parent 237a7ef commit 0e31924
Show file tree
Hide file tree
Showing 4 changed files with 119 additions and 12 deletions.
27 changes: 23 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,25 @@ freecdn-js能提高网站稳定性,如果其中一个cdn链接不可用则启

在`.py`文件头部可以设置是否使用代理(v2ray代理,默认开启),需要自行设置。

`generate_external_manifest_file.py`用于生成`freecdn-manifest.txt`,`.txt`储存用于加速`manifest-full.txt`的cdn链接。详见[EtherDream/freecdn](https://github.com/EtherDream/freecdn/tree/master/examples/ext-manifest)
在上传hexo博客后使用`refresh_cdn_cache.py`进行刷新。通过访问`purge.jsdelivr.net/resource`来刷新`cdn.jsdelivr.net/resource`缓存。

> P.S. cdn有缓存,如果freecdn失效请检查`freecdn-manifest.txt`或`manifest-full.txt`是否和对应原文件一致
> P.S. 官方进行了限制,需要用邮箱申请权限才能生效,比较麻烦(可以设置`generate_external_manifest_file.py`中的`is_refresh_tag`为 `True`,这样可以刷新博客的release`tag`从而达到即时更新cdn缓存

在上传hexo博客后使用`refresh_cdn_cache.py`进行刷新
`generate_external_manifest_file.py`用于生成`freecdn-manifest.txt`,`.txt`储存用于加速`manifest-full.txt`的cdn链接。需要在文件中填写`user`、`repo`等信息

> P.S. `jsd.cdn.zzko.cn`缓存时间长,而且没有刷新缓存的方法,若出现网页加载失败的情况请不要使用`refresh_cdn_cache.py`,这是因为`jsd.cdn.zzko.cn`的加载速度最快,但是加载的文件不是最新版本,因而hash对不上网页就加载失败。
`generate_external_manifest_file.py`中的`is_refresh_tag`为 `True`时能刷新博客的release`tag`从而达到即时更新cdn缓存的目的。需要填写`user`、`token`等信息。

<font color=#808080 >*注:若在没有更新repo资源的时候重复刷新tag可能会生成多个`draft` release*</font>

> Github账户中添加Token:
>1. Github任意页面中,依次点击:右上角头像 -> Settings -> Developer Settings -> Personal access tokens
>1. 点击Generate new token
>1. Notes中随便输入个名字,Select scopes中,确保repo及其子项目全部选中,然后点击Generate Token
>1. 把产生的token,一个40位的16进制字符串记住。重要:此token只显示这一次,如果没记住只能删除重建

外部`manifest`详见[EtherDream/freecdn](https://github.com/EtherDream/freecdn/tree/master/examples/ext-manifest)

> P.S. cdn有缓存,如果freecdn失效请通过访问cdn的`freecdn-manifest.txt`或`manifest-full.txt`来检验是否和在`repo`中对应原文件一致。

生成的`freecdn-manifest.txt`[示例](https://github.com/xingpingcn/picture-bed-using-freecdn/blob/main/freecdn-manifest.txt)如下

Expand All @@ -96,6 +108,7 @@ freecdn-js能提高网站稳定性,如果其中一个cdn链接不可用则启
https://cdn.jsdelivr.us/gh/xingpingcn/xingpingcn.github.io@main/manifest-full.txt
https://cdn.jsdelivr.ren/gh/xingpingcn/xingpingcn.github.io@main/manifest-full.txt
https://cdn.jsdelivr.net/gh/xingpingcn/xingpingcn.github.io@main/manifest-full.txt
https://raw.githubusercontent.com/xingpingcn/xingpingcn.github.io/main/manifest-full.txt
hash=izgWMFIdMtd29Zy7kWt3rWohTm7WQsZ9003qUATHdFo=
```

Expand All @@ -111,6 +124,12 @@ freecdn-js能提高网站稳定性,如果其中一个cdn链接不可用则启

内置了几个`类cdn.jsdelivr.net`的cdn。其中jsd.cdn.zzko.cn的GitHub地址是[这里](https://github.com/54ayao/Chinajsdelivr)

`generate_external_manifest_file.py`中的`is_refresh_tag`为 `True`时,会查询当前的branch是否有release `tag`,如果没有则创建一个新的`tag`([github API: create-a-release](https://docs.github.com/zh/rest/releases/releases?apiVersion=2022-11-28#create-a-release)),这个`tag`由当前head_commit的`sha_id`的前10位组成。如果有则删除,然后创建一个新的`tag`,freecdn-manifest.txt中的url替换成以下样式:

```
https://cdn.jsdelivr.us/gh/xingpingcn/xingpingcn.github.io@tag/manifest-full.txt
```

## 和hexo配合使用

我的博客用的hexo,因而可以使用以下命令行生成对应文件。
Expand Down
Binary file not shown.
99 changes: 92 additions & 7 deletions generate_external_manifest_file.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,91 @@
import os
import sys,base64,hashlib
from import_to_db_with_urls_txt import cdn_list
import sys,base64,hashlib,requests
from import_to_db_with_urls_txt import cdn_list,proxies_dict

'''
从freecdn-manifest.txt中生成manifest-full.txt和用于引入外部manifest的freecdn-manifest.txt
从freecdn-manifest.txt中生成manifest-full.txt和用于引入外部manifest的freecdn-manifest.txt。需要填写user、token等信息。
is_refresh_tag = True 会刷新tag,此tag用于即时更新cdn缓存(间接)。需要填写user、token(personal access token)等信息。
'''

user = ''
repo = ''
branch = ''

is_refresh_tag = True

token = ''

headers = {
"Accept" : "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"X-GitHub-Api-Version": "2022-11-28"
}

def try_func(func):
def wrapper():
try:
return func()
except Exception :
print('[error] check your network or uesr and repo')
raise
return wrapper
@try_func
def get_release_id():

r = requests.get(f'https://api.github.com/repos/{user}/{repo}/releases/latest',headers=headers,proxies=proxies_dict)
json = r.json()
if r.status_code == 200:
id = json["id"]
print(f'[info] latest release id: {id}.')
return id
else:
if json["message"] == "Not Found":
print("[warning] status_code: "+str(r.status_code))
print('[info] would get 404 status_code if there were no release. or check your network.')
return None
@try_func
def get_branch_sha():

r = requests.get(f'https://api.github.com/repos/{user}/{repo}/branches/{branch}',headers=headers,proxies=proxies_dict)
json = r.json()
return json['commit']['sha'][0:10]

# 取当前head commit的sha-id的前10位作为tag和release的名称
branch_sha = get_branch_sha()
data_of_new_release= {
"tag_name":f"{branch_sha}",
"target_commitish":f"{branch}",
"name":f"{branch_sha}",
"body":"update blog",
"draft": False
}
def post_new_release():
release_id = get_release_id()
if not release_id == None:
#delete release
r1 = requests.delete(f'https://api.github.com/repos/{user}/{repo}/releases/{release_id}',headers=headers,proxies=proxies_dict)
if r1.status_code == 204 :
print('[success] old release deleted.')
else:
print('[error] '+r1.content)
r2 = requests.delete(f'https://api.github.com/repos/{user}/{repo}/git/refs/tags/{branch_sha}',headers=headers,proxies=proxies_dict)
if r1.status_code == 204 :
print('[success] old tag deleted.')
else:
print('[error] '+r2.content)
#create a new one
r = requests.post(f'https://api.github.com/repos/{user}/{repo}/releases',headers=headers,json=data_of_new_release,proxies=proxies_dict)
if r.status_code == 201:
print('[success] new release created.')
elif r.status_code == 404:
print('[error] Not Found if the discussion category name is invalid.')
print(r.json())
elif r.status_code == 422:
print('[error] Validation failed, or the endpoint has been spammed.')
print(r.json())
else:
print('[error] status_code: '+str(r.status_code)+'. when post a new release.')
def CalcFileSha256_with_base64(filname):
''' calculate file sha256 '''
with open(filname, "rb") as f:
Expand All @@ -19,13 +100,17 @@ def main():
hash256 = CalcFileSha256_with_base64(
os.path.join('./public', 'manifest-full.txt'))
f.write('@include\n\t/manifest-full.txt\n@global\n\topen_timeout=0\n/manifest-full.txt')
if is_refresh_tag:
post_new_release()
for cdn in cdn_list:
if not cdn == 'https://raw.githubusercontent.com/':
f.write(f'\n\t{cdn}xingpingcn/xingpingcn.github.io@main/manifest-full.txt')
if is_refresh_tag:
f.write(f'\n\t{cdn}{user}/{repo}@{branch_sha}/manifest-full.txt')
else:
f.write(f'\n\t{cdn}{user}/{repo}@{branch}/manifest-full.txt')
else:
f.write(f'\n\t{cdn}xingpingcn/xingpingcn.github.io/main/manifest-full.txt')
# f.write(f'''@include\n\t/manifest-full.txt\n@global\n\topen_timeout=0\n/manifest-full.txt\n\thttps://jsd.cdn.zzko.cn/gh/xingpingcn/xingpingcn.github.io@main/manifest-full.txt\n\thttps://cdn.jsdelivr.us/gh/xingpingcn/xingpingcn.github.io@main/manifest-full.txt\n\thttps://cdn.jsdelivr.ren/gh/xingpingcn/xingpingcn.github.io@main/manifest-full.txt\n\thttps://cdn.jsdelivr.net/gh/xingpingcn/xingpingcn.github.io@main/manifest-full.txt\n\thash={hash256}''')
f.write(f'\n\t{cdn}{user}/{repo}/{branch}/manifest-full.txt')
f.write(f'\n\thash={hash256}')
print('manifest_file generaeted.')
print('[success] manifest_file generaeted.')
if __name__ == '__main__':
main()
5 changes: 4 additions & 1 deletion import_to_db_with_urls_txt.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@
os.chdir(sys.path[0]) # os.chdir(sys.path[0])把当前py文件所在路径设置为当前运行路径.

is_use_proxy = True
proxies_dict = {'http': 'socks5://127.0.0.1:10808',
if is_use_proxy:
proxies_dict = {'http': 'socks5://127.0.0.1:10808',
'https': 'socks5://127.0.0.1:10808'}
else:
proxies_dict ={}
dir_for_custom_conf = 'dir_for_custom_conf' # 储存文件的文件夹名称
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
Expand Down

0 comments on commit 0e31924

Please sign in to comment.