安卓使用termux接收cubox文件并保存到指定obsidian库

请看b站演示视频。

步骤:

  1. 下载安装应用termux和termux-api,推荐从F-Droid下载
  2. 需要允许termux的存储权限,运行命令
termux-setup-storage

允许后termux的home目录下会出现storage文件夹,可以通过ls storage查看,手机的对应的目录在storage/shared

  1. 安装termux-api
pkg install termux-api

还要允许termux-api的后台弹出界面权限

  1. 安装python
pkg install python3
  1. 安装requests库
pip install requests
  1. 配置脚本内容,可以修改的地方通过注释1-6标识,包括文件保存路径,图片保存路径,是否下载图片到本地,标签列表等

  1. 下载脚本到手机,然后拷贝到bin目录,命名为termux-file-editor,并赋予执行权限
mkdir bin
cp storage/shared/Document/cubox-termux-obsidian.py bin/termux-file-editor
chmod +x bin/termux-file-editor

其中storage/shared/Document/cubox-termux-obsidian.py需要改为自己脚本的位置。

  1. 也可以使用wget直接从github下载
pkg install wget
mkdir bin
wget  https://gist.githubusercontent.com/chenghongyao/3bc9ca3440304b6e3214ca271febda96/raw/d42f9a5f788aea0faa7a3ebf43260c426d43b8c9/cubox-termux-obsidian.py -O bin/termux-file-editor
chmod +x bin/termux-file-editor

或者使用镜像地址https://gh.api.99988866.xyz/https://gist.githubusercontent.com/chenghongyao/3bc9ca3440304b6e3214ca271febda96/raw/d42f9a5f788aea0faa7a3ebf43260c426d43b8c9/cubox-termux-obsidian.py不保证可用

完成,到cubox导出个文件试一下~~

8 个赞

黑科技 解锁新技能!

有点酷,但脚本,就算登录也会提示无访问权限

是的,突然发现gitee的代码片端只支持私有,还是用github的吧。

#!/bin/python

import os
import json
import sys
import time
import re
import requests


stamp = time.strftime("%Y%m%d%H%M%S")
title = "文件处理"
options = {}


# 1. 文件保存路径
ob_dst = "/data/data/com.termux/files/home/storage/shared/Documents/obnote/K 快收/"
# 2. 是否下载图片到本地, True/False
download_img = True
# 3. 图片下载路径
ob_img_dst = ob_dst + "assets/"

# 4. 可选标签
tags = ['技术','社评','信息', '生活','知识','其他']
# 5. 文件来源(只支持cubox导出的markdown)
host_map = {
        "www.zhihu.com":"知乎",
        "mp.weixin.qq.com":"微信"
        }
        
# 6. 自定义yaml
def get_meta(fro, md):

    created = time.strftime("%Y-%m-%d")
    ts = show_checkbox_dialog("选择标签",tags) # 标签
    
    meta = {
            "created": created,
            "uid": stamp,
            }
    if fro:
        meta["from"] = fro

    if ts:
        meta["tags"] = ','.join(ts)

    return meta

# 注册文件处理函数
def register(name):
    def _d(fun):
        options[name] = fun
    return _d

# 显示radio选择框
def show_radio_dialog(title,options):
    cmd = f'termux-dialog radio -t "{title}" -v "{",".join(options)}"'
    s = os.popen(cmd).read()
    res = json.loads(s)
    if res['code'] != -1 or res.get('index',None) is None:
        return
    return res['text']

def show_checkbox_dialog(title,options):
    cmd = f'termux-dialog checkbox -t "{title}" -v "{",".join(options)}"'
    s = os.popen(cmd).read()
    res = json.loads(s)
    if res['code'] != -1 or res.get('text','[]') == '[]':
        return
    return [x['text'] for x in res['values']]


# markdown简单预处理
def md_pre_common(md):
    md = re.sub(r"\n{3,}","\n\n",md)
    md = re.sub(r"\n-\n\n","\n",md)
    return md

@register("ob快收")
def move_to_obsidian(src):
    print(src)

    # 打开文件
    with open(src,'r',encoding='utf8') as f:
        md = f.read()
    
    # 提取第一行的一级标题作为文件名
    first_line = md.split("\n")[0] 
    if first_line.startswith("# "):
        filename = first_line[2:]+".md"
    else:
        filename = os.path.basename(src)

    # 删除非法路径字符
    filename = re.sub(r'[\||/|\|:|*|?]','',filename)
    
    # 从最后一行提取文件来源(cubox)
    fro = None 
    last_line = md.split("\n")[-1] 
    res = re.search(r"\[查看原网页: (.*)\]",last_line)
    if res:
        fro = res.group(1)
        fro = host_map.get(fro,fro)
    
    # 文件预处理
    md = md_pre_common(md)


    # 生成yaml数据
    meta = get_meta(fro,md)

    meta_str  = "---\n" + "\n".join([f"{k}: {v}" for k,v in meta.items()]) + "\n---\n"


    # markdown 插入yaml
    md = meta_str + md

    # 下载图片
    if download_img:
        links = re.findall(r"(!\[(.*)\]\((.*)\))",md)
        link_count = len(links)

        if link_count > 0:
            if not os.path.exists(ob_img_dst):
                os.makedirs(ob_img_dst)

            # TODO: 多线程下载
            for i,item in enumerate(links):
                print("%d/%d:"%(i+1,link_count),end="")
                raw, title,href = item
                res = requests.get(href)
                content = res.content
                content_type = res.headers['Content-Type']
                if content_type.startswith("image/"):
                    ext = content_type[6:]
                    name = "%s%03d.%s"%(stamp,i,ext)
                    print(name)
                    with open(ob_img_dst + name,'wb') as f:
                        f.write(content)
                    md = md.replace(raw,f'![[{name}]]')

    # 保存文件
    with open(ob_dst+filename,'w') as f:
        f.write(md)

    # 删除源文件
    os.remove(src)



def main():

    if len(sys.argv) < 2:
        print("need file path")
        return

    keys = list(options.keys())
    if len(keys) > 1:
        res = show_radio_dialog(title,keys)
        if res is None:
            return
        fun = options[res]
    else:
        fun = options[keys[0]]

    fun(sys.argv[1])

main()

1 个赞

请问这是怎么回事呢?

/data/data/com.termux/files/usr/bin/sh: 1: termux-dialog: not found
Traceback (most recent call last):
File “/data/data/com.termux/files/home/bin/termux-file-editor”, line 168, in
main()
File “/data/data/com.termux/files/home/bin/termux-file-editor”, line 166, in main
fun(sys.argv[1])
File “/data/data/com.termux/files/home/bin/termux-file-editor”, line 110, in move_to_obsidian
meta = get_meta(fro,md)
File “/data/data/com.termux/files/home/bin/termux-file-editor”, line 35, in get_meta
ts = show_checkbox_dialog(“选择标签”,tags) # 标签
File “/data/data/com.termux/files/home/bin/termux-file-editor”, line 67, in show_checkbox_dialog
res = json.loads(s)
File “/data/data/com.termux/files/usr/lib/python3.10/json/init.py”, line 346, in loads
return _default_decoder.decode(s)
File “/data/data/com.termux/files/usr/lib/python3.10/json/decoder.py”, line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File “/data/data/com.termux/files/usr/lib/python3.10/json/decoder.py”, line 355, in raw_decode
raise JSONDecodeError(“Expecting value”, s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

[Process completed (code 1) - press Enter]

你安装了termux:api吗,我忘了这一步了。

已经更新了下教程,你再试一下

啊,我刚才看一遍报错信息说是找不到文件夹。原来是保存路径不对,我以为脚本里的路径会自动创建呢,现在换了新建的仓库路径就好了。
让你见笑了哈哈:joy: