repo_id
stringlengths 6
101
| size
int64 367
5.14M
| file_path
stringlengths 2
269
| content
stringlengths 367
5.14M
|
|---|---|---|---|
281677160/openwrt-package
| 26,267
|
luci-app-amlogic/root/usr/sbin/openwrt-update-rockchip
|
#!/bin/bash
#======================================================================================
# Function: Update openwrt to emmc for Rockchip STB
# Copyright (C) 2020-- https://github.com/unifreq/openwrt_packit
# Copyright (C) 2021-- https://github.com/ophub/luci-app-amlogic
#======================================================================================
#
# The script supports directly setting parameters for update, skipping interactive selection
# openwrt-update-rockchip ${OPENWRT_FILE} ${AUTO_MAINLINE_UBOOT} ${RESTORE_CONFIG}
# E.g: openwrt-update-rockchip openwrt_s905d.img.gz yes restore
# E.g: openwrt-update-rockchip openwrt_s905d.img.gz no no-restore
# You can also execute the script directly, and interactively select related functions
# E.g: openwrt-update-rockchip
#
#======================================================================================
# Encountered a serious error, abort the script execution
error_msg() {
echo -e "[ERROR] ${1}"
exit 1
}
# Get the partition name of the root file system
get_root_partition_name() {
local paths=("/" "/overlay" "/rom")
local partition_name
for path in "${paths[@]}"; do
partition_name=$(df "${path}" | awk 'NR==2 {print $1}' | awk -F '/' '{print $3}')
[[ -n "${partition_name}" ]] && break
done
[[ -z "${partition_name}" ]] && error_msg "Cannot find the root partition!"
echo "${partition_name}"
}
# Get the partition message of the root file system
get_root_partition_msg() {
local paths=("/" "/overlay" "/rom")
local partition_name
for path in "${paths[@]}"; do
partition_msg=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | awk '$3~/^part$/ && $5 ~ "^" "'"${path}"'" "$" {print $0}')
[[ -n "${partition_msg}" ]] && break
done
[[ -z "${partition_msg}" ]] && error_msg "Cannot find the root partition message!"
echo "${partition_msg}"
}
# Receive one-key command related parameters
IMG_NAME="${1}"
AUTO_MAINLINE_UBOOT="${2}"
BACKUP_RESTORE_CONFIG="${3}"
# Current device model
if [ -f /boot/armbianEnv.txt ]; then
source /boot/armbianEnv.txt 2>/dev/null
CURRENT_FDTFILE=$(basename ${fdtfile})
fi
MYDEVICE_NAME=$(cat /proc/device-tree/model | tr -d '\000')
case $MYDEVICE_NAME in
"")
error_msg "The device name is empty and cannot be recognized."
;;
"Chainedbox L1 Pro")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3328-l1pro-1296mhz.dtb"
fi
SOC="l1pro"
;;
"BeikeYun")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3328-beikeyun-1296mhz.dtb"
fi
SOC="beikeyun"
;;
"ZCuble1 Max")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3399-zcube1-max.dtb"
fi
SOC="zcube1 max"
;;
"JP TVbox 3566")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3566-jp-tvbox.dtb"
fi
SOC="jp-tvbox"
;;
"Radxa CM3 RPI CM4 IO")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3566-radxa-cm3-rpi-cm4-io.dtb"
fi
SOC="radxa-cm3-rpi-cm4-io"
;;
"FastRhino R66S" | "Lunzn FastRhino R66S")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-fastrhino-r66s.dtb"
fi
SOC="r66s"
;;
"FastRhino R68S" | "Lunzn FastRhino R68S")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-fastrhino-r68s.dtb"
fi
SOC="r68s"
;;
"RK3568 EC-X")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-ec-x.dtb"
fi
SOC="ec-x"
;;
"HINLINK OPC-H66K Board" | "Hlink H66K")
if [ -n "${CURRENT_FDTFILE}" ] && [ "${CURRENT_FDTFILE}" != "rk3568-opc-h66k.dtb" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-hlink-h66k.dtb"
fi
SOC="h66k"
;;
"HINLINK OPC-H68K Board" | "Hlink H68K")
if [ -n "${CURRENT_FDTFILE}" ] && [ "${CURRENT_FDTFILE}" != "rk3568-opc-h68k.dtb" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-hlink-h68k.dtb"
fi
SOC="h68k"
;;
"HINLINK OPC-H69K Board" | "Hlink H69K")
if [ -n "${CURRENT_FDTFILE}" ] && [ "${CURRENT_FDTFILE}" != "rk3568-opc-h69k.dtb" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-hlink-h69k.dtb"
fi
SOC="h69k"
;;
"Radxa E25" | "Radxa E25 Carrier Board")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-radxa-e25.dtb"
fi
SOC="e25"
;;
"HINLINK OWL H88K-V3 Board" | "Hlink H88K-V3")
if [ -n "${CURRENT_FDTFILE}" ] && [ "${CURRENT_FDTFILE}" != "rk3568-hinlink-h88k-v3.dtb" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3588-hlink-h88k-v3.dtb"
fi
SOC="h88k-v3"
;;
"Hlink H88K V3.1")
if [ -n "${CURRENT_FDTFILE}" ] && [ "${CURRENT_FDTFILE}" != "rk3568-hinlink-h88k-v31.dtb" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3588-hlink-h88k-v31.dtb"
fi
SOC="h88k-v3"
;;
"HINLINK OWL H88K Board" | "Hlink H88K")
if [ -n "${CURRENT_FDTFILE}" ] && [ "${CURRENT_FDTFILE}" != "rk3568-hinlink-h88k.dtb" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3588-hlink-h88k.dtb"
fi
SOC="ak88/h88k"
;;
"Hlink H28K")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3528-hlink-h28k.dtb"
fi
SOC="h28k"
;;
"Hlink HT2")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3528-hlink-ht2.dtb"
fi
SOC="ht2"
;;
"Radxa E20C")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3528-radxa-e20c.dtb"
fi
SOC="e20c"
;;
"Radxa E24C")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3528-radxa-e24c.dtb"
fi
SOC="e24c"
;;
"YiXun Rs6Pro")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3528-yixun-rs6pro.dtb"
fi
SOC="rs6pro"
;;
"Ariaboard Photonicat")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-photonicat.dtb"
fi
SOC="photonicat"
;;
"NLnet Watermelon Pi V3")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-watermelon-pi-v3.dtb"
fi
SOC="watermelon-pi-v3"
;;
"NLnet Watermelon Pi")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-watermelon-pi.dtb"
fi
SOC="watermelon-pi"
;;
"Radxa ROCK 5B" | "Radxa ROCK 5 Model B")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3588-rock-5b.dtb"
fi
SOC="rock5b"
;;
"Radxa ROCK 5C" | "Radxa ROCK 5 Model C")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3588s-rock-5c.dtb"
fi
SOC="rock5c"
;;
"Radxa E52C")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3588s-radxa-e52c.dtb"
fi
SOC="e52c"
;;
"Radxa E54C")
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3588s-radxa-e54c.dtb"
fi
SOC="e54c"
;;
*) #default
if [ -f "/etc/flippy-openwrt-release" ]; then
source /etc/flippy-openwrt-release 2>/dev/null
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="${FDTFILE}"
fi
SOC="${SOC}"
else
error_msg "Unknown device: [ ${MYDEVICE_NAME} ], Not supported."
fi
;;
esac
[[ -z "${MYDTB_FDTFILE}" || -z "${SOC}" ]] && {
error_msg "Invalid FDTFILE or SOC: [ ${MYDTB_FDTFILE} / ${SOC} ]"
}
echo -e "Current device: ${MYDEVICE_NAME} [ ${SOC} ]"
sleep 3
# Find the partition where root is located
ROOT_PTNAME="$(get_root_partition_name)"
# Find the disk where the partition is located, only supports mmcblk?p? sd?? hd?? vd?? and other formats
case ${ROOT_PTNAME} in
mmcblk?p[1-4])
EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}')
PARTITION_NAME="p"
LB_PRE="EMMC_"
;;
nvme?n?p?)
EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}')
PARTITION_NAME="p"
LB_PRE="NVME_"
;;
[hsv]d[a-z][1-4])
EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-1)}')
PARTITION_NAME=""
LB_PRE="USB_"
;;
*)
error_msg "Unable to recognize the disk type of ${ROOT_PTNAME}!"
;;
esac
cd /mnt/${EMMC_NAME}${PARTITION_NAME}4/
mv -f /tmp/upload/* . 2>/dev/null && sync
if [[ "${IMG_NAME}" == *.img ]]; then
echo -e "Update using [ ${IMG_NAME} ] file. Please wait a moment ..."
elif [ $(ls *.img -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then
IMG_NAME=$(ls *.img | head -n 1)
echo -e "Update using [ ${IMG_NAME} ] ] file. Please wait a moment ..."
elif [ $(ls *.img.xz -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then
xz_file=$(ls *.img.xz | head -n 1)
echo -e "Update using [ ${xz_file} ] file. Please wait a moment ..."
xz -d ${xz_file} 2>/dev/null
IMG_NAME=$(ls *.img | head -n 1)
elif [ $(ls *.img.gz -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then
gz_file=$(ls *.img.gz | head -n 1)
echo -e "Update using [ ${gz_file} ] file. Please wait a moment ..."
gzip -df ${gz_file} 2>/dev/null
IMG_NAME=$(ls *.img | head -n 1)
elif [ $(ls *.7z -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then
gz_file=$(ls *.7z | head -n 1)
echo -e "Update using [ ${gz_file} ] file. Please wait a moment ..."
bsdtar -xmf ${gz_file} 2>/dev/null
[ $? -eq 0 ] || 7z x ${gz_file} -aoa -y 2>/dev/null
IMG_NAME=$(ls *.img | head -n 1)
elif [ $(ls *.zip -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then
zip_file=$(ls *.zip | head -n 1)
echo -e "Update using [ ${zip_file} ] file. Please wait a moment ..."
unzip -o ${zip_file} 2>/dev/null
IMG_NAME=$(ls *.img | head -n 1)
else
echo -e "Please upload or specify the update openwrt firmware file."
echo -e "Upload method: system menu → Amlogic Service → Manually Upload Update"
echo -e "Specify method: Place the openwrt firmware file in [ /mnt/${EMMC_NAME}${PARTITION_NAME}4/ ]"
echo -e "The supported file suffixes are: *.img, *.img.xz, *.img.gz, *.7z, *.zip"
echo -e "After upload the openwrt firmware file, run again."
exit 1
fi
sync
# check file
if [ ! -f "${IMG_NAME}" ]; then
error_msg "No update file found."
else
echo "Start update from [ ${IMG_NAME} ]"
fi
# find boot partition
BOOT_PART_MSG=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | awk '$3~/^part$/ && $5 ~ /^\/boot$/ {print $0}')
if [ "${BOOT_PART_MSG}" == "" ]; then
error_msg "The boot partition is not exists or not mounted, so it cannot be upgraded with this script!"
fi
BR_FLAG=1
echo -ne "Whether to backup and restore the current config files? y/n [y]\b\b"
if [[ ${BACKUP_RESTORE_CONFIG} == "restore" ]]; then
yn="y"
elif [[ ${BACKUP_RESTORE_CONFIG} == "no-restore" ]]; then
yn="n"
else
read yn
fi
case ${yn} in
n* | N*)
BR_FLAG=0
;;
esac
BOOT_NAME=$(echo ${BOOT_PART_MSG} | awk '{print $1}')
BOOT_PATH=$(echo ${BOOT_PART_MSG} | awk '{print $2}')
BOOT_UUID=$(echo ${BOOT_PART_MSG} | awk '{print $4}')
# find root partition
ROOT_PART_MSG="$(get_root_partition_msg)"
ROOT_NAME=$(echo ${ROOT_PART_MSG} | awk '{print $1}')
ROOT_PATH=$(echo ${ROOT_PART_MSG} | awk '{print $2}')
ROOT_UUID=$(echo ${ROOT_PART_MSG} | awk '{print $4}')
case ${ROOT_NAME} in
${EMMC_NAME}${PARTITION_NAME}2)
NEW_ROOT_NAME="${EMMC_NAME}${PARTITION_NAME}3"
NEW_ROOT_LABEL="${LB_PRE}ROOTFS2"
;;
${EMMC_NAME}${PARTITION_NAME}3)
NEW_ROOT_NAME="${EMMC_NAME}${PARTITION_NAME}2"
NEW_ROOT_LABEL="${LB_PRE}ROOTFS1"
;;
*)
error_msg "The root partition location is invalid, so it cannot be upgraded with this script!"
;;
esac
# find new root partition
NEW_ROOT_PART_MSG=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | grep "${NEW_ROOT_NAME}" | awk '$3 ~ /^part$/ && $5 !~ /^\/$/ && $5 !~ /^\/boot$/ {print $0}')
if [ "${NEW_ROOT_PART_MSG}" == "" ]; then
error_msg "The new root partition is not exists, so it cannot be upgraded with this script!"
fi
NEW_ROOT_NAME=$(echo ${NEW_ROOT_PART_MSG} | awk '{print $1}')
NEW_ROOT_PATH=$(echo ${NEW_ROOT_PART_MSG} | awk '{print $2}')
NEW_ROOT_UUID=$(echo ${NEW_ROOT_PART_MSG} | awk '{print $4}')
NEW_ROOT_MP=$(echo ${NEW_ROOT_PART_MSG} | awk '{print $5}')
# losetup
losetup -f -P ${IMG_NAME}
if [[ "${?}" -eq "0" ]]; then
LOOP_DEV=$(losetup | grep "${IMG_NAME}" | awk '{print $1}')
if [ "$LOOP_DEV" == "" ]; then
error_msg "loop device not found!"
fi
else
error_msg "losetup ${IMG_FILE} failed!"
fi
# fix loopdev issue in kernel 5.19
function fix_loopdev() {
local parentdev=${1##*/}
if [ ! -d /sys/block/${parentdev} ]; then
return
fi
subdevs=$(lsblk -l -o NAME | grep -E "^${parentdev}.+\$")
for subdev in ${subdevs}; do
if [ ! -d /sys/block/${parentdev}/${subdev} ]; then
return
elif [ -b /dev/${sub_dev} ]; then
continue
fi
source /sys/block/${parentdev}/${subdev}/uevent
mknod /dev/${subdev} b ${MAJOR} ${MINOR}
unset MAJOR MINOR DEVNAME DEVTYPE DISKSEQ PARTN PARTNAME
done
}
fix_loopdev ${LOOP_DEV}
WAIT=3
echo -n "The loopdev is ${LOOP_DEV}, wait ${WAIT} seconds "
while [ ${WAIT} -ge 1 ]; do
echo -n "."
sleep 1
WAIT=$((WAIT - 1))
done
echo
# umount loop devices (openwrt will auto mount some partition)
MOUNTED_DEVS=$(lsblk -l -o NAME,PATH,MOUNTPOINT | grep "${LOOP_DEV}" | awk '$3 !~ /^$/ {print $2}')
for dev in ${MOUNTED_DEVS}; do
while :; do
echo -n "umount ${dev} ... "
umount -f ${dev}
sleep 1
mnt=$(lsblk -l -o NAME,PATH,MOUNTPOINT | grep "${dev}" | awk '$3 !~ /^$/ {print $2}')
if [ "${mnt}" == "" ]; then
echo "ok"
break
else
echo "try again ..."
fi
done
done
# mount src part
WORK_DIR=${PWD}
P1=${WORK_DIR}/boot
P2=${WORK_DIR}/root
mkdir -p $P1 $P2
echo -n "mount ${LOOP_DEV}p1 -> ${P1} ... "
mount -t ext4 -o ro ${LOOP_DEV}p1 ${P1}
if [[ "${?}" -ne "0" ]]; then
echo "mount failed"
losetup -D
exit 1
else
echo "ok"
fi
echo -n "mount ${LOOP_DEV}p2 -> ${P2} ... "
ZSTD_LEVEL=6
mount -t btrfs -o ro,compress=zstd:${ZSTD_LEVEL} ${LOOP_DEV}p2 ${P2}
if [[ "${?}" -ne "0" ]]; then
echo "mount failed"
umount -f ${P1}
losetup -D
exit 1
else
echo "ok"
fi
# Prepare the dockerman config file
if [ -f ${P2}/etc/init.d/dockerman ] && [ -f ${P2}/etc/config/dockerd ]; then
flg=0
# get current docker data root
data_root=$(uci get dockerd.globals.data_root 2>/dev/null)
if [ "${data_root}" == "" ]; then
flg=1
# get current config from /etc/docker/daemon.json
if [ -f "/etc/docker/daemon.json" ] && [ -x "/usr/bin/jq" ]; then
data_root=$(jq -r '."data-root"' /etc/docker/daemon.json)
bip=$(jq -r '."bip"' /etc/docker/daemon.json)
[ "${bip}" == "null" ] && bip="172.31.0.1/24"
log_level=$(jq -r '."log-level"' /etc/docker/daemon.json)
[ "${log_level}" == "null" ] && log_level="warn"
_iptables=$(jq -r '."iptables"' /etc/docker/daemon.json)
[ "${_iptables}" == "null" ] && _iptables="true"
registry_mirrors=$(jq -r '."registry-mirrors"[]' /etc/docker/daemon.json 2>/dev/null)
fi
fi
if [ "${data_root}" == "" ]; then
data_root="/opt/docker/" # the default data root
fi
if ! uci get dockerd.globals >/dev/null 2>&1; then
uci set dockerd.globals='globals'
uci commit
fi
# delete alter config , use inner config
if uci get dockerd.globals.alt_config_file >/dev/null 2>&1; then
uci delete dockerd.globals.alt_config_file
uci commit
fi
if [[ "${flg}" -eq "1" ]]; then
uci set dockerd.globals.data_root=${data_root}
[ "${bip}" != "" ] && uci set dockerd.globals.bip=${bip}
[ "${log_level}" != "" ] && uci set dockerd.globals.log_level=${log_level}
[ "${_iptables}" != "" ] && uci set dockerd.globals.iptables=${_iptables}
if [ "${registry_mirrors}" != "" ]; then
for reg in ${registry_mirrors}; do
uci add_list dockerd.globals.registry_mirrors=${reg}
done
fi
uci set dockerd.globals.auto_start='1'
uci commit
fi
fi
#format NEW_ROOT
echo "umount ${NEW_ROOT_MP}"
umount -f "${NEW_ROOT_MP}"
if [[ "${?}" -ne "0" ]]; then
echo "umount failed, please reboot and try again!"
umount -f ${P1}
umount -f ${P2}
losetup -D
exit 1
fi
echo "format ${NEW_ROOT_PATH}"
NEW_ROOT_UUID=$(uuidgen)
mkfs.btrfs -f -U ${NEW_ROOT_UUID} -L ${NEW_ROOT_LABEL} -m single ${NEW_ROOT_PATH}
if [[ "${?}" -ne "0" ]]; then
echo "format ${NEW_ROOT_PATH} failed!"
umount -f ${P1}
umount -f ${P2}
losetup -D
exit 1
fi
echo "mount ${NEW_ROOT_PATH} to ${NEW_ROOT_MP}"
mount -t btrfs -o compress=zstd:${ZSTD_LEVEL} ${NEW_ROOT_PATH} ${NEW_ROOT_MP}
if [[ "${?}" -ne "0" ]]; then
echo "mount ${NEW_ROOT_PATH} to ${NEW_ROOT_MP} failed!"
umount -f ${P1}
umount -f ${P2}
losetup -D
exit 1
fi
# begin copy rootfs
cd ${NEW_ROOT_MP}
echo "Start copy data from ${P2} to ${NEW_ROOT_MP} ..."
ENTRYS=$(ls)
for entry in ${ENTRYS}; do
if [ "${entry}" == "lost+found" ]; then
continue
fi
echo -n "remove old ${entry} ... "
rm -rf ${entry}
if [ $? -eq 0 ]; then
echo "ok"
else
echo "failed"
exit 1
fi
done
echo
echo "create etc subvolume ..."
btrfs subvolume create etc
echo -n "make dirs ... "
mkdir -p .snapshots .reserved bin boot dev lib opt mnt overlay proc rom root run sbin sys tmp usr www
ln -sf lib/ lib64
ln -sf tmp/ var
echo "done"
echo
COPY_SRC="root etc bin sbin lib opt usr www"
echo "copy data ... "
for src in ${COPY_SRC}; do
echo -n "copy ${src} ... "
(cd ${P2} && tar cf - ${src}) | tar xf -
sync
echo "done"
done
SHFS="/mnt/${EMMC_NAME}${PARTITION_NAME}4"
echo "Modify config files ... "
if [ -x ./usr/sbin/balethirq.pl ]; then
if grep "balethirq.pl" "./etc/rc.local"; then
echo "balance irq is enabled"
else
echo "enable balance irq"
sed -e "/exit/i\/usr/sbin/balethirq.pl" -i ./etc/rc.local
fi
fi
rm -f ./etc/bench.log
cat >./etc/fstab <<EOF
UUID=${NEW_ROOT_UUID} / btrfs compress=zstd:${ZSTD_LEVEL} 0 1
UUID=${BOOT_UUID} /boot ext4 defaults 0 2
#tmpfs /tmp tmpfs defaults,nosuid 0 0
EOF
cat >./etc/config/fstab <<EOF
config global
option anon_swap '0'
option anon_mount '1'
option auto_swap '0'
option auto_mount '1'
option delay_root '5'
option check_fs '0'
config mount
option target '/rom'
option uuid '${NEW_ROOT_UUID}'
option enabled '1'
option enabled_fsck '1'
option fstype 'btrfs'
option options 'compress=zstd:${ZSTD_LEVEL}'
config mount
option target '/boot'
option uuid '${BOOT_UUID}'
option enabled '1'
option enabled_fsck '0'
option fstype 'ext4'
EOF
(
cd etc/rc.d
rm -f S??shortcut-fe
if grep "sfe_flow '1'" ../config/turboacc >/dev/null; then
if find ../../lib/modules -name 'shortcut-fe-cm.ko'; then
ln -sf ../init.d/shortcut-fe S99shortcut-fe
fi
fi
)
# move /etc/config/balance_irq to /etc/balance_irq
[ -f "./etc/config/balance_irq" ] && mv ./etc/config/balance_irq ./etc/
sync
echo "create the first etc snapshot -> .snapshots/etc-000"
btrfs subvolume snapshot -r etc .snapshots/etc-000
[ -d ${SHFS}/docker ] || mkdir -p ${SHFS}/docker
rm -rf opt/docker && ln -sf ${SHFS}/docker/ opt/docker
if [ -f /mnt/${NEW_ROOT_NAME}/etc/config/AdGuardHome ]; then
[ -d ${SHFS}/AdGuardHome/data ] || mkdir -p ${SHFS}/AdGuardHome/data
if [ ! -L /usr/bin/AdGuardHome ]; then
[ -d /usr/bin/AdGuardHome ] &&
cp -a /usr/bin/AdGuardHome/* ${SHFS}/AdGuardHome/
fi
ln -sf ${SHFS}/AdGuardHome /mnt/${NEW_ROOT_NAME}/usr/bin/AdGuardHome
fi
sync
echo "copy done"
echo
BACKUP_LIST=$(${P2}/usr/sbin/openwrt-backup -p)
if [ $BR_FLAG -eq 1 ]; then
echo -n "Restore your old config files ... "
(
cd /
eval tar czf ${NEW_ROOT_MP}/.reserved/openwrt_config.tar.gz "${BACKUP_LIST}" 2>/dev/null
)
tar xzf ${NEW_ROOT_MP}/.reserved/openwrt_config.tar.gz
[ -f ./etc/config/dockerman ] && sed -e "s/option wan_mode 'false'/option wan_mode 'true'/" -i ./etc/config/dockerman 2>/dev/null
[ -f ./etc/config/dockerd ] && sed -e "s/option wan_mode '0'/option wan_mode '1'/" -i ./etc/config/dockerd 2>/dev/null
[ -f ./etc/config/verysync ] && sed -e 's/config setting/config verysync/' -i ./etc/config/verysync
# 还原 fstab
cp -f .snapshots/etc-000/fstab ./etc/fstab
cp -f .snapshots/etc-000/config/fstab ./etc/config/fstab
# 还原 luci
cp -f .snapshots/etc-000/config/luci ./etc/config/luci
# 还原/etc/config/rpcd
cp -f .snapshots/etc-000/config/rpcd ./etc/config/rpcd
sync
echo "done"
echo
fi
cat >>./etc/crontabs/root <<EOF
17 3 * * * /etc/coremark.sh
EOF
sed -e 's/ttyAMA0/ttyS2/' -i ./etc/inittab
[ "${SOC}" != "h28k" ] && \
[ "${SOC}" != "h29k" ] && \
[ "${SOC}" != "ht2" ] && \
[ "${SOC}" != "e20c" ] && \
[ "${SOC}" != "e24c" ] && \
sed -e 's/ttyS0/tty1/' -i ./etc/inittab
sss=$(date +%s)
ddd=$((sss / 86400))
sed -e "s/:0:0:99999:7:::/:${ddd}:0:99999:7:::/" -i ./etc/shadow
# 修复amule每次升级后重复添加条目的问题
sed -e "/amule:x:/d" -i ./etc/shadow
# 修复dropbear每次升级后重复添加sshd条目的问题
sed -e "/sshd:x:/d" -i ./etc/shadow
if ! grep "sshd:x:22:sshd" ./etc/group >/dev/null; then
echo "sshd:x:22:sshd" >>./etc/group
fi
if ! grep "sshd:x:22:22:sshd:" ./etc/passwd >/dev/null; then
echo "sshd:x:22:22:sshd:/var/run/sshd:/bin/false" >>./etc/passwd
fi
if ! grep "sshd:x:" ./etc/shadow >/dev/null; then
echo "sshd:x:${ddd}:0:99999:7:::" >>./etc/shadow
fi
if [ $BR_FLAG -eq 1 ]; then
if [ -x ./bin/bash ] && [ -f ./etc/profile.d/30-sysinfo.sh ]; then
sed -e 's/\/bin\/ash/\/bin\/bash/' -i ./etc/passwd
fi
sync
echo "done"
echo
fi
sed -e "s/option hw_flow '1'/option hw_flow '0'/" -i ./etc/config/turboacc
(
cd etc/rc.d
rm -f S??shortcut-fe
if grep "sfe_flow '1'" ../config/turboacc >/dev/null; then
if find ../../lib/modules -name 'shortcut-fe-cm.ko'; then
ln -sf ../init.d/shortcut-fe S99shortcut-fe
fi
fi
)
# move /etc/config/balance_irq to /etc/balance_irq
[ -f "./etc/config/balance_irq" ] && mv ./etc/config/balance_irq ./etc/
rm -f "./etc/rc.local.orig" "./etc/first_run.sh" "./etc/part_size"
eval tar czf .reserved/openwrt_config.tar.gz "${BACKUP_LIST}" 2>/dev/null
sync
mv ./etc/rc.local ./etc/rc.local.orig
cat >"./etc/rc.local" <<EOF
if ! ls /etc/rc.d/S??dockerd >/dev/null 2>&1;then
/etc/init.d/dockerd enable
/etc/init.d/dockerd start
fi
if ! ls /etc/rc.d/S??dockerman >/dev/null 2>&1 && [ -f /etc/init.d/dockerman ];then
/etc/init.d/dockerman enable
/etc/init.d/dockerman start
fi
mv /etc/rc.local.orig /etc/rc.local
chmod 755 /etc/rc.local
exec /etc/rc.local
exit
EOF
chmod 755 ./etc/rc.local*
echo "create the second etc snapshot -> .snapshots/etc-001"
btrfs subvolume snapshot -r etc .snapshots/etc-001
# 2021.04.01添加
# 强制锁定fstab,防止用户擅自修改挂载点
# 开启了快照功能之后,不再需要锁定fstab
#chattr +ia ./etc/config/fstab
cd ${WORK_DIR}
echo "Start copy data from ${P2} to /boot ..."
cd /boot
echo -n "backup armbianEnv.txt ..."
cp armbianEnv.txt /tmp/
echo -n "backup current dtb file ..."
cp -v dtb/rockchip/${CURRENT_FDTFILE} /tmp/
echo -n "remove old boot files ..."
rm -rf *
echo "done"
echo -n "copy new boot files ... "
(cd ${P1} && tar cf - .) | tar xf -
sync
echo "done"
echo
echo -n "Update boot args ... "
if [ -f /tmp/armbianEnv.txt ]; then
ORIG_OVERLAYS=$(grep '^overlays=' /tmp/armbianEnv.txt)
ORIG_USER_OVERLAYS=$(grep '^user_overlays=' /tmp/armbianEnv.txt)
sed -e '/user_overlays=/d' -i armbianEnv.txt
sed -e '/overlays=/d' -i armbianEnv.txt
echo "$ORIG_OVERLAYS" >>armbianEnv.txt
echo "$ORIG_USER_OVERLAYS" >>armbianEnv.txt
fi
sed -e '/fdtfile=/d' -i armbianEnv.txt
sed -e '/rootdev=/d' -i armbianEnv.txt
sed -e '/rootfstype=/d' -i armbianEnv.txt
sed -e '/rootflags=/d' -i armbianEnv.txt
case $SOC in
l1pro | beikeyun)
echo "fdtfile=/dtb/rockchip/${MYDTB_FDTFILE}" >>armbianEnv.txt
;;
*)
echo "fdtfile=rockchip/${MYDTB_FDTFILE}" >>armbianEnv.txt
;;
esac
cat >>armbianEnv.txt <<EOF
rootdev=UUID=${NEW_ROOT_UUID}
rootfstype=btrfs
rootflags=compress=zstd:${ZSTD_LEVEL}
EOF
# Replace the UUID for extlinux/extlinux.conf if it exists
[[ -f "extlinux/extlinux.conf" ]] && {
sed -i -E "s|UUID=[^ ]*|UUID=${NEW_ROOT_UUID}|" extlinux/extlinux.conf 2>/dev/null
}
# 如果新的dtb文件不存在,则用旧的代替
if [ ! -f "dtb/rockchip/${MYDTB_FDTFILE}" ]; then
echo "The new dtb file does not exist, replace it with the old one."
cp -v /tmp/${CURRENT_FDTFILE} dtb/rockchip/${MYDTB_FDTFILE}
fi
sync
echo "done"
echo
cd $WORK_DIR
umount -f ${P1} ${P2} 2>/dev/null
losetup -D 2>/dev/null
rmdir ${P1} ${P2} 2>/dev/null
rm -f ${IMG_NAME} 2>/dev/null
rm -f sha256sums 2>/dev/null
sync
echo "Successfully updated, automatic restarting..."
sleep 3
reboot
exit 0
|
2929004360/ruoyi-sign
| 2,043
|
ruoyi-framework/src/main/java/com/ruoyi/framework/config/FilterConfig.java
|
package com.ruoyi.framework.config;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.DispatcherType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.ruoyi.common.filter.RepeatableFilter;
import com.ruoyi.common.filter.XssFilter;
import com.ruoyi.common.utils.StringUtils;
/**
* Filter配置
*
* @author ruoyi
*/
@Configuration
public class FilterConfig
{
@Value("${xss.excludes}")
private String excludes;
@Value("${xss.urlPatterns}")
private String urlPatterns;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
@ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
public FilterRegistrationBean xssFilterRegistration()
{
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new XssFilter());
registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
registration.setName("xssFilter");
registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("excludes", excludes);
registration.setInitParameters(initParameters);
return registration;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public FilterRegistrationBean someFilterRegistration()
{
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new RepeatableFilter());
registration.addUrlPatterns("/*");
registration.setName("repeatableFilter");
registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
return registration;
}
}
|
281677160/openwrt-package
| 27,710
|
luci-app-amlogic/root/usr/sbin/openwrt-update-amlogic
|
#!/bin/bash
#======================================================================================
# Function: Update openwrt to emmc for Amlogic S9xxx STB
# Copyright (C) 2020-- https://github.com/unifreq/openwrt_packit
# Copyright (C) 2021-- https://github.com/ophub/luci-app-amlogic
#======================================================================================
#
# The script supports directly setting parameters for update, skipping interactive selection
# openwrt-update-amlogic ${OPENWRT_FILE} ${AUTO_MAINLINE_UBOOT} ${RESTORE_CONFIG}
# E.g: openwrt-update-amlogic openwrt_s905d.img.gz yes restore
# E.g: openwrt-update-amlogic openwrt_s905d.img.gz no no-restore
# You can also execute the script directly, and interactively select related functions
# E.g: openwrt-update-amlogic
#
#======================================================================================
# Encountered a serious error, abort the script execution
error_msg() {
echo -e "[ERROR] ${1}"
exit 1
}
# Get the partition name of the root file system
get_root_partition_name() {
local paths=("/" "/overlay" "/rom")
local partition_name
for path in "${paths[@]}"; do
partition_name=$(df "${path}" | awk 'NR==2 {print $1}' | awk -F '/' '{print $3}')
[[ -n "${partition_name}" ]] && break
done
[[ -z "${partition_name}" ]] && error_msg "Cannot find the root partition!"
echo "${partition_name}"
}
# Get the partition message of the root file system
get_root_partition_msg() {
local paths=("/" "/overlay" "/rom")
local partition_name
for path in "${paths[@]}"; do
partition_msg=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | awk '$3~/^part$/ && $5 ~ "^" "'"${path}"'" "$" {print $0}')
[[ -n "${partition_msg}" ]] && break
done
[[ -z "${partition_msg}" ]] && error_msg "Cannot find the root partition message!"
echo "${partition_msg}"
}
# Receive one-key command related parameters
IMG_NAME="${1}"
AUTO_MAINLINE_UBOOT="${2}"
BACKUP_RESTORE_CONFIG="${3}"
# Current device model
MYDEVICE_NAME=$(cat /proc/device-tree/model | tr -d '\000')
if [[ -z "${MYDEVICE_NAME}" ]]; then
error_msg "The device name is empty and cannot be recognized."
elif [[ ! -f "/etc/flippy-openwrt-release" ]]; then
error_msg "The [ /etc/flippy-openwrt-release ] file is missing."
else
echo -e "Current device: ${MYDEVICE_NAME} [ amlogic ]"
sleep 3
fi
# Find the partition where root is located
ROOT_PTNAME="$(get_root_partition_name)"
# Find the disk where the partition is located, only supports mmcblk?p? sd?? hd?? vd?? and other formats
case ${ROOT_PTNAME} in
mmcblk?p[1-4])
EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}')
if lsblk -l -o NAME | grep "${EMMC_NAME}boot0" >/dev/null; then
ROOT_DISK_TYPE="EMMC"
else
ROOT_DISK_TYPE="SD"
fi
PARTITION_NAME="p"
LB_PRE="${ROOT_DISK_TYPE}_"
;;
[hsv]d[a-z][1-4])
EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-1)}')
ROOT_DISK_TYPE="USB"
PARTITION_NAME=""
LB_PRE="${ROOT_DISK_TYPE}_"
;;
*)
error_msg "Unable to recognize the disk type of ${ROOT_PTNAME}!"
;;
esac
DOCKER_ROOT="/mnt/${EMMC_NAME}${PARTITION_NAME}4/docker/"
cd /mnt/${EMMC_NAME}${PARTITION_NAME}4/
mv -f /tmp/upload/* . 2>/dev/null && sync
if [[ "${IMG_NAME}" == *.img ]]; then
echo -e "Update using [ ${IMG_NAME} ] file. Please wait a moment ..."
elif [ $(ls *.img -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then
IMG_NAME=$(ls *.img | head -n 1)
echo -e "Update using [ ${IMG_NAME} ] ] file. Please wait a moment ..."
elif [ $(ls *.img.xz -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then
xz_file=$(ls *.img.xz | head -n 1)
echo -e "Update using [ ${xz_file} ] file. Please wait a moment ..."
xz -d ${xz_file} 2>/dev/null
IMG_NAME=$(ls *.img | head -n 1)
elif [ $(ls *.img.gz -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then
gz_file=$(ls *.img.gz | head -n 1)
echo -e "Update using [ ${gz_file} ] file. Please wait a moment ..."
gzip -df ${gz_file} 2>/dev/null
IMG_NAME=$(ls *.img | head -n 1)
elif [ $(ls *.7z -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then
gz_file=$(ls *.7z | head -n 1)
echo -e "Update using [ ${gz_file} ] file. Please wait a moment ..."
bsdtar -xmf ${gz_file} 2>/dev/null
[ $? -eq 0 ] || 7z x ${gz_file} -aoa -y 2>/dev/null
IMG_NAME=$(ls *.img | head -n 1)
elif [ $(ls *.zip -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then
zip_file=$(ls *.zip | head -n 1)
echo -e "Update using [ ${zip_file} ] file. Please wait a moment ..."
unzip -o ${zip_file} 2>/dev/null
IMG_NAME=$(ls *.img | head -n 1)
else
echo -e "Please upload or specify the update openwrt firmware file."
echo -e "Upload method: system menu → Amlogic Service → Manually Upload Update"
echo -e "Specify method: Place the openwrt firmware file in [ /mnt/${EMMC_NAME}${PARTITION_NAME}4/ ]"
echo -e "The supported file suffixes are: *.img, *.img.xz, *.img.gz, *.7z, *.zip"
echo -e "After upload the openwrt firmware file, run again."
exit 1
fi
sync
# check file
if [ ! -f "${IMG_NAME}" ]; then
error_msg "No update file found."
else
echo "Start update from [ ${IMG_NAME} ]"
fi
# Check the necessary dependencies
DEPENDS="lsblk uuidgen grep awk btrfs mkfs.fat mkfs.btrfs md5sum fatlabel"
echo "Check the necessary dependencies..."
for dep in ${DEPENDS}; do
WITCH=$(busybox which ${dep})
if [ "${WITCH}" == "" ]; then
error_msg "Dependent command: ${dep} does not exist, upgrade cannot be performed, only flash through U disk/TF card!"
else
echo "${dep} path: ${WITCH}"
fi
done
echo "Check passed"
# find boot partition
BOOT_PART_MSG=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | awk '$3~/^part$/ && $5 ~ /^\/boot$/ {print $0}')
if [ "${BOOT_PART_MSG}" == "" ]; then
error_msg "Boot The partition does not exist, so the update cannot be continued!"
fi
BOOT_NAME=$(echo ${BOOT_PART_MSG} | awk '{print $1}')
BOOT_PATH=$(echo ${BOOT_PART_MSG} | awk '{print $2}')
BOOT_UUID=$(echo ${BOOT_PART_MSG} | awk '{print $4}')
BR_FLAG=1
echo -ne "Whether to backup and restore the current config files? y/n [y]\b\b"
if [[ ${BACKUP_RESTORE_CONFIG} == "restore" ]]; then
yn="y"
elif [[ ${BACKUP_RESTORE_CONFIG} == "no-restore" ]]; then
yn="n"
else
read yn
fi
case $yn in
n* | N*)
BR_FLAG=0
;;
esac
# find root partition
ROOT_PART_MSG="$(get_root_partition_msg)"
ROOT_NAME=$(echo ${ROOT_PART_MSG} | awk '{print $1}')
ROOT_PATH=$(echo ${ROOT_PART_MSG} | awk '{print $2}')
ROOT_UUID=$(echo ${ROOT_PART_MSG} | awk '{print $4}')
case ${ROOT_NAME} in
${EMMC_NAME}${PARTITION_NAME}2)
NEW_ROOT_NAME="${EMMC_NAME}${PARTITION_NAME}3"
NEW_ROOT_LABEL="${LB_PRE}ROOTFS2"
;;
${EMMC_NAME}${PARTITION_NAME}3)
NEW_ROOT_NAME="${EMMC_NAME}${PARTITION_NAME}2"
NEW_ROOT_LABEL="${LB_PRE}ROOTFS1"
;;
*)
error_msg "ROOTFS The partition location is incorrect, so the update cannot continue!"
;;
esac
echo "NEW_ROOT_NAME: [ ${NEW_ROOT_NAME} ]"
# find new root partition
NEW_ROOT_PART_MSG=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | grep "${NEW_ROOT_NAME}" | awk '$3 ~ /^part$/ && $5 !~ /^\/$/ && $5 !~ /^\/boot$/ {print $0}')
if [ "${NEW_ROOT_PART_MSG}" == "" ]; then
error_msg "The new ROOTFS partition does not exist, so the update cannot continue!"
fi
NEW_ROOT_NAME=$(echo ${NEW_ROOT_PART_MSG} | awk '{print $1}')
NEW_ROOT_PATH=$(echo ${NEW_ROOT_PART_MSG} | awk '{print $2}')
NEW_ROOT_UUID=$(echo ${NEW_ROOT_PART_MSG} | awk '{print $4}')
NEW_ROOT_MP=$(echo ${NEW_ROOT_PART_MSG} | awk '{print $5}')
echo "NEW_ROOT_MP: [ ${NEW_ROOT_MP} ]"
# backup old bootloader
if [ ! -f /root/BackupOldBootloader.img ]; then
echo "Backup bootloader -> [ BackupOldBootloader.img ] ... "
dd if=/dev/${EMMC_NAME} of=/root/BackupOldBootloader.img bs=1M count=4 conv=fsync
echo "Backup bootloader complete."
echo
fi
# losetup
losetup -f -P ${IMG_NAME}
if [ ${?} -eq 0 ]; then
LOOP_DEV=$(losetup | grep "${IMG_NAME}" | awk '{print $1}')
if [ "${LOOP_DEV}" == "" ]; then
error_msg "loop device not found!"
fi
else
error_msg "losetup [ ${IMG_FILE} ] failed!"
fi
# fix loopdev issue in kernel 5.19
function fix_loopdev() {
local parentdev=${1##*/}
if [ ! -d /sys/block/${parentdev} ]; then
return
fi
subdevs=$(lsblk -l -o NAME | grep -E "^${parentdev}.+\$")
for subdev in ${subdevs}; do
if [ ! -d /sys/block/${parentdev}/${subdev} ]; then
return
elif [ -b /dev/${sub_dev} ]; then
continue
fi
source /sys/block/${parentdev}/${subdev}/uevent
mknod /dev/${subdev} b ${MAJOR} ${MINOR}
unset MAJOR MINOR DEVNAME DEVTYPE DISKSEQ PARTN PARTNAME
done
}
fix_loopdev ${LOOP_DEV}
WAIT=3
echo "The loopdev is [ $LOOP_DEV ], wait [ ${WAIT} ] seconds. "
while [[ "${WAIT}" -ge "1" ]]; do
sleep 1
WAIT=$((WAIT - 1))
done
# umount loop devices (openwrt will auto mount some partition)
MOUNTED_DEVS=$(lsblk -l -o NAME,PATH,MOUNTPOINT | grep "${LOOP_DEV}" | awk '$3 !~ /^$/ {print $2}')
for dev in ${MOUNTED_DEVS}; do
while :; do
echo "umount [ ${dev} ] ... "
umount -f ${dev}
sleep 1
mnt=$(lsblk -l -o NAME,PATH,MOUNTPOINT | grep "${dev}" | awk '$3 !~ /^$/ {print $2}')
if [ "${mnt}" == "" ]; then
break
else
echo "Retry ..."
fi
done
done
# mount src part
WORK_DIR=${PWD}
P1=${WORK_DIR}/boot
P2=${WORK_DIR}/root
mkdir -p $P1 $P2
echo "Mount [ ${LOOP_DEV}p1 ] -> [ ${P1} ] ... "
mount -t vfat -o ro ${LOOP_DEV}p1 ${P1}
if [ $? -ne 0 ]; then
echo "Mount p1 [ ${LOOP_DEV}p1 ] failed!"
losetup -D
exit 1
fi
echo "Mount [ ${LOOP_DEV}p2 ] -> [ ${P2} ] ... "
ZSTD_LEVEL=6
mount -t btrfs -o ro,compress=zstd:${ZSTD_LEVEL} ${LOOP_DEV}p2 ${P2}
if [ $? -ne 0 ]; then
echo "Mount p2 [ ${LOOP_DEV}p2 ] failed!"
umount -f ${P1}
losetup -D
exit 1
fi
# Prepare the dockerman config file
if [ -f ${P2}/etc/init.d/dockerman ] && [ -f ${P2}/etc/config/dockerd ]; then
flg=0
# get current docker data root
data_root=$(uci get dockerd.globals.data_root 2>/dev/null)
if [ "${data_root}" == "" ]; then
flg=1
# get current config from /etc/docker/daemon.json
if [ -f "/etc/docker/daemon.json" ] && [ -x "/usr/bin/jq" ]; then
data_root=$(jq -r '."data-root"' /etc/docker/daemon.json)
bip=$(jq -r '."bip"' /etc/docker/daemon.json)
[ "${bip}" == "null" ] && bip="172.31.0.1/24"
log_level=$(jq -r '."log-level"' /etc/docker/daemon.json)
[ "${log_level}" == "null" ] && log_level="warn"
_iptables=$(jq -r '."iptables"' /etc/docker/daemon.json)
[ "${_iptables}" == "null" ] && _iptables="true"
registry_mirrors=$(jq -r '."registry-mirrors"[]' /etc/docker/daemon.json 2>/dev/null)
fi
fi
if [ "${data_root}" == "" ]; then
data_root="/opt/docker/" # the default data root
fi
if ! uci get dockerd.globals >/dev/null 2>&1; then
uci set dockerd.globals='globals'
uci commit
fi
# delete alter config , use inner config
if uci get dockerd.globals.alt_config_file >/dev/null 2>&1; then
uci delete dockerd.globals.alt_config_file
uci commit
fi
if [ ${flg} -eq 1 ]; then
uci set dockerd.globals.data_root=${data_root}
[ "${bip}" != "" ] && uci set dockerd.globals.bip=${bip}
[ "${log_level}" != "" ] && uci set dockerd.globals.log_level=${log_level}
[ "${_iptables}" != "" ] && uci set dockerd.globals.iptables=${_iptables}
if [ "${registry_mirrors}" != "" ]; then
for reg in ${registry_mirrors}; do
uci add_list dockerd.globals.registry_mirrors=${reg}
done
fi
uci set dockerd.globals.auto_start='1'
uci commit
fi
fi
#update version prompt
source /boot/uEnv.txt 2>/dev/null
CUR_FDTFILE=${FDT}
echo -e "FDT Value [ ${CUR_FDTFILE} ]"
cp /boot/uEnv.txt /tmp/uEnv.txt && sync
K510="1"
[[ "$(hexdump -n 15 -x "${P1}/zImage" 2>/dev/null | head -n 1 | awk '{print $7}')" == "0108" ]] && K510="0"
echo -e "K510 [ ${K510} ]"
# flippy-openwrt-release info
UBOOT_OVERLOAD=""
MAINLINE_UBOOT=""
ANDROID_UBOOT=""
env_openwrt_file=""
if [ -f "${P2}/etc/flippy-openwrt-release" ]; then
env_openwrt_file="${P2}/etc/flippy-openwrt-release"
elif [ -f "/etc/flippy-openwrt-release" ]; then
env_openwrt_file="/etc/flippy-openwrt-release"
else
env_openwrt_file=""
fi
if [ -n "${env_openwrt_file}" ]; then
source "${env_openwrt_file}" 2>/dev/null
# Update the parameters used
UBOOT_OVERLOAD=${UBOOT_OVERLOAD}
MAINLINE_UBOOT=${MAINLINE_UBOOT}
ANDROID_UBOOT=${ANDROID_UBOOT}
# Unused parameters
FDTFILE=${FDTFILE}
U_BOOT_EXT=${U_BOOT_EXT}
KERNEL_VERSION=${KERNEL_VERSION}
SOC=${SOC}
fi
#format NEW_ROOT
echo "umount [ ${NEW_ROOT_MP} ]"
umount -f "${NEW_ROOT_MP}"
if [[ "${?}" -ne "0" ]]; then
echo "Umount [ ${NEW_ROOT_MP} ] failed, Please restart and try again!"
umount -f ${P1}
umount -f ${P2}
losetup -D
exit 1
fi
# check and fix partition
function check_and_fix_partition() {
local target_dev_name=${1} # mmcblk2
local target_pt_name=${2} # p2
local target_pt_idx=${3} # 2
local safe_pt_begin_mb=${4} # 800
local safe_pt_begin_byte=$((${safe_pt_begin_mb} * 1024 * 1024))
local cur_pt_begin_sector=$(fdisk -l /dev/${target_dev_name} | grep ${target_dev_name}${target_pt_name} | awk '{printf $2}')
local cur_pt_begin_mb=$((${cur_pt_begin_sector} * 512 / 1024 / 1024))
if [ ${cur_pt_begin_mb} -ge ${safe_pt_begin_mb} ]; then
# check pass
return
fi
local cur_pt_end_sector=$(fdisk -l /dev/${target_dev_name} | grep ${target_dev_name}${target_pt_name} | awk '{printf $3}')
local cur_pt_end_byte=$(((${cur_pt_end_sector} + 1) * 512 - 1))
echo "Unsafe partition found, repairing ... "
parted /dev/${target_dev_name} rm ${target_pt_idx} ||
(
error_msg "rm partion ${target_pt_idx} failed"
)
parted /dev/${target_dev_name} mkpart primary btrfs "${safe_pt_begin_byte}b" "${cur_pt_end_byte}b" ||
(
error_msg "create new partion ${target_pt_idx} failed"
)
echo "Partition repaired"
}
# check if need fix partition
if [ "${NEW_ROOT_NAME}" == "mmcblk2p2" ]; then
if [ "${MYDEVICE_NAME}" == "Phicomm N1" ] || [ "${MYDEVICE_NAME}" == "Octopus Planet" ]; then
# 最新研究结果:
# Phicomm N1当采用官方 "天天链" 固件底包时,
# 796MB开始的 12 字节在每次重启后会被 bootloader 覆写,
# 因此把安全位置设定在800MB之后
# The latest research results:
# When Phicomm N1 uses the official "tian tian lian" firmware bottom package,
# the 12 bytes starting from 796MB will be overwritten by bootloader after each reboot,
# so the safe location is set after 800MB
SAFE_PT_BEGIN_MB=800
check_and_fix_partition "${EMMC_NAME}" "p2" 2 ${SAFE_PT_BEGIN_MB}
fi
fi
echo "Format [ ${NEW_ROOT_PATH} ]"
NEW_ROOT_UUID=$(uuidgen)
mkfs.btrfs -f -U ${NEW_ROOT_UUID} -L ${NEW_ROOT_LABEL} -m single ${NEW_ROOT_PATH}
if [ $? -ne 0 ]; then
echo "Format [ ${NEW_ROOT_PATH} ] failed!"
umount -f ${P1}
umount -f ${P2}
losetup -D
exit 1
fi
echo "Mount [ ${NEW_ROOT_PATH} ] -> [ ${NEW_ROOT_MP} ]"
mount -t btrfs -o compress=zstd:${ZSTD_LEVEL} ${NEW_ROOT_PATH} ${NEW_ROOT_MP}
if [ $? -ne 0 ]; then
echo "Mount [ ${NEW_ROOT_PATH} ] -> [ ${NEW_ROOT_MP} ] failed!"
umount -f ${P1}
umount -f ${P2}
losetup -D
exit 1
fi
# begin copy rootfs
cd ${NEW_ROOT_MP}
echo "Start copying data, From [ ${P2} ] TO [ ${NEW_ROOT_MP} ] ..."
ENTRYS=$(ls)
for entry in ${ENTRYS}; do
if [[ "${entry}" == "lost+found" ]]; then
continue
fi
echo "Remove old [ ${entry} ] ... "
rm -rf ${entry}
if [[ "${?}" -ne "0" ]]; then
error_msg "failed."
fi
done
echo "Create folder ... "
btrfs subvolume create etc
mkdir -p .snapshots .reserved bin boot dev lib opt mnt overlay proc rom root run sbin sys tmp usr www
ln -sf lib/ lib64
ln -sf tmp/ var
sync
COPY_SRC="root etc bin sbin lib opt usr www"
echo "Copy data begin ... "
for src in ${COPY_SRC}; do
echo "Copy [ ${src} ] ... "
(cd ${P2} && tar cf - ${src}) | tar xf -
sync
done
# if not backup, then force rewrite the etc/docker/daemon.json
if [ "${BR_FLAG}" -eq 0 ]; then
cat >./etc/docker/daemon.json <<EOF
{
"bip": "172.31.0.1/24",
"data-root": "${DOCKER_ROOT}",
"log-level": "warn",
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "5"
},
"registry-mirrors": [
"https://mirror.baidubce.com/",
"https://hub-mirror.c.163.com"
]
}
EOF
fi
cat >./etc/fstab <<EOF
UUID=${NEW_ROOT_UUID} / btrfs compress=zstd:${ZSTD_LEVEL} 0 1
LABEL=${LB_PRE}BOOT /boot vfat defaults 0 2
#tmpfs /tmp tmpfs defaults,nosuid 0 0
EOF
cat >./etc/config/fstab <<EOF
config global
option anon_swap '0'
option anon_mount '1'
option auto_swap '0'
option auto_mount '1'
option delay_root '5'
option check_fs '0'
config mount
option target '/rom'
option uuid '${NEW_ROOT_UUID}'
option enabled '1'
option enabled_fsck '1'
option fstype 'btrfs'
option options 'compress=zstd:${ZSTD_LEVEL}'
config mount
option target '/boot'
option label '${LB_PRE}BOOT'
option enabled '1'
option enabled_fsck '1'
option fstype 'vfat'
EOF
(
cd etc/rc.d
rm -f S??shortcut-fe
if grep "sfe_flow '1'" ../config/turboacc >/dev/null; then
if find ../../lib/modules -name 'shortcut-fe-cm.ko'; then
ln -sf ../init.d/shortcut-fe S99shortcut-fe
fi
fi
)
# move /etc/config/balance_irq to /etc/balance_irq
[ -f "./etc/config/balance_irq" ] && mv ./etc/config/balance_irq ./etc/
sync
echo "Create initial etc snapshot -> .snapshots/etc-000"
btrfs subvolume snapshot -r etc .snapshots/etc-000
sync
[ -d /mnt/${EMMC_NAME}${PARTITION_NAME}4/docker ] || mkdir -p /mnt/${EMMC_NAME}${PARTITION_NAME}4/docker
rm -rf opt/docker && ln -sf /mnt/${EMMC_NAME}${PARTITION_NAME}4/docker/ opt/docker
if [ -f /mnt/${NEW_ROOT_NAME}/etc/config/AdGuardHome ]; then
[ -d /mnt/${EMMC_NAME}${PARTITION_NAME}4/AdGuardHome/data ] || mkdir -p /mnt/${EMMC_NAME}${PARTITION_NAME}4/AdGuardHome/data
if [ ! -L /usr/bin/AdGuardHome ]; then
[ -d /usr/bin/AdGuardHome ] &&
cp -a /usr/bin/AdGuardHome/* /mnt/${EMMC_NAME}${PARTITION_NAME}4/AdGuardHome/
fi
ln -sf /mnt/${EMMC_NAME}${PARTITION_NAME}4/AdGuardHome /mnt/${NEW_ROOT_NAME}/usr/bin/AdGuardHome
fi
#rm -f /mnt/${NEW_ROOT_NAME}/usr/sbin/openwrt-install-amlogic
#rm -f /mnt/${NEW_ROOT_NAME}/usr/sbin/openwrt-update-amlogic
rm -f /mnt/${NEW_ROOT_NAME}/root/install-to-emmc.sh
sync
echo "Copy data complete ..."
BACKUP_LIST=$(${P2}/usr/sbin/openwrt-backup -p)
if [[ "${BR_FLAG}" -eq "1" && -n "${BACKUP_LIST}" ]]; then
echo -n "Start restoring configuration files ... "
(
cd /
eval tar czf ${NEW_ROOT_MP}/.reserved/openwrt_config.tar.gz "${BACKUP_LIST}" 2>/dev/null
)
tar xzf ${NEW_ROOT_MP}/.reserved/openwrt_config.tar.gz
[ -f ./etc/config/dockerman ] && sed -e "s/option wan_mode 'false'/option wan_mode 'true'/" -i ./etc/config/dockerman 2>/dev/null
[ -f ./etc/config/dockerd ] && sed -e "s/option wan_mode '0'/option wan_mode '1'/" -i ./etc/config/dockerd 2>/dev/null
[ -f ./etc/config/verysync ] && sed -e 's/config setting/config verysync/' -i ./etc/config/verysync 2>/dev/null
# Restore fstab
cp -f .snapshots/etc-000/fstab ./etc/fstab
cp -f .snapshots/etc-000/config/fstab ./etc/config/fstab
# 还原 luci
cp -f .snapshots/etc-000/config/luci ./etc/config/luci
# 还原/etc/config/rpcd
cp -f .snapshots/etc-000/config/rpcd ./etc/config/rpcd
sync
echo "Restore configuration information complete."
fi
echo "Modify the configuration file ... "
rm -f "./etc/rc.local.orig" "./etc/first_run.sh" "./etc/part_size"
rm -rf "./opt/docker" && ln -sf "/mnt/${EMMC_NAME}${PARTITION_NAME}4/docker" "./opt/docker"
rm -f ./etc/bench.log
cat >>./etc/crontabs/root <<EOF
37 5 * * * /etc/coremark.sh
EOF
sed -e 's/ttyAMA0/ttyAML0/' -i ./etc/inittab
sed -e 's/ttyS0/tty0/' -i ./etc/inittab
sss=$(date +%s)
ddd=$((sss / 86400))
sed -e "s/:0:0:99999:7:::/:${ddd}:0:99999:7:::/" -i ./etc/shadow
# Fix the problem of repeatedly adding amule entries after each upgrade
sed -e "/amule:x:/d" -i ./etc/shadow
# Fix the problem of repeatedly adding sshd entries after each upgrade of dropbear
sed -e "/sshd:x:/d" -i ./etc/shadow
if ! grep "sshd:x:22:sshd" ./etc/group >/dev/null; then
echo "sshd:x:22:sshd" >>./etc/group
fi
if ! grep "sshd:x:22:22:sshd:" ./etc/passwd >/dev/null; then
echo "sshd:x:22:22:sshd:/var/run/sshd:/bin/false" >>./etc/passwd
fi
if ! grep "sshd:x:" ./etc/shadow >/dev/null; then
echo "sshd:x:${ddd}:0:99999:7:::" >>./etc/shadow
fi
if [ "${BR_FLAG}" -eq "1" ]; then
if [ -x ./bin/bash ] && [ -f ./etc/profile.d/30-sysinfo.sh ]; then
sed -e 's/\/bin\/ash/\/bin\/bash/' -i ./etc/passwd
fi
sync
fi
sed -e "s/option hw_flow '1'/option hw_flow '0'/" -i ./etc/config/turboacc
(
cd etc/rc.d
rm -f S??shortcut-fe
if grep "sfe_flow '1'" ../config/turboacc >/dev/null; then
if find ../../lib/modules -name 'shortcut-fe-cm.ko'; then
ln -sf ../init.d/shortcut-fe S99shortcut-fe
fi
fi
)
eval tar czf .reserved/openwrt_config.tar.gz "${BACKUP_LIST}" 2>/dev/null
rm -f ./etc/part_size ./etc/first_run.sh
if [ -x ./usr/sbin/balethirq.pl ]; then
if grep "balethirq.pl" "./etc/rc.local"; then
echo "balance irq is enabled"
else
echo "enable balance irq"
sed -e "/exit/i\/usr/sbin/balethirq.pl" -i ./etc/rc.local
fi
fi
mv ./etc/rc.local ./etc/rc.local.orig
cat >"./etc/rc.local" <<EOF
if ! ls /etc/rc.d/S??dockerd >/dev/null 2>&1;then
/etc/init.d/dockerd enable
/etc/init.d/dockerd start
fi
if ! ls /etc/rc.d/S??dockerman >/dev/null 2>&1 && [ -f /etc/init.d/dockerman ];then
/etc/init.d/dockerman enable
/etc/init.d/dockerman start
fi
mv /etc/rc.local.orig /etc/rc.local
chmod 755 /etc/rc.local
exec /etc/rc.local
exit
EOF
chmod 755 ./etc/rc.local*
#Mainline U-BOOT detection
FLASH_MAINLINE_UBOOT=0
if [[ -n "${MAINLINE_UBOOT}" && -f "${P2}${MAINLINE_UBOOT}" ]]; then
cat <<EOF
----------------------------------------------------------------------------------
Found an available mainline bootloader (Mainline u-boot), you can flash into EMMC.
----------------------------------------------------------------------------------
EOF
while :; do
if [[ "${AUTO_MAINLINE_UBOOT}" == "yes" ]]; then
if [[ "${K510}" -eq "1" ]]; then
yn="y"
else
yn="n"
fi
elif [[ "${AUTO_MAINLINE_UBOOT}" == "no" ]]; then
yn="n"
else
read -p "Please choose whether to write the mainline bootloader to EMMC? y/n " yn
fi
case ${yn} in
y | Y)
FLASH_MAINLINE_UBOOT=1
break
;;
n | N)
FLASH_MAINLINE_UBOOT=0
break
;;
esac
done
fi
if [[ "${FLASH_MAINLINE_UBOOT}" -eq "1" ]]; then
echo -e "Write Mainline bootloader: [ ${MAINLINE_UBOOT} ]"
dd if=${P2}${MAINLINE_UBOOT} of=/dev/${EMMC_NAME} bs=1 count=444 conv=fsync
dd if=${P2}${MAINLINE_UBOOT} of=/dev/${EMMC_NAME} bs=512 skip=1 seek=1 conv=fsync
elif [[ -n "${ANDROID_UBOOT}" && -f "${P2}${ANDROID_UBOOT}" ]]; then
echo -e "Write Android bootloader: [ ${ANDROID_UBOOT} ]"
dd if=${P2}${ANDROID_UBOOT} of=/dev/${EMMC_NAME} bs=1 count=444 conv=fsync
dd if=${P2}${ANDROID_UBOOT} of=/dev/${EMMC_NAME} bs=512 skip=1 seek=1 conv=fsync
else
echo "Did not change the original bootloader."
fi
# move /etc/config/balance_irq to /etc/balance_irq
[ -f "./etc/config/balance_irq" ] && mv ./etc/config/balance_irq ./etc/
echo "Create etc snapshot -> .snapshots/etc-001"
btrfs subvolume snapshot -r etc .snapshots/etc-001
cd ${WORK_DIR}
echo "Change the label of ${BOOT_PATH} ... "
fatlabel ${BOOT_PATH} "${LB_PRE}BOOT"
echo "Start copying data, from [ ${P1} ] to [ /boot ] ..."
cd /boot
echo "Delete the old boot file ..."
rm -rf * && sync
echo "Copy the new boot file ... "
(cd ${P1} && tar cf - .) | tar xf - 2>/dev/null
sync
if [ -f ${P1}/uInitrd ]; then
i=1
max_try=10
while [ "${i}" -le "${max_try}" ]; do
uInitrd_original=$(md5sum ${P1}/uInitrd | awk '{print $1}')
uInitrd_new=$(md5sum uInitrd | awk '{print $1}')
if [ "${uInitrd_original}" = "${uInitrd_new}" ]; then
break
else
rm -f uInitrd && sync
cp -f ${P1}/uInitrd uInitrd 2>/dev/null && sync
let i++
continue
fi
done
[ "${i}" -eq "10" ] && error_msg "uInitrd file copy failed."
else
echo "uInitrd file is missing."
fi
if [ -f ${P1}/zImage ]; then
i=1
max_try=10
while [ "${i}" -le "${max_try}" ]; do
zImage_original=$(md5sum ${P1}/zImage | awk '{print $1}')
zImage_new=$(md5sum zImage | awk '{print $1}')
if [ "${zImage_original}" = "${zImage_new}" ]; then
break
else
rm -f zImage && sync
cp -f ${P1}/zImage zImage 2>/dev/null && sync
let i++
continue
fi
done
[ "${i}" -eq "10" ] && error_msg "zImage file copy failed."
else
error_msg "zImage file is missing."
fi
if [ ${ROOT_DISK_TYPE} == "EMMC" ]; then
rm -f s905_autoscript* aml_autoscript*
mv -f boot-emmc.ini boot.ini
mv -f boot-emmc.cmd boot.cmd
mv -f boot-emmc.scr boot.scr
fi
if [ "${K510}" -eq "1" ]; then
if [ -f "u-boot.ext" ]; then
cp -vf u-boot.ext u-boot.emmc
elif [ -f ${P1}/${UBOOT_OVERLOAD} ]; then
cp -vf ${P1}/${UBOOT_OVERLOAD} ${UBOOT_OVERLOAD}
cp -vf ${P1}/${UBOOT_OVERLOAD} u-boot.ext
cp -vf ${P1}/${UBOOT_OVERLOAD} u-boot.emmc
chmod +x u-boot*
fi
else
rm -f u-boot.ext 2>/dev/null
rm -f u-boot.emmc 2>/dev/null
fi
sync
echo "Update boot parameters ... "
if [ -f /tmp/uEnv.txt ]; then
lines=$(wc -l </tmp/uEnv.txt)
lines=$((lines - 1))
head -n $lines /tmp/uEnv.txt >uEnv.txt
cat >>uEnv.txt <<EOF
APPEND=root=UUID=${NEW_ROOT_UUID} rootfstype=btrfs rootflags=compress=zstd:${ZSTD_LEVEL} console=ttyAML0,115200n8 console=tty0 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1
EOF
else
cat >uEnv.txt <<EOF
LINUX=/zImage
INITRD=/uInitrd
FDT=${CUR_FDTFILE}
APPEND=root=UUID=${NEW_ROOT_UUID} rootfstype=btrfs rootflags=compress=zstd:${ZSTD_LEVEL} console=ttyAML0,115200n8 console=tty0 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1
EOF
fi
sync
# Replace the UUID for extlinux/extlinux.conf if it exists
[[ -f "extlinux/extlinux.conf" ]] && {
sed -i -E "s|UUID=[^ ]*|UUID=${NEW_ROOT_UUID}|" extlinux/extlinux.conf 2>/dev/null
}
cd $WORK_DIR
umount -f ${P1} ${P2} 2>/dev/null
losetup -D 2>/dev/null
rm -rf ${P1} ${P2} 2>/dev/null
rm -f ${IMG_NAME} 2>/dev/null
rm -f sha256sums 2>/dev/null
sync
wait
echo "Successfully updated, automatic restarting..."
sleep 3
reboot
exit 0
|
2929004360/ruoyi-sign
| 4,737
|
ruoyi-framework/src/main/java/com/ruoyi/framework/config/DruidConfig.java
|
package com.ruoyi.framework.config;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.config.properties.DruidProperties;
import com.ruoyi.framework.datasource.DynamicDataSource;
/**
* druid 配置多数据源
*
* @author ruoyi
*/
@Configuration
public class DruidConfig
{
@Bean
@ConfigurationProperties("spring.datasource.druid.master")
public DataSource masterDataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slave")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
public DataSource slaveDataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource)
{
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource");
return new DynamicDataSource(masterDataSource, targetDataSources);
}
/**
* 设置数据源
*
* @param targetDataSources 备选数据源集合
* @param sourceName 数据源名称
* @param beanName bean名称
*/
public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName)
{
try
{
DataSource dataSource = SpringUtils.getBean(beanName);
targetDataSources.put(sourceName, dataSource);
}
catch (Exception e)
{
}
}
/**
* 去除监控页面底部的广告
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
@ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties)
{
// 获取web监控页面的参数
DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
// 提取common.js的配置路径
String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
final String filePath = "support/http/resources/js/common.js";
// 创建filter进行过滤
Filter filter = new Filter()
{
@Override
public void init(javax.servlet.FilterConfig filterConfig) throws ServletException
{
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
chain.doFilter(request, response);
// 重置缓冲区,响应头不会被重置
response.resetBuffer();
// 获取common.js
String text = Utils.readFromResource(filePath);
// 正则替换banner, 除去底部的广告信息
text = text.replaceAll("<a.*?banner\"></a><br/>", "");
text = text.replaceAll("powered.*?shrek.wang</a>", "");
response.getWriter().write(text);
}
@Override
public void destroy()
{
}
};
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(filter);
registrationBean.addUrlPatterns(commonJsPattern);
return registrationBean;
}
}
|
2929004360/ruoyi-sign
| 3,795
|
ruoyi-framework/src/main/java/com/ruoyi/framework/config/CaptchaConfig.java
|
package com.ruoyi.framework.config;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import static com.google.code.kaptcha.Constants.*;
/**
* 验证码配置
*
* @author ruoyi
*/
@Configuration
public class CaptchaConfig
{
@Bean(name = "captchaProducer")
public DefaultKaptcha getKaptchaBean()
{
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 是否有边框 默认为true 我们可以自己设置yes,no
properties.setProperty(KAPTCHA_BORDER, "yes");
// 验证码文本字符颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");
// 验证码图片宽度 默认为200
properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
// 验证码图片高度 默认为50
properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
// 验证码文本字符大小 默认为40
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38");
// KAPTCHA_SESSION_KEY
properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode");
// 验证码文本字符长度 默认为5
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
// 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
// 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
@Bean(name = "captchaProducerMath")
public DefaultKaptcha getKaptchaBeanMath()
{
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 是否有边框 默认为true 我们可以自己设置yes,no
properties.setProperty(KAPTCHA_BORDER, "yes");
// 边框颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90");
// 验证码文本字符颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
// 验证码图片宽度 默认为200
properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
// 验证码图片高度 默认为50
properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
// 验证码文本字符大小 默认为40
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35");
// KAPTCHA_SESSION_KEY
properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath");
// 验证码文本生成器
properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "com.ruoyi.framework.config.KaptchaTextCreator");
// 验证码文本字符间距 默认为2
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3");
// 验证码文本字符长度 默认为5
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6");
// 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
// 验证码噪点颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_NOISE_COLOR, "white");
// 干扰实现类
properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
// 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
|
2929004360/ruoyi-sign
| 5,596
|
ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java
|
package com.ruoyi.framework.config;
import com.ruoyi.framework.config.properties.PermitAllUrlProperties;
import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;
/**
* spring security配置
*
* @author ruoyi
*/
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Configuration
public class SecurityConfig {
/**
* 自定义用户认证逻辑
*/
@Autowired
private UserDetailsService userDetailsService;
/**
* 认证失败处理类
*/
@Autowired
private AuthenticationEntryPointImpl unauthorizedHandler;
/**
* 退出处理类
*/
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
/**
* token认证过滤器
*/
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
/**
* 跨域过滤器
*/
@Autowired
private CorsFilter corsFilter;
/**
* 允许匿名访问的地址
*/
@Autowired
private PermitAllUrlProperties permitAllUrl;
/**
* 身份验证实现
*/
@Bean
public AuthenticationManager authenticationManager() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
return new ProviderManager(daoAuthenticationProvider);
}
/**
* anyRequest | 匹配所有请求路径
* access | SpringEl表达式结果为true时可以访问
* anonymous | 匿名可以访问
* denyAll | 用户不能访问
* fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录)
* hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问
* hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问
* hasAuthority | 如果有参数,参数表示权限,则其权限可以访问
* hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
* hasRole | 如果有参数,参数表示角色,则其角色可以访问
* permitAll | 用户可以任意访问
* rememberMe | 允许通过remember-me登录的用户访问
* authenticated | 用户登录后可访问
*/
@Bean
protected SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
// CSRF禁用,因为不使用session
.csrf(csrf -> csrf.disable())
// 禁用HTTP响应标头
.headers((headersCustomizer) -> {
headersCustomizer.cacheControl(cache -> cache.disable()).frameOptions(options -> options.sameOrigin());
})
// 认证失败处理类
.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
// 基于token,所以不需要session
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// 注解标记允许匿名访问的url
.authorizeHttpRequests((requests) -> {
permitAllUrl.getUrls().forEach(url -> requests.antMatchers(url).permitAll());
// 对于登录login 注册register 验证码captchaImage 允许匿名访问
requests.antMatchers("/login", "/register", "/captchaImage").permitAll()
// 静态资源,可匿名访问
.antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
.antMatchers("/doc.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
.antMatchers("/monitor/shutdown").permitAll()
.antMatchers("/websocket/**").permitAll()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
})
// 添加Logout filter
.logout(logout -> logout.logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler))
// 添加JWT filter
.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
// 添加CORS filter
.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class)
.addFilterBefore(corsFilter, LogoutFilter.class)
.build();
}
/**
* 强散列哈希加密实现
*/
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
|
2929004360/ruoyi-sign
| 1,027
|
ruoyi-framework/src/main/java/com/ruoyi/framework/manager/AsyncManager.java
|
package com.ruoyi.framework.manager;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.common.utils.spring.SpringUtils;
/**
* 异步任务管理器
*
* @author ruoyi
*/
public class AsyncManager
{
/**
* 操作延迟10毫秒
*/
private final int OPERATE_DELAY_TIME = 10;
/**
* 异步操作任务调度线程池
*/
private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
/**
* 单例模式
*/
private AsyncManager(){}
private static AsyncManager me = new AsyncManager();
public static AsyncManager me()
{
return me;
}
/**
* 执行任务
*
* @param task 任务
*/
public void execute(TimerTask task)
{
executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
}
/**
* 停止任务线程池
*/
public void shutdown()
{
Threads.shutdownAndAwaitTermination(executor);
}
}
|
281677160/openwrt-package
| 8,809
|
luci-app-amlogic/root/usr/share/amlogic/amlogic_check_kernel.sh
|
#!/bin/bash
#==================================================================
# This file is licensed under the terms of the GNU General Public
# License version 2. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.
#
# This file is a part of the luci-app-amlogic plugin
# https://github.com/ophub/luci-app-amlogic
#
# Description: Check and update OpenWrt Kernel
# Copyright (C) 2021- https://github.com/unifreq/openwrt_packit
# Copyright (C) 2021- https://github.com/ophub/luci-app-amlogic
#==================================================================
# Set a fixed value
check_option="${1}"
download_version="${2}"
TMP_CHECK_DIR="/tmp/amlogic"
AMLOGIC_SOC_FILE="/etc/flippy-openwrt-release"
START_LOG="${TMP_CHECK_DIR}/amlogic_check_kernel.log"
RUNNING_LOG="${TMP_CHECK_DIR}/amlogic_running_script.log"
LOG_FILE="${TMP_CHECK_DIR}/amlogic.log"
support_platform=("allwinner" "rockchip" "amlogic" "qemu-aarch64")
LOGTIME="$(date "+%Y-%m-%d %H:%M:%S")"
[[ -d ${TMP_CHECK_DIR} ]] || mkdir -p ${TMP_CHECK_DIR}
# Clean the running log
clean_running() {
echo -e '' >${RUNNING_LOG} 2>/dev/null && sync
}
# Add log
tolog() {
echo -e "${1}" >${START_LOG}
echo -e "${LOGTIME} ${1}" >>${LOG_FILE}
[[ -n "${2}" && "${2}" -eq "1" ]] && clean_running && exit 1
}
# Get the partition name of the root file system
get_root_partition_name() {
local paths=("/" "/overlay" "/rom")
local partition_name
for path in "${paths[@]}"; do
partition_name=$(df "${path}" | awk 'NR==2 {print $1}' | awk -F '/' '{print $3}')
[[ -n "${partition_name}" ]] && break
done
[[ -z "${partition_name}" ]] && tolog "Cannot find the root partition!" "1"
echo "${partition_name}"
}
# Check running scripts, prohibit running concurrently
this_running_log="2@Kernel update in progress, try again later!"
running_script="$(cat ${RUNNING_LOG} 2>/dev/null | xargs)"
if [[ -n "${running_script}" ]]; then
run_num="$(echo "${running_script}" | awk -F "@" '{print $1}')"
run_log="$(echo "${running_script}" | awk -F "@" '{print $2}')"
fi
if [[ -n "${run_log}" && "${run_num}" -ne "2" ]]; then
echo -e "${run_log}" >${START_LOG} 2>/dev/null && sync && exit 1
else
echo -e "${this_running_log}" >${RUNNING_LOG} 2>/dev/null && sync
fi
# Find the partition where root is located
ROOT_PTNAME="$(get_root_partition_name)"
# Find the disk where the partition is located, only supports mmcblk?p? sd?? hd?? vd?? and other formats
case "${ROOT_PTNAME}" in
mmcblk?p[1-4])
EMMC_NAME="$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}')"
PARTITION_NAME="p"
;;
[hsv]d[a-z][1-4])
EMMC_NAME="$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-1)}')"
PARTITION_NAME=""
;;
nvme?n?p[1-4])
EMMC_NAME="$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}')"
PARTITION_NAME="p"
;;
*)
tolog "Unable to recognize the disk type of ${ROOT_PTNAME}!" "1"
;;
esac
# Set the default download path
KERNEL_DOWNLOAD_PATH="/mnt/${EMMC_NAME}${PARTITION_NAME}4"
# Check release file
if [[ -s "${AMLOGIC_SOC_FILE}" ]]; then
source "${AMLOGIC_SOC_FILE}" 2>/dev/null
PLATFORM="${PLATFORM}"
SOC="${SOC}"
KERNEL_TAGS="${KERNEL_TAGS}"
else
tolog "${AMLOGIC_SOC_FILE} file is missing!" "1"
fi
if [[ -z "${PLATFORM}" || -z "$(echo "${support_platform[@]}" | grep -w "${PLATFORM}")" || -z "${SOC}" ]]; then
tolog "Missing [ PLATFORM ] value in ${AMLOGIC_SOC_FILE} file." "1"
fi
tolog "PLATFORM: [ ${PLATFORM} ], SOC: [ ${SOC} ], Use in [ ${EMMC_NAME} ]"
sleep 2
# Step 1. Set the kernel query api
tolog "01. Start checking the kernel version."
firmware_repo="$(uci get amlogic.config.amlogic_firmware_repo 2>/dev/null)"
[[ -n "${firmware_repo}" ]] || tolog "01.01 The custom kernel download repo is invalid." "1"
kernel_repo="$(uci get amlogic.config.amlogic_kernel_path 2>/dev/null)"
[[ -n "${kernel_repo}" ]] || tolog "01.02 The custom kernel download repo is invalid." "1"
if [[ "${kernel_repo}" == "opt/kernel" ]]; then
uci set amlogic.config.amlogic_kernel_path="${firmware_repo}" 2>/dev/null
uci commit amlogic 2>/dev/null
kernel_repo="${firmware_repo}"
fi
# Convert kernel repo to api format
[[ "${kernel_repo}" =~ ^https: ]] && kernel_repo="$(echo ${kernel_repo} | awk -F'/' '{print $4"/"$5}')"
kernel_api="https://github.com/${kernel_repo}"
if [[ -n "${KERNEL_TAGS}" ]]; then
kernel_tag="${KERNEL_TAGS}"
else
if [[ "${SOC}" == "rk3588" ]]; then
kernel_tag="rk3588"
elif [[ "${SOC}" == "rk3528" ]]; then
kernel_tag="rk35xx"
else
kernel_tag="stable"
fi
fi
# Remove the kernel_ prefix
kernel_tag="${kernel_tag/kernel_/}"
# If the kernel tag is a number, it is converted to a stable branch
[[ "${kernel_tag}" =~ ^[1-9]+ ]] && kernel_tag="stable"
# Step 2: Check if there is the latest kernel version
check_kernel() {
# 02. Query local version information
tolog "02. Start checking the kernel version."
# 02.01 Query the current version
if [[ "${kernel_tag}" == "rk3588" || "${kernel_tag}" == "rk35xx" ]]; then
current_kernel_v=$(uname -r 2>/dev/null)
else
current_kernel_v=$(uname -r 2>/dev/null | grep -oE '^[1-9]\.[0-9]{1,2}\.[0-9]+')
fi
[[ -n "${current_kernel_v}" ]] || tolog "02.01 The current kernel version is not detected." "1"
tolog "02.01 current version: ${current_kernel_v}"
sleep 2
# 02.02 Version comparison
main_line_version="$(echo ${current_kernel_v} | awk -F '.' '{print $1"."$2}')"
# 02.03 Query the selected branch in the settings
server_kernel_branch="$(uci get amlogic.config.amlogic_kernel_branch 2>/dev/null | grep -oE '^[1-9].[0-9]{1,3}')"
if [[ -z "${server_kernel_branch}" ]]; then
server_kernel_branch="${main_line_version}"
uci set amlogic.config.amlogic_kernel_branch="${main_line_version}" 2>/dev/null
uci commit amlogic 2>/dev/null
fi
if [[ "${server_kernel_branch}" != "${main_line_version}" ]]; then
main_line_version="${server_kernel_branch}"
main_line_now="0"
tolog "02.02 Select branch: ${main_line_version}"
sleep 2
fi
# Check the version on the server
latest_version="$(
curl -fsSL -m 10 \
${kernel_api}/releases/expanded_assets/kernel_${kernel_tag} |
grep -oE "${main_line_version}\.[0-9]+\.tar\.gz" | sed 's/.tar.gz//' |
sort -urV | head -n 1
)"
[[ -n "${latest_version}" ]] || tolog "02.03 No kernel available, please use another kernel branch." "1"
tolog "02.03 current version: ${current_kernel_v}, Latest version: ${latest_version}"
sleep 2
if [[ "${latest_version}" == "${current_kernel_v}" ]]; then
tolog "02.04 Already the latest version, no need to update." "1"
sleep 2
else
tolog '<input type="button" class="cbi-button cbi-button-reload" value="Download" onclick="return b_check_kernel(this, '"'download_${latest_version}'"')"/> Latest version: '${latest_version}'' "1"
fi
exit 0
}
# Step 3: Download the latest kernel version
download_kernel() {
tolog "03. Start download the kernels."
if [[ "${download_version}" == "download_"* ]]; then
download_version="$(echo "${download_version}" | cut -d '_' -f2)"
tolog "03.01 The kernel version: ${download_version}, downloading..."
else
tolog "03.02 Invalid parameter" "1"
fi
# Delete other residual kernel files
rm -f ${KERNEL_DOWNLOAD_PATH}/*.tar.gz
rm -f ${KERNEL_DOWNLOAD_PATH}/sha256sums
rm -rf ${KERNEL_DOWNLOAD_PATH}/${download_version}*
kernel_down_from="https://github.com/${kernel_repo}/releases/download/kernel_${kernel_tag}/${download_version}.tar.gz"
curl -fsSL "${kernel_down_from}" -o ${KERNEL_DOWNLOAD_PATH}/${download_version}.tar.gz
[[ "${?}" -ne "0" ]] && tolog "03.03 The kernel download failed." "1"
tar -xf ${KERNEL_DOWNLOAD_PATH}/${download_version}.tar.gz -C ${KERNEL_DOWNLOAD_PATH}
[[ "${?}" -ne "0" ]] && tolog "03.04 Kernel decompression failed." "1"
mv -f ${KERNEL_DOWNLOAD_PATH}/${download_version}/* ${KERNEL_DOWNLOAD_PATH}/
sync && sleep 3
# Delete the downloaded kernel file
rm -f ${KERNEL_DOWNLOAD_PATH}/${download_version}.tar.gz
rm -rf ${KERNEL_DOWNLOAD_PATH}/${download_version}
tolog "03.05 The kernel is ready, you can update."
sleep 2
#echo '<a href="javascript:;" onclick="return amlogic_kernel(this)">Update</a>' >$START_LOG
tolog '<input type="button" class="cbi-button cbi-button-reload" value="Update" onclick="return amlogic_kernel(this)"/>' "1"
exit 0
}
getopts 'cd' opts
case "${opts}" in
c | check)
check_kernel
;;
* | download)
download_kernel
;;
esac
|
281677160/openwrt-package
| 6,593
|
luci-app-amlogic/root/usr/share/amlogic/amlogic_check_plugin.sh
|
#!/bin/bash
#==================================================================
# This file is licensed under the terms of the GNU General Public
# License version 2. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.
#
# This file is a part of the luci-app-amlogic plugin
# https://github.com/ophub/luci-app-amlogic
#
# Description: Check and update luci-app-amlogic plugin
# Copyright (C) 2021- https://github.com/unifreq/openwrt_packit
# Copyright (C) 2021- https://github.com/ophub/luci-app-amlogic
#==================================================================
# Set a fixed value
TMP_CHECK_DIR="/tmp/amlogic"
AMLOGIC_SOC_FILE="/etc/flippy-openwrt-release"
START_LOG="${TMP_CHECK_DIR}/amlogic_check_plugin.log"
RUNNING_LOG="${TMP_CHECK_DIR}/amlogic_running_script.log"
LOG_FILE="${TMP_CHECK_DIR}/amlogic.log"
support_platform=("allwinner" "rockchip" "amlogic" "qemu-aarch64")
LOGTIME="$(date "+%Y-%m-%d %H:%M:%S")"
[[ -d ${TMP_CHECK_DIR} ]] || mkdir -p ${TMP_CHECK_DIR}
rm -f ${TMP_CHECK_DIR}/*.ipk 2>/dev/null && sync
rm -f ${TMP_CHECK_DIR}/sha256sums 2>/dev/null && sync
# Clean the running log
clean_running() {
echo -e '' >${RUNNING_LOG} 2>/dev/null && sync
}
# Add log
tolog() {
echo -e "${1}" >${START_LOG}
echo -e "${LOGTIME} ${1}" >>${LOG_FILE}
[[ -n "${2}" && "${2}" -eq "1" ]] && clean_running && exit 1
}
# Check running scripts, prohibit running concurrently
this_running_log="1@Plugin update in progress, try again later!"
running_script="$(cat ${RUNNING_LOG} 2>/dev/null | xargs)"
if [[ -n "${running_script}" ]]; then
run_num="$(echo "${running_script}" | awk -F "@" '{print $1}')"
run_log="$(echo "${running_script}" | awk -F "@" '{print $2}')"
fi
if [[ -n "${run_log}" && "${run_num}" -ne "1" ]]; then
echo -e "${run_log}" >${START_LOG} 2>/dev/null && sync && exit 1
else
echo -e "${this_running_log}" >${RUNNING_LOG} 2>/dev/null && sync
fi
# Check release file
if [[ -s "${AMLOGIC_SOC_FILE}" ]]; then
source "${AMLOGIC_SOC_FILE}" 2>/dev/null
PLATFORM="${PLATFORM}"
SOC="${SOC}"
else
tolog "${AMLOGIC_SOC_FILE} file is missing!" "1"
fi
if [[ -z "${PLATFORM}" || -z "$(echo "${support_platform[@]}" | grep -w "${PLATFORM}")" || -z "${SOC}" ]]; then
tolog "Missing [ PLATFORM ] value in ${AMLOGIC_SOC_FILE} file." "1"
fi
tolog "PLATFORM: [ ${PLATFORM} ], SOC: [ ${SOC} ]"
sleep 2
# 01. Query local version information
tolog "01. Query current version information."
# If neither opkg nor apk found, set package_manager to empty
package_manager=""
current_plugin_v=""
if command -v opkg >/dev/null 2>&1; then
# System has opkg
package_manager="ipk"
# Important: Add cut to handle versions like X.Y.Z-r1, ensuring consistent output
current_plugin_v="$(opkg list-installed | grep '^luci-app-amlogic' | awk '{print $3}' | cut -d'-' -f1)"
elif command -v apk >/dev/null 2>&1; then
# System has apk
package_manager="apk"
current_plugin_v="$(apk list --installed | grep '^luci-app-amlogic' | awk '{print $1}' | cut -d'-' -f4)"
fi
# Check if we successfully found the plugin
if [[ -z "${package_manager}" || -z "${current_plugin_v}" ]]; then
tolog "01.01 Plugin 'luci-app-amlogic' not found or package manager unknown." "1"
else
tolog "01.01 Using [${package_manager}]. Current version: ${current_plugin_v}"
fi
sleep 2
# 02. Check the version on the server
tolog "02. Start querying plugin version..."
# Get the latest version
latest_version="$(
curl -fsSL -m 10 \
https://github.com/ophub/luci-app-amlogic/releases |
grep -oE 'expanded_assets/[0-9]+.[0-9]+.[0-9]+(-[0-9]+)?' | sed 's|expanded_assets/||g' |
sort -urV | head -n 1
)"
if [[ -z "${latest_version}" ]]; then
tolog "02.01 Query failed, please try again." "1"
else
tolog "02.01 current version: ${current_plugin_v}, Latest version: ${latest_version}"
sleep 2
fi
# Compare the version and download the latest version
if [[ "${current_plugin_v}" == "${latest_version}" ]]; then
tolog "02.02 Already the latest version, no need to update." "1"
else
tolog "02.03 New version found. Preparing to download for [${package_manager}]..."
download_repo="https://github.com/ophub/luci-app-amlogic/releases/download"
# Intelligent File Discovery
plugin_file_name=""
lang_file_name=""
# Method 1: Use GitHub API if 'jq' is installed (Preferred Method)
if command -v jq >/dev/null 2>&1; then
tolog "Using GitHub API with jq to find package files."
api_url="https://api.github.com/repos/ophub/luci-app-amlogic/releases/tags/${latest_version}"
# Fetch all asset names from the API
asset_list="$(curl -fsSL -m 15 "${api_url}" | jq -r '.assets[].name' | xargs)"
if [[ -n "${asset_list}" ]]; then
# Discover exact filenames using regular expressions from the asset list
plugin_file_name="$(echo "${asset_list}" | tr ' ' '\n' | grep -oE "^luci-app-amlogic.*${package_manager}$" | head -n 1)"
lang_file_name="$(echo "${asset_list}" | tr ' ' '\n' | grep -oE "^luci-i18n-amlogic-zh-cn.*${package_manager}$" | head -n 1)"
else
tolog "Warning: Failed to fetch data from GitHub API." "1"
fi
else
tolog "jq not found, Aborting." "1"
fi
# Validation and Download
if [[ -z "${plugin_file_name}" || -z "${lang_file_name}" ]]; then
tolog "02.03.2 Could not discover plugin(.${package_manager}) in the release. Aborting." "1"
fi
tolog "Found plugin file: ${plugin_file_name}"
tolog "Found language file: ${lang_file_name}"
plugin_full_url="${download_repo}/${latest_version}/${plugin_file_name}"
lang_full_url="${download_repo}/${latest_version}/${lang_file_name}"
# Download the language pack
tolog "02.04 Downloading language pack..."
curl -fsSL "${lang_full_url}" -o "${TMP_CHECK_DIR}/${lang_file_name}"
if [[ "${?}" -ne "0" ]]; then
tolog "02.04 Language pack download failed." "1"
fi
# Download the main plugin file
tolog "02.05 Downloading main plugin..."
curl -fsSL "${plugin_full_url}" -o "${TMP_CHECK_DIR}/${plugin_file_name}"
if [[ "${?}" -ne "0" ]]; then
tolog "02.05 Plugin download failed." "1"
fi
sync && sleep 2
fi
tolog "03. The plug is ready, you can update."
sleep 2
#echo '<a href=upload>Update</a>' >$START_LOG
tolog '<input type="button" class="cbi-button cbi-button-reload" value="Update" onclick="return amlogic_plugin(this)"/> Latest version: '${latest_version}'' "1"
exit 0
|
2929004360/ruoyi-sign
| 1,759
|
ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/RepeatSubmitInterceptor.java
|
package com.ruoyi.framework.interceptor;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
/**
* 防止重复提交拦截器
*
* @author ruoyi
*/
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor
{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
if (handler instanceof HandlerMethod)
{
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
if (annotation != null)
{
if (this.isRepeatSubmit(request, annotation))
{
AjaxResult ajaxResult = AjaxResult.error(annotation.message());
ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
return false;
}
}
return true;
}
else
{
return true;
}
}
/**
* 验证是否重复提交由子类实现具体的防重复提交的规则
*
* @param request 请求信息
* @param annotation 防重复注解参数
* @return 结果
* @throws Exception
*/
public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);
}
|
281677160/openwrt-package
| 11,626
|
luci-app-amlogic/root/usr/share/amlogic/amlogic_check_firmware.sh
|
#!/bin/bash
#==================================================================
# This file is licensed under the terms of the GNU General Public
# License version 2. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.
#
# This file is a part of the luci-app-amlogic plugin
# https://github.com/ophub/luci-app-amlogic
#
# Description: Check and update OpenWrt firmware
# Copyright (C) 2021- https://github.com/unifreq/openwrt_packit
# Copyright (C) 2021- https://github.com/ophub/luci-app-amlogic
#==================================================================
# Set a fixed value
check_option="${1}"
download_version="${2}"
TMP_CHECK_DIR="/tmp/amlogic"
AMLOGIC_SOC_FILE="/etc/flippy-openwrt-release"
START_LOG="${TMP_CHECK_DIR}/amlogic_check_firmware.log"
RUNNING_LOG="${TMP_CHECK_DIR}/amlogic_running_script.log"
LOG_FILE="${TMP_CHECK_DIR}/amlogic.log"
support_platform=("allwinner" "rockchip" "amlogic" "qemu-aarch64")
LOGTIME="$(date "+%Y-%m-%d %H:%M:%S")"
[[ -d ${TMP_CHECK_DIR} ]] || mkdir -p ${TMP_CHECK_DIR}
# Clean the running log
clean_running() {
echo -e '' >${RUNNING_LOG} 2>/dev/null && sync
}
# Add log
tolog() {
echo -e "${1}" >${START_LOG}
echo -e "${LOGTIME} ${1}" >>${LOG_FILE}
[[ -n "${2}" && "${2}" -eq "1" ]] && clean_running && exit 1
}
# Get the partition name of the root file system
get_root_partition_name() {
local paths=("/" "/overlay" "/rom")
local partition_name
for path in "${paths[@]}"; do
partition_name=$(df "${path}" | awk 'NR==2 {print $1}' | awk -F '/' '{print $3}')
[[ -n "${partition_name}" ]] && break
done
[[ -z "${partition_name}" ]] && tolog "Cannot find the root partition!" "1"
echo "${partition_name}"
}
# Check running scripts, prohibit running concurrently
this_running_log="3@OpenWrt update in progress, try again later!"
running_script="$(cat ${RUNNING_LOG} 2>/dev/null | xargs)"
if [[ -n "${running_script}" ]]; then
run_num="$(echo "${running_script}" | awk -F "@" '{print $1}')"
run_log="$(echo "${running_script}" | awk -F "@" '{print $2}')"
fi
if [[ -n "${run_log}" && "${run_num}" -ne "3" ]]; then
echo -e "${run_log}" >${START_LOG} 2>/dev/null && sync && exit 1
else
echo -e "${this_running_log}" >${RUNNING_LOG} 2>/dev/null && sync
fi
# Find the partition where root is located
ROOT_PTNAME="$(get_root_partition_name)"
# Find the disk where the partition is located, only supports mmcblk?p? sd?? hd?? vd?? and other formats
case "${ROOT_PTNAME}" in
mmcblk?p[1-4])
EMMC_NAME="$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}')"
PARTITION_NAME="p"
;;
[hsv]d[a-z][1-4])
EMMC_NAME="$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-1)}')"
PARTITION_NAME=""
;;
nvme?n?p[1-4])
EMMC_NAME="$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}')"
PARTITION_NAME="p"
;;
*)
tolog "Unable to recognize the disk type of ${ROOT_PTNAME}!" "1"
;;
esac
# Set the default download path
FIRMWARE_DOWNLOAD_PATH="/mnt/${EMMC_NAME}${PARTITION_NAME}4"
[ -d "${FIRMWARE_DOWNLOAD_PATH}/.luci-app-amlogic" ] || mkdir -p "${FIRMWARE_DOWNLOAD_PATH}/.luci-app-amlogic"
# Check release file
if [[ -s "${AMLOGIC_SOC_FILE}" ]]; then
source "${AMLOGIC_SOC_FILE}" 2>/dev/null
PLATFORM="${PLATFORM}"
SOC="${SOC}"
BOARD="${BOARD}"
else
tolog "${AMLOGIC_SOC_FILE} file is missing!" "1"
fi
if [[ -z "${PLATFORM}" || -z "$(echo "${support_platform[@]}" | grep -w "${PLATFORM}")" || -z "${SOC}" || -z "${BOARD}" ]]; then
tolog "Missing [ PLATFORM / SOC / BOARD ] value in ${AMLOGIC_SOC_FILE} file." "1"
fi
tolog "PLATFORM: [ ${PLATFORM} ], BOARD: [ ${BOARD} ], Use in [ ${EMMC_NAME} ]"
sleep 2
# 01. Query local version information
tolog "01. Query version information..."
# 01.01 Query the current version
current_kernel_v="$(uname -r 2>/dev/null | grep -oE '^[1-9].[0-9]{1,3}.[0-9]+')"
tolog "01.01 current version: ${current_kernel_v}"
sleep 2
# 01.01 Version comparison
main_line_version="$(echo ${current_kernel_v} | awk -F '.' '{print $1"."$2}')"
# 01.02. Query the selected branch in the settings
server_kernel_branch="$(uci get amlogic.config.amlogic_kernel_branch 2>/dev/null | grep -oE '^[1-9].[0-9]{1,3}')"
if [[ -z "${server_kernel_branch}" ]]; then
server_kernel_branch="${main_line_version}"
uci set amlogic.config.amlogic_kernel_branch="${main_line_version}" 2>/dev/null
uci commit amlogic 2>/dev/null
fi
if [[ "${server_kernel_branch}" != "${main_line_version}" ]]; then
main_line_version="${server_kernel_branch}"
tolog "01.02 Select branch: ${main_line_version}"
sleep 2
fi
# 01.03. Download server version documentation
server_firmware_url="$(uci get amlogic.config.amlogic_firmware_repo 2>/dev/null)"
[[ ! -z "${server_firmware_url}" ]] || tolog "01.03 The custom firmware download repo is invalid." "1"
releases_tag_keywords="$(uci get amlogic.config.amlogic_firmware_tag 2>/dev/null)"
[[ ! -z "${releases_tag_keywords}" ]] || tolog "01.04 The custom firmware tag keywords is invalid." "1"
firmware_suffix="$(uci get amlogic.config.amlogic_firmware_suffix 2>/dev/null)"
[[ ! -z "${firmware_suffix}" ]] || tolog "01.05 The custom firmware suffix is invalid." "1"
if [[ "${server_firmware_url}" == http* ]]; then
server_firmware_url="${server_firmware_url#*com\/}"
fi
# 02. Check Updated
check_updated() {
tolog "02.01 Search for tags in the first 5 pages of releases..."
# Get the tags list
firmware_tags_array=()
for i in {1..5}; do
while IFS= read -r firmware_tags_name; do
firmware_tags_name="$(echo "${firmware_tags_name}" | sed 's/releases\/tag\///g')"
if [[ -n "${firmware_tags_name}" ]]; then
firmware_tags_array+=("${firmware_tags_name}")
fi
done < <(
curl -fsSL -m 10 \
https://github.com/${server_firmware_url}/releases?page=${i} |
grep -oE 'releases/tag/([^" ]+)'
)
done
if [[ "${#firmware_tags_array[*]}" -eq "0" ]]; then
tolog "02.01.01 Unable to retrieve a list of firmware tags." "1"
fi
tolog "02.02 Search for tags containing the keyword..."
# Search for tags containing the keyword
for i in "${firmware_tags_array[@]}"; do
if [[ "${i}" == *"${releases_tag_keywords}"* ]]; then
firmware_releases_tag="${i}"
break
fi
done
if [[ -n "${firmware_releases_tag}" ]]; then
tolog "02.02.01 Tags: ${firmware_releases_tag}"
sleep 2
else
tolog "02.02.01 No matching tags found." "1"
fi
tolog "02.03 Start searching for firmware download links..."
# Retrieve the HTML code of the tags list page
html_code="$(
curl -fsSL -m 10 \
https://github.com/${server_firmware_url}/releases/expanded_assets/${firmware_releases_tag}
)"
# Set the regular expression for the OpenWrt filename
op_file_pattern=".*_${BOARD}_.*k${main_line_version}\..*${firmware_suffix}"
# Find the <li> list item where the OpenWrt file is located
li_block=$(awk -v pattern="${op_file_pattern}" -v RS='</li>' '$0 ~ pattern { print $0 "</li>"; exit }' <<<"${html_code}")
[[ -z "${li_block}" ]] && tolog "02.03.01 No matching download links found." "1"
# Find the OpenWrt filename
latest_url=$(echo "${li_block}" | grep -o "/[^\"]*_${BOARD}_.*k${main_line_version}\.[^\"']*${firmware_suffix}" | sort -urV | head -n 1 | xargs basename 2>/dev/null)
tolog "02.03.02 OpenWrt file: ${latest_url}"
# Find the date of the latest update
latest_updated_at=$(echo "${li_block}" | grep -o 'datetime="[^"]*"' | sed 's/datetime="//; s/"//')
tolog "02.03.03 Latest updated at: ${latest_updated_at}"
# Format the date for display
date_display_format="$(echo ${latest_updated_at} | tr 'T' '(' | tr 'Z' ')')"
[[ -z "${latest_url}" || -z "${latest_updated_at}" ]] && tolog "02.03.04 The download URL or date is invalid." "1"
# Check the firmware update code
down_check_code="${latest_updated_at}.${main_line_version}"
op_release_code="${FIRMWARE_DOWNLOAD_PATH}/.luci-app-amlogic/op_release_code"
if [[ -s "${op_release_code}" ]]; then
update_check_code="$(cat ${op_release_code} | xargs)"
if [[ -n "${update_check_code}" && "${update_check_code}" == "${down_check_code}" ]]; then
tolog "02.03.05 Already the latest version, no need to update." "1"
fi
fi
# Prompt to update
if [[ -n "${latest_url}" ]]; then
tolog '<input type="button" class="cbi-button cbi-button-reload" value="Download" onclick="return b_check_firmware(this, '"'download_${latest_updated_at}@${firmware_releases_tag}/${latest_url}'"')"/> Latest updated: '${date_display_format}'' "1"
else
tolog "02.04 No OpenWrt available, please use another kernel branch." "1"
fi
exit 0
}
# 03. Download Openwrt firmware
download_firmware() {
tolog "03. Download Openwrt firmware..."
# Get the openwrt firmware download path
if [[ "${download_version}" == "download_"* ]]; then
tolog "03.01 Start downloading..."
else
tolog "03.02 Invalid parameter." "1"
fi
# Delete other residual firmware files
rm -f ${FIRMWARE_DOWNLOAD_PATH}/*${firmware_suffix} 2>/dev/null && sync
rm -f ${FIRMWARE_DOWNLOAD_PATH}/*.img 2>/dev/null && sync
rm -f ${FIRMWARE_DOWNLOAD_PATH}/sha256sums 2>/dev/null && sync
# OpenWrt make data
latest_updated_at="$(echo ${download_version} | awk -F'@' '{print $1}' | sed -e s'|download_||'g)"
down_check_code="${latest_updated_at}.${main_line_version}"
# Download firmware
opfile_path="$(echo ${download_version} | awk -F'@' '{print $2}')"
# Restore converted characters in file names(%2B to +)
firmware_download_oldname="${opfile_path//%2B/+}"
latest_url="https://github.com/${server_firmware_url}/releases/download/${firmware_download_oldname}"
# Download to OpenWrt file
firmware_download_name="openwrt_${BOARD}_k${main_line_version}_github${firmware_suffix}"
curl -fsSL "${latest_url}" -o "${FIRMWARE_DOWNLOAD_PATH}/${firmware_download_name}"
if [[ "$?" -eq "0" && -s "${FIRMWARE_DOWNLOAD_PATH}/${firmware_download_name}" ]]; then
tolog "03.01 OpenWrt downloaded successfully."
else
tolog "03.02 OpenWrt download failed." "1"
fi
# Download sha256sums file
if curl -fsSL "${latest_url}.sha" -o "${FIRMWARE_DOWNLOAD_PATH}/sha256sums" 2>/dev/null; then
tolog "03.03 sha file downloaded successfully."
# If there is a sha256sum file, compare it
releases_firmware_sha256sums="$(cat ${FIRMWARE_DOWNLOAD_PATH}/sha256sums | grep ${firmware_download_oldname##*/} | awk '{print $1}')"
download_firmware_sha256sums="$(sha256sum ${FIRMWARE_DOWNLOAD_PATH}/${firmware_download_name} | awk '{print $1}')"
if [[ -n "${releases_firmware_sha256sums}" && "${releases_firmware_sha256sums}" != "${download_firmware_sha256sums}" ]]; then
tolog "03.04 sha256sum verification mismatched." "1"
else
tolog "03.05 sha256sum verification succeeded."
fi
fi
sync && sleep 3
tolog "You can update."
tolog '<input type="button" class="cbi-button cbi-button-reload" value="Update" onclick="return amlogic_update(this, '"'${firmware_download_name}@${down_check_code}@${FIRMWARE_DOWNLOAD_PATH}'"')"/>' "1"
exit 0
}
getopts 'cd' opts
case "${opts}" in
c | check)
check_updated
;;
* | download)
download_firmware
;;
esac
|
2929004360/ruoyi-sign
| 6,450
|
ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java
|
package com.ruoyi.framework.aspectj;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.context.PermissionContextHolder;
/**
* 数据过滤处理
*
* @author ruoyi
*/
@Aspect
@Component
public class DataScopeAspect
{
/**
* 全部数据权限
*/
public static final String DATA_SCOPE_ALL = "1";
/**
* 自定数据权限
*/
public static final String DATA_SCOPE_CUSTOM = "2";
/**
* 部门数据权限
*/
public static final String DATA_SCOPE_DEPT = "3";
/**
* 部门及以下数据权限
*/
public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";
/**
* 仅本人数据权限
*/
public static final String DATA_SCOPE_SELF = "5";
/**
* 数据权限过滤关键字
*/
public static final String DATA_SCOPE = "dataScope";
@Before("@annotation(controllerDataScope)")
public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable
{
clearDataScope(point);
handleDataScope(point, controllerDataScope);
}
protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope)
{
// 获取当前的用户
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNotNull(loginUser))
{
SysUser currentUser = loginUser.getUser();
// 如果是超级管理员,则不过滤数据
if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())
{
String permission = StringUtils.defaultIfEmpty(controllerDataScope.permission(), PermissionContextHolder.getContext());
dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), controllerDataScope.userAlias(), permission);
}
}
}
/**
* 数据范围过滤
*
* @param joinPoint 切点
* @param user 用户
* @param deptAlias 部门别名
* @param userAlias 用户别名
* @param permission 权限字符
*/
public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias, String permission)
{
StringBuilder sqlString = new StringBuilder();
List<String> conditions = new ArrayList<String>();
List<String> scopeCustomIds = new ArrayList<String>();
user.getRoles().forEach(role -> {
if (DATA_SCOPE_CUSTOM.equals(role.getDataScope()) && StringUtils.equals(role.getStatus(), UserConstants.ROLE_NORMAL) && StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission)))
{
scopeCustomIds.add(Convert.toStr(role.getRoleId()));
}
});
for (SysRole role : user.getRoles())
{
String dataScope = role.getDataScope();
if (conditions.contains(dataScope) || StringUtils.equals(role.getStatus(), UserConstants.ROLE_DISABLE))
{
continue;
}
if (!StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission)))
{
continue;
}
if (DATA_SCOPE_ALL.equals(dataScope))
{
sqlString = new StringBuilder();
conditions.add(dataScope);
break;
}
else if (DATA_SCOPE_CUSTOM.equals(dataScope))
{
if (scopeCustomIds.size() > 1)
{
// 多个自定数据权限使用in查询,避免多次拼接。
sqlString.append(StringUtils.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id in ({}) ) ", deptAlias, String.join(",", scopeCustomIds)));
}
else
{
sqlString.append(StringUtils.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, role.getRoleId()));
}
}
else if (DATA_SCOPE_DEPT.equals(dataScope))
{
sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
}
else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope))
{
sqlString.append(StringUtils.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", deptAlias, user.getDeptId(), user.getDeptId()));
}
else if (DATA_SCOPE_SELF.equals(dataScope))
{
if (StringUtils.isNotBlank(userAlias))
{
sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
}
else
{
// 数据权限为仅本人且没有userAlias别名不查询任何数据
sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));
}
}
conditions.add(dataScope);
}
// 角色都不包含传递过来的权限字符,这个时候sqlString也会为空,所以要限制一下,不查询任何数据
if (StringUtils.isEmpty(conditions))
{
sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));
}
if (StringUtils.isNotBlank(sqlString.toString()))
{
Object params = joinPoint.getArgs()[0];
if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
{
BaseEntity baseEntity = (BaseEntity) params;
baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
}
}
}
/**
* 拼接权限sql前先清空params.dataScope参数防止注入
*/
private void clearDataScope(final JoinPoint joinPoint)
{
Object params = joinPoint.getArgs()[0];
if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
{
BaseEntity baseEntity = (BaseEntity) params;
baseEntity.getParams().put(DATA_SCOPE, "");
}
}
}
|
2929004360/ruoyi-sign
| 8,655
|
ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/LogAspect.java
|
package com.ruoyi.framework.aspectj;
import java.util.Collection;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.enums.HttpMethod;
import com.ruoyi.common.filter.PropertyPreExcludeFilter;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.SysOperLog;
/**
* 操作日志记录处理
*
* @author ruoyi
*/
@Aspect
@Component
public class LogAspect
{
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
/** 排除敏感属性字段 */
public static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" };
/** 计算操作消耗时间 */
private static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<Long>("Cost Time");
/**
* 处理请求前执行
*/
@Before(value = "@annotation(controllerLog)")
public void boBefore(JoinPoint joinPoint, Log controllerLog)
{
TIME_THREADLOCAL.set(System.currentTimeMillis());
}
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult)
{
handleLog(joinPoint, controllerLog, null, jsonResult);
}
/**
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e)
{
handleLog(joinPoint, controllerLog, e, null);
}
protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult)
{
try
{
// 获取当前的用户
LoginUser loginUser = SecurityUtils.getLoginUser();
// *========数据库日志=========*//
SysOperLog operLog = new SysOperLog();
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
// 请求的地址
String ip = IpUtils.getIpAddr();
operLog.setOperIp(ip);
operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
if (loginUser != null)
{
operLog.setOperName(loginUser.getUsername());
SysUser currentUser = loginUser.getUser();
if (StringUtils.isNotNull(currentUser) && StringUtils.isNotNull(currentUser.getDept()))
{
operLog.setDeptName(currentUser.getDept().getDeptName());
}
}
if (e != null)
{
operLog.setStatus(BusinessStatus.FAIL.ordinal());
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 设置请求方式
operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
// 处理设置注解上的参数
getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
// 设置消耗时间
operLog.setCostTime(System.currentTimeMillis() - TIME_THREADLOCAL.get());
// 保存数据库
AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
}
catch (Exception exp)
{
// 记录本地异常日志
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
finally
{
TIME_THREADLOCAL.remove();
}
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param log 日志
* @param operLog 操作日志
* @throws Exception
*/
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception
{
// 设置action动作
operLog.setBusinessType(log.businessType().ordinal());
// 设置标题
operLog.setTitle(log.title());
// 设置操作人类别
operLog.setOperatorType(log.operatorType().ordinal());
// 是否需要保存request,参数和值
if (log.isSaveRequestData())
{
// 获取参数的信息,传入到数据库中。
setRequestValue(joinPoint, operLog, log.excludeParamNames());
}
// 是否需要保存response,参数和值
if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult))
{
operLog.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
}
}
/**
* 获取请求的参数,放到log中
*
* @param operLog 操作日志
* @throws Exception 异常
*/
private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog, String[] excludeParamNames) throws Exception
{
Map<?, ?> paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest());
String requestMethod = operLog.getRequestMethod();
if (StringUtils.isEmpty(paramsMap) && StringUtils.equalsAny(requestMethod, HttpMethod.PUT.name(), HttpMethod.POST.name(), HttpMethod.DELETE.name()))
{
String params = argsArrayToString(joinPoint.getArgs(), excludeParamNames);
operLog.setOperParam(StringUtils.substring(params, 0, 2000));
}
else
{
operLog.setOperParam(StringUtils.substring(JSON.toJSONString(paramsMap, excludePropertyPreFilter(excludeParamNames)), 0, 2000));
}
}
/**
* 参数拼装
*/
private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames)
{
String params = "";
if (paramsArray != null && paramsArray.length > 0)
{
for (Object o : paramsArray)
{
if (StringUtils.isNotNull(o) && !isFilterObject(o))
{
try
{
String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter(excludeParamNames));
params += jsonObj.toString() + " ";
}
catch (Exception e)
{
}
}
}
}
return params.trim();
}
/**
* 忽略敏感属性
*/
public PropertyPreExcludeFilter excludePropertyPreFilter(String[] excludeParamNames)
{
return new PropertyPreExcludeFilter().addExcludes(ArrayUtils.addAll(EXCLUDE_PROPERTIES, excludeParamNames));
}
/**
* 判断是否需要过滤的对象。
*
* @param o 对象信息。
* @return 如果是需要过滤的对象,则返回true;否则返回false。
*/
@SuppressWarnings("rawtypes")
public boolean isFilterObject(final Object o)
{
Class<?> clazz = o.getClass();
if (clazz.isArray())
{
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
}
else if (Collection.class.isAssignableFrom(clazz))
{
Collection collection = (Collection) o;
for (Object value : collection)
{
return value instanceof MultipartFile;
}
}
else if (Map.class.isAssignableFrom(clazz))
{
Map map = (Map) o;
for (Object value : map.entrySet())
{
Map.Entry entry = (Map.Entry) value;
return entry.getValue() instanceof MultipartFile;
}
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|| o instanceof BindingResult;
}
}
|
2929004360/ruoyi-sign
| 2,014
|
ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataSourceAspect.java
|
package com.ruoyi.framework.aspectj;
import java.util.Objects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
/**
* 多数据源处理
*
* @author ruoyi
*/
@Aspect
@Order(1)
@Component
public class DataSourceAspect
{
protected Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut("@annotation(com.ruoyi.common.annotation.DataSource)"
+ "|| @within(com.ruoyi.common.annotation.DataSource)")
public void dsPointCut()
{
}
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable
{
DataSource dataSource = getDataSource(point);
if (StringUtils.isNotNull(dataSource))
{
DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
}
try
{
return point.proceed();
}
finally
{
// 销毁数据源 在执行方法之后
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
/**
* 获取需要切换的数据源
*/
public DataSource getDataSource(ProceedingJoinPoint point)
{
MethodSignature signature = (MethodSignature) point.getSignature();
DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
if (Objects.nonNull(dataSource))
{
return dataSource;
}
return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
}
}
|
2929004360/ruoyi-sign
| 2,876
|
ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/RateLimiterAspect.java
|
package com.ruoyi.framework.aspectj;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.enums.LimitType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
/**
* 限流处理
*
* @author ruoyi
*/
@Aspect
@Component
public class RateLimiterAspect
{
private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class);
private RedisTemplate<Object, Object> redisTemplate;
private RedisScript<Long> limitScript;
@Autowired
public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate)
{
this.redisTemplate = redisTemplate;
}
@Autowired
public void setLimitScript(RedisScript<Long> limitScript)
{
this.limitScript = limitScript;
}
@Before("@annotation(rateLimiter)")
public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable
{
int time = rateLimiter.time();
int count = rateLimiter.count();
String combineKey = getCombineKey(rateLimiter, point);
List<Object> keys = Collections.singletonList(combineKey);
try
{
Long number = redisTemplate.execute(limitScript, keys, count, time);
if (StringUtils.isNull(number) || number.intValue() > count)
{
throw new ServiceException("访问过于频繁,请稍候再试");
}
log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), combineKey);
}
catch (ServiceException e)
{
throw e;
}
catch (Exception e)
{
throw new RuntimeException("服务器限流异常,请稍候再试");
}
}
public String getCombineKey(RateLimiter rateLimiter, JoinPoint point)
{
StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());
if (rateLimiter.limitType() == LimitType.IP)
{
stringBuffer.append(IpUtils.getIpAddr()).append("-");
}
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
Class<?> targetClass = method.getDeclaringClass();
stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
return stringBuffer.toString();
}
}
|
281677160/openwrt-package
| 2,508
|
luci-app-amlogic/root/etc/init.d/amlogic
|
#!/bin/sh /etc/rc.common
START=60
NAME=amlogic
uci_get_by_type() {
local ret=$(uci get $NAME.@$1[0].$2 2>/dev/null)
echo ${ret:=$3}
}
uci_set_by_type() {
uci set $NAME.@$1[0].$2=$3 2>/dev/null
uci commit $NAME
}
start() {
[ -x "/usr/sbin/fixcpufreq.pl" ] && /usr/sbin/fixcpufreq.pl && sync
local cpu_policys=$(ls /sys/devices/system/cpu/cpufreq 2>/dev/null | grep -E 'policy[0-9]{1,3}' | xargs)
if [ "${cpu_policys}" = "" ]; then
cpu_policys="policy0"
fi
config_load $NAME
for policy_name in ${cpu_policys}; do
local policy_id="${policy_name//policy/}"
# Get an optional value list for the current device
local governor_list="$(cat /sys/devices/system/cpu/cpufreq/${policy_name}/scaling_available_frequencies 2>/dev/null | xargs)"
local second_place_order="$(echo ${governor_list} | awk '{print $1}')"
local second_place_reverse="$(echo ${governor_list} | awk '{print $NF}')"
# Get the default value in the Config file
local governor=$(uci_get_by_type settings governor${policy_id} schedutil)
local minfreq=$(uci_get_by_type settings minfreq${policy_id} ${second_place_order})
local maxfreq=$(uci_get_by_type settings maxfreq${policy_id} ${second_place_reverse})
# Update result to the corresponding file
echo $governor >/sys/devices/system/cpu/cpufreq/${policy_name}/scaling_governor
echo $minfreq >/sys/devices/system/cpu/cpufreq/${policy_name}/scaling_min_freq
echo $maxfreq >/sys/devices/system/cpu/cpufreq/${policy_name}/scaling_max_freq
# If the governor is ondemand, configure its specific parameters.
if [ "$governor" = "ondemand" ]; then
local ondemand_dir="/sys/devices/system/cpu/cpufreq/${policy_name}/ondemand"
# Check if the per-policy ondemand directory exists.
if [ -d "$ondemand_dir" ]; then
# Read ondemand parameters from UCI, or use default values (e.g., 80 and 20) if not set.
local up_threshold=$(uci_get_by_type settings up_threshold${policy_id} 80)
local sampling_down_factor=$(uci_get_by_type settings sampling_down_factor${policy_id} 20)
# Write the values to the system files.
echo $up_threshold > "${ondemand_dir}/up_threshold"
echo $sampling_down_factor > "${ondemand_dir}/sampling_down_factor"
fi
fi
done
}
reload() {
start
return 0
}
|
2929004360/ruoyi-sign
| 2,671
|
ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/PermitAllUrlProperties.java
|
package com.ruoyi.framework.config.properties;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import org.apache.commons.lang3.RegExUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import com.ruoyi.common.annotation.Anonymous;
/**
* 设置Anonymous注解允许匿名访问的url
*
* @author ruoyi
*/
@Configuration
public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware
{
private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
private ApplicationContext applicationContext;
private List<String> urls = new ArrayList<>();
public String ASTERISK = "*";
@Override
public void afterPropertiesSet()
{
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
map.keySet().forEach(info -> {
HandlerMethod handlerMethod = map.get(info);
// 获取方法上边的注解 替代path variable 为 *
Anonymous method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Anonymous.class);
Optional.ofNullable(method).ifPresent(anonymous -> Objects.requireNonNull(info.getPatternsCondition().getPatterns())
.forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))));
// 获取类上边的注解, 替代path variable 为 *
Anonymous controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Anonymous.class);
Optional.ofNullable(controller).ifPresent(anonymous -> Objects.requireNonNull(info.getPatternsCondition().getPatterns())
.forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))));
});
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException
{
this.applicationContext = context;
}
public List<String> getUrls()
{
return urls;
}
public void setUrls(List<String> urls)
{
this.urls = urls;
}
}
|
2929004360/ruoyi-sign
| 2,971
|
ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/DruidProperties.java
|
package com.ruoyi.framework.config.properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
/**
* druid 配置属性
*
* @author ruoyi
*/
@Configuration
public class DruidProperties
{
@Value("${spring.datasource.druid.initialSize}")
private int initialSize;
@Value("${spring.datasource.druid.minIdle}")
private int minIdle;
@Value("${spring.datasource.druid.maxActive}")
private int maxActive;
@Value("${spring.datasource.druid.maxWait}")
private int maxWait;
@Value("${spring.datasource.druid.connectTimeout}")
private int connectTimeout;
@Value("${spring.datasource.druid.socketTimeout}")
private int socketTimeout;
@Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.maxEvictableIdleTimeMillis}")
private int maxEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.druid.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.druid.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.druid.testOnReturn}")
private boolean testOnReturn;
public DruidDataSource dataSource(DruidDataSource datasource)
{
/** 配置初始化大小、最小、最大 */
datasource.setInitialSize(initialSize);
datasource.setMaxActive(maxActive);
datasource.setMinIdle(minIdle);
/** 配置获取连接等待超时的时间 */
datasource.setMaxWait(maxWait);
/** 配置驱动连接超时时间,检测数据库建立连接的超时时间,单位是毫秒 */
datasource.setConnectTimeout(connectTimeout);
/** 配置网络超时时间,等待数据库操作完成的网络超时时间,单位是毫秒 */
datasource.setSocketTimeout(socketTimeout);
/** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
/** 配置一个连接在池中最小、最大生存的时间,单位是毫秒 */
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);
/**
* 用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
*/
datasource.setValidationQuery(validationQuery);
/** 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 */
datasource.setTestWhileIdle(testWhileIdle);
/** 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */
datasource.setTestOnBorrow(testOnBorrow);
/** 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */
datasource.setTestOnReturn(testOnReturn);
return datasource;
}
}
|
2929004360/ruoyi-sign
| 3,491
|
ruoyi-framework/src/main/java/com/ruoyi/framework/manager/factory/AsyncFactory.java
|
package com.ruoyi.framework.manager.factory;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysLogininforService;
import com.ruoyi.system.service.ISysOperLogService;
import eu.bitwalker.useragentutils.UserAgent;
/**
* 异步工厂(产生任务用)
*
* @author ruoyi
*/
public class AsyncFactory
{
private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");
/**
* 记录登录信息
*
* @param username 用户名
* @param status 状态
* @param message 消息
* @param args 列表
* @return 任务task
*/
public static TimerTask recordLogininfor(final String username, final String status, final String message,
final Object... args)
{
final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
final String ip = IpUtils.getIpAddr();
return new TimerTask()
{
@Override
public void run()
{
String address = AddressUtils.getRealAddressByIP(ip);
StringBuilder s = new StringBuilder();
s.append(LogUtils.getBlock(ip));
s.append(address);
s.append(LogUtils.getBlock(username));
s.append(LogUtils.getBlock(status));
s.append(LogUtils.getBlock(message));
// 打印信息到日志
sys_user_logger.info(s.toString(), args);
// 获取客户端操作系统
String os = userAgent.getOperatingSystem().getName();
// 获取客户端浏览器
String browser = userAgent.getBrowser().getName();
// 封装对象
SysLogininfor logininfor = new SysLogininfor();
logininfor.setUserName(username);
logininfor.setIpaddr(ip);
logininfor.setLoginLocation(address);
logininfor.setBrowser(browser);
logininfor.setOs(os);
logininfor.setMsg(message);
// 日志状态
if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
{
logininfor.setStatus(Constants.SUCCESS);
}
else if (Constants.LOGIN_FAIL.equals(status))
{
logininfor.setStatus(Constants.FAIL);
}
// 插入数据
SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
}
};
}
/**
* 操作日志记录
*
* @param operLog 操作日志信息
* @return 任务task
*/
public static TimerTask recordOper(final SysOperLog operLog)
{
return new TimerTask()
{
@Override
public void run()
{
// 远程查询操作地点
operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
}
};
}
}
|
2929004360/ruoyi-sign
| 3,687
|
ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java
|
package com.ruoyi.framework.interceptor.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.filter.RepeatedlyRequestWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpHelper;
import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor;
/**
* 判断请求url和数据是否和上一次相同,
* 如果和上次相同,则是重复提交表单。 有效时间为10秒内。
*
* @author ruoyi
*/
@Component
public class SameUrlDataInterceptor extends RepeatSubmitInterceptor
{
public final String REPEAT_PARAMS = "repeatParams";
public final String REPEAT_TIME = "repeatTime";
// 令牌自定义标识
@Value("${token.header}")
private String header;
@Autowired
private RedisCache redisCache;
@SuppressWarnings("unchecked")
@Override
public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation)
{
String nowParams = "";
if (request instanceof RepeatedlyRequestWrapper)
{
RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
nowParams = HttpHelper.getBodyString(repeatedlyRequest);
}
// body参数为空,获取Parameter的数据
if (StringUtils.isEmpty(nowParams))
{
nowParams = JSON.toJSONString(request.getParameterMap());
}
Map<String, Object> nowDataMap = new HashMap<String, Object>();
nowDataMap.put(REPEAT_PARAMS, nowParams);
nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());
// 请求地址(作为存放cache的key值)
String url = request.getRequestURI();
// 唯一值(没有消息头则使用请求地址)
String submitKey = StringUtils.trimToEmpty(request.getHeader(header));
// 唯一标识(指定key + url + 消息头)
String cacheRepeatKey = CacheConstants.REPEAT_SUBMIT_KEY + url + submitKey;
Object sessionObj = redisCache.getCacheObject(cacheRepeatKey);
if (sessionObj != null)
{
Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
if (sessionMap.containsKey(url))
{
Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval()))
{
return true;
}
}
}
Map<String, Object> cacheMap = new HashMap<String, Object>();
cacheMap.put(url, nowDataMap);
redisCache.setCacheObject(cacheRepeatKey, cacheMap, annotation.interval(), TimeUnit.MILLISECONDS);
return false;
}
/**
* 判断参数是否相同
*/
private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap)
{
String nowParams = (String) nowMap.get(REPEAT_PARAMS);
String preParams = (String) preMap.get(REPEAT_PARAMS);
return nowParams.equals(preParams);
}
/**
* 判断两次间隔时间
*/
private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap, int interval)
{
long time1 = (Long) nowMap.get(REPEAT_TIME);
long time2 = (Long) preMap.get(REPEAT_TIME);
if ((time1 - time2) < interval)
{
return true;
}
return false;
}
}
|
281677160/openwrt-package
| 2,320
|
luci-app-msd_lite/luasrc/model/cbi/msd_lite.lua
|
require ("nixio.fs")
require ("luci.sys")
require ("luci.http")
require ("luci.dispatcher")
require "luci.model.uci".cursor()
m = Map("msd_lite")
m.title = translate("Multi Stream daemon Lite")
m.description = translate("The lightweight version of Multi Stream daemon (msd) Program for organizing IP TV streaming on the network via HTTP.")
m:section(SimpleSection).template = "msd_lite/msd_lite_status"
s = m:section(TypedSection, "instance")
s.addremove = true
s.anonymous = false
s.addbtntitle = translate("Add instance")
o = s:option(Flag, "enabled", translate("Enable"))
o.default = o.disabled
o.rmempty = false
o = s:option(DynamicList, "address", translate("Bind address"))
o.datatype = "list(ipaddrport(1))"
o.rmempty = false
o = s:option(ListValue, "network", translate("Source interface"))
local x = luci.model.uci.cursor()
local net = x:get_all("network")
for interface, config in pairs(net) do
if interface ~= "loopback" and config.proto ~= nil then
o:value(interface)
end
end
o:value("", translate("Disable"))
o.default = ""
o.description = translate("For multicast receive.")
o = s:option(Value, "threads", translate("Worker threads"))
o.datatype = "uinteger"
o.default = "0"
o.description = translate("0 = auto.")
o = s:option(Flag, "bind_to_cpu", translate("Bind threads to CPUs"))
o.default = o.disabled
o = s:option(Flag, "drop_slow_clients", translate("Disconnect slow clients"))
o.default = o.disabled
o = s:option(Value, "precache_size", translate("Pre cache size"))
o.datatype = "uinteger"
o.default = "4096"
o = s:option(Value, "ring_buffer_size", translate("Ring buffer size"))
o.datatype = "uinteger"
o.default = "1024"
o.description = translate("Stream receive ring buffer size.")
o = s:option(Value, "multicast_recv_buffer_size", translate("Receive buffer size"))
o.datatype = "uinteger"
o.default = "512"
o.description = translate("Multicast receive socket buffer size.")
o = s:option(Value, "multicast_recv_timeout", translate("Receive timeout"))
o.datatype = "uinteger"
o.default = "2"
o.description = translate("Multicast receive timeout.")
o = s:option(Value, "rejoin_time", translate("IGMP/MLD rejoin time"))
o.datatype = "uinteger"
o.default = "0"
o.description = translate("Do IGMP/MLD leave+join every X seconds. Leave <em>0</em> to disable.")
return m
|
2929004360/ruoyi-sign
| 1,863
|
ruoyi-framework/src/main/java/com/ruoyi/framework/security/filter/JwtAuthenticationTokenFilter.java
|
package com.ruoyi.framework.security.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
/**
* token过滤器 验证token有效性
*
* @author ruoyi
*/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
@Autowired
private TokenService tokenService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException
{
LoginUser loginUser = tokenService.getLoginUser(request);
if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
{
tokenService.verifyToken(loginUser);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
chain.doFilter(request, response);
}
}
|
2929004360/ruoyi-sign
| 1,947
|
ruoyi-framework/src/main/java/com/ruoyi/framework/security/handle/LogoutSuccessHandlerImpl.java
|
package com.ruoyi.framework.security.handle;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
/**
* 自定义退出处理类 返回成功
*
* @author ruoyi
*/
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
@Autowired
private TokenService tokenService;
/**
* 退出处理
*
* @return
*/
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException
{
LoginUser loginUser = tokenService.getLoginUser(request);
if (StringUtils.isNotNull(loginUser))
{
String userName = loginUser.getUsername();
// 删除用户缓存记录
tokenService.delLoginUser(loginUser.getToken());
// 记录用户退出日志
AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
}
ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
}
}
|
2929004360/ruoyi-sign
| 1,214
|
ruoyi-framework/src/main/java/com/ruoyi/framework/security/handle/AuthenticationEntryPointImpl.java
|
package com.ruoyi.framework.security.handle;
import java.io.IOException;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
/**
* 认证失败处理类 返回未授权
*
* @author ruoyi
*/
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
private static final long serialVersionUID = -8970718410437077606L;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
throws IOException
{
int code = HttpStatus.UNAUTHORIZED;
String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI());
ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
}
}
|
2929004360/ruoyi-sign
| 6,846
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java
|
package com.ruoyi.framework.web.service;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
/**
* 登录校验方法
*
* @author ruoyi
*/
@Component
public class SysLoginService
{
@Autowired
private TokenService tokenService;
@Resource
private AuthenticationManager authenticationManager;
@Autowired
private RedisCache redisCache;
@Autowired
private ISysUserService userService;
@Autowired
private ISysConfigService configService;
/**
* 登录验证
*
* @param username 用户名
* @param password 密码
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public String login(String username, String password, String code, String uuid)
{
// 验证码校验
validateCaptcha(username, code, uuid);
// 登录前置校验
loginPreCheck(username, password);
// 用户验证
Authentication authentication = null;
try
{
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
AuthenticationContextHolder.setContext(authenticationToken);
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(authenticationToken);
}
catch (Exception e)
{
if (e instanceof BadCredentialsException)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
else
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
throw new ServiceException(e.getMessage());
}
}
finally
{
AuthenticationContextHolder.clearContext();
}
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
recordLoginInfo(loginUser.getUserId());
// 生成token
return tokenService.createToken(loginUser);
}
/**
* 校验验证码
*
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public void validateCaptcha(String username, String code, String uuid)
{
boolean captchaEnabled = configService.selectCaptchaEnabled();
if (captchaEnabled)
{
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
String captcha = redisCache.getCacheObject(verifyKey);
if (captcha == null)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
throw new CaptchaExpireException();
}
redisCache.deleteObject(verifyKey);
if (!code.equalsIgnoreCase(captcha))
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new CaptchaException();
}
}
}
/**
* 登录前置校验
* @param username 用户名
* @param password 用户密码
*/
public void loginPreCheck(String username, String password)
{
// 用户名或密码为空 错误
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
throw new UserNotExistsException();
}
// 密码如果不在指定范围内 错误
if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
// 用户名不在指定范围内 错误
if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|| username.length() > UserConstants.USERNAME_MAX_LENGTH)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
// IP黑名单校验
String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
throw new BlackListException();
}
}
/**
* 记录登录信息
*
* @param userId 用户ID
*/
public void recordLoginInfo(Long userId)
{
SysUser sysUser = new SysUser();
sysUser.setUserId(userId);
sysUser.setLoginIp(IpUtils.getIpAddr());
sysUser.setLoginDate(DateUtils.getNowDate());
userService.updateUserProfile(sysUser);
}
}
|
2929004360/ruoyi-sign
| 2,248
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/UserDetailsServiceImpl.java
|
package com.ruoyi.framework.web.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
/**
* 用户验证处理
*
* @author ruoyi
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
@Autowired
private ISysUserService userService;
@Autowired
private SysPasswordService passwordService;
@Autowired
private SysPermissionService permissionService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
SysUser user = userService.selectUserByUserName(username);
if (StringUtils.isNull(user))
{
log.info("登录用户:{} 不存在.", username);
throw new ServiceException(MessageUtils.message("user.not.exists"));
}
else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
{
log.info("登录用户:{} 已被删除.", username);
throw new ServiceException(MessageUtils.message("user.password.delete"));
}
else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
{
log.info("登录用户:{} 已被停用.", username);
throw new ServiceException(MessageUtils.message("user.blocked"));
}
passwordService.validate(user);
return createLoginUser(user);
}
public UserDetails createLoginUser(SysUser user)
{
return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
}
}
|
281677160/openwrt-package
| 1,262
|
luci-app-msd_lite/po/zh_Hans/msd_lite.po
|
msgid "NOT RUNNING"
msgstr "未运行"
msgid "RUNNING"
msgstr "运行中"
msgid "MultiSD_Lite"
msgstr "MultiSD_Lite"
msgid "Multi Stream daemon Lite"
msgstr "组播转换 Lite"
msgid "The lightweight version of Multi Stream daemon (msd) Program for organizing IP TV streaming on the network via HTTP."
msgstr "Multi Stream daemon (msd) 程序的轻量级版本,用于通过 HTTP 管理网络上的 IP TV 流。"
msgid "Add instance"
msgstr "添加实例"
msgid "Enable"
msgstr "启用"
msgid "Bind address"
msgstr "绑定地址"
msgid "Source interface"
msgstr "源接口"
msgid "For multicast receive."
msgstr "用于接收组播流。"
msgid "Worker threads"
msgstr "工作线程"
msgid "0 = auto."
msgstr "保留为 0 以自动检测。"
msgid "Bind threads to CPUs"
msgstr "绑定线程到 CPU"
msgid "Disconnect slow clients"
msgstr "断开慢速客户端"
msgid "Pre cache size"
msgstr "预缓存大小"
msgid "Ring buffer size"
msgstr "环形缓冲区大小"
msgid "Stream receive ring buffer size."
msgstr "流接收环形缓冲区大小。"
msgid "Receive buffer size"
msgstr "接收缓冲区大小"
msgid "Multicast receive socket buffer size."
msgstr "组播接收套接字缓冲区大小。"
msgid "Receive timeout"
msgstr "接收超时"
msgid "Multicast receive timeout."
msgstr "组播接收超时。"
msgid "Do IGMP/MLD leave+join every X seconds. Leave <em>0</em> to disable."
msgstr "每隔 X 秒执行 IGMP/MLD 退出重进。设置为 <em>0</em> 以禁用。"
msgid "IGMP/MLD rejoin time"
msgstr "IGMP/MLD 重新加入时间"
|
2929004360/ruoyi-sign
| 2,582
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPasswordService.java
|
package com.ruoyi.framework.web.service;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
/**
* 登录密码方法
*
* @author ruoyi
*/
@Component
public class SysPasswordService
{
@Autowired
private RedisCache redisCache;
@Value(value = "${user.password.maxRetryCount}")
private int maxRetryCount;
@Value(value = "${user.password.lockTime}")
private int lockTime;
/**
* 登录账户密码错误次数缓存键名
*
* @param username 用户名
* @return 缓存键key
*/
private String getCacheKey(String username)
{
return CacheConstants.PWD_ERR_CNT_KEY + username;
}
public void validate(SysUser user)
{
Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
String username = usernamePasswordAuthenticationToken.getName();
String password = usernamePasswordAuthenticationToken.getCredentials().toString();
Integer retryCount = redisCache.getCacheObject(getCacheKey(username));
if (retryCount == null)
{
retryCount = 0;
}
if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
{
throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
}
if (!matches(user, password))
{
retryCount = retryCount + 1;
redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
throw new UserPasswordNotMatchException();
}
else
{
clearLoginRecordCache(username);
}
}
public boolean matches(SysUser user, String rawPassword)
{
return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
}
public void clearLoginRecordCache(String loginName)
{
if (redisCache.hasKey(getCacheKey(loginName)))
{
redisCache.deleteObject(getCacheKey(loginName));
}
}
}
|
2929004360/ruoyi-sign
| 3,535
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysRegisterService.java
|
package com.ruoyi.framework.web.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
/**
* 注册校验方法
*
* @author ruoyi
*/
@Component
public class SysRegisterService
{
@Autowired
private ISysUserService userService;
@Autowired
private ISysConfigService configService;
@Autowired
private RedisCache redisCache;
/**
* 注册
*/
public String register(RegisterBody registerBody)
{
String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
SysUser sysUser = new SysUser();
sysUser.setUserName(username);
// 验证码开关
boolean captchaEnabled = configService.selectCaptchaEnabled();
if (captchaEnabled)
{
validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
}
if (StringUtils.isEmpty(username))
{
msg = "用户名不能为空";
}
else if (StringUtils.isEmpty(password))
{
msg = "用户密码不能为空";
}
else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|| username.length() > UserConstants.USERNAME_MAX_LENGTH)
{
msg = "账户长度必须在2到20个字符之间";
}
else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH)
{
msg = "密码长度必须在5到20个字符之间";
}
else if (!userService.checkUserNameUnique(sysUser))
{
msg = "保存用户'" + username + "'失败,注册账号已存在";
}
else
{
sysUser.setNickName(username);
sysUser.setPassword(SecurityUtils.encryptPassword(password));
boolean regFlag = userService.registerUser(sysUser);
if (!regFlag)
{
msg = "注册失败,请联系系统管理人员";
}
else
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
}
}
return msg;
}
/**
* 校验验证码
*
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public void validateCaptcha(String username, String code, String uuid)
{
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
String captcha = redisCache.getCacheObject(verifyKey);
redisCache.deleteObject(verifyKey);
if (captcha == null)
{
throw new CaptchaExpireException();
}
if (!code.equalsIgnoreCase(captcha))
{
throw new CaptchaException();
}
}
}
|
2929004360/ruoyi-sign
| 5,968
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java
|
package com.ruoyi.framework.web.service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
/**
* token验证处理
*
* @author ruoyi
*/
@Component
public class TokenService
{
private static final Logger log = LoggerFactory.getLogger(TokenService.class);
// 令牌自定义标识
@Value("${token.header}")
private String header;
// 令牌秘钥
@Value("${token.secret}")
private String secret;
// 令牌有效期(默认30分钟)
@Value("${token.expireTime}")
private int expireTime;
protected static final long MILLIS_SECOND = 1000;
protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
@Autowired
private RedisCache redisCache;
/**
* 获取用户身份信息
*
* @return 用户信息
*/
public LoginUser getLoginUser(HttpServletRequest request)
{
// 获取请求携带的令牌
String token = getToken(request);
if (StringUtils.isNotEmpty(token))
{
try
{
Claims claims = parseToken(token);
// 解析对应的权限以及用户信息
String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
String userKey = getTokenKey(uuid);
LoginUser user = redisCache.getCacheObject(userKey);
return user;
}
catch (Exception e)
{
log.error("获取用户信息异常'{}'", e.getMessage());
}
}
return null;
}
/**
* 设置用户身份信息
*/
public void setLoginUser(LoginUser loginUser)
{
if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
{
refreshToken(loginUser);
}
}
/**
* 删除用户身份信息
*/
public void delLoginUser(String token)
{
if (StringUtils.isNotEmpty(token))
{
String userKey = getTokenKey(token);
redisCache.deleteObject(userKey);
}
}
/**
* 创建令牌
*
* @param loginUser 用户信息
* @return 令牌
*/
public String createToken(LoginUser loginUser)
{
String token = IdUtils.fastUUID();
loginUser.setToken(token);
setUserAgent(loginUser);
refreshToken(loginUser);
Map<String, Object> claims = new HashMap<>();
claims.put(Constants.LOGIN_USER_KEY, token);
return createToken(claims);
}
/**
* 验证令牌有效期,相差不足20分钟,自动刷新缓存
*
* @param loginUser
* @return 令牌
*/
public void verifyToken(LoginUser loginUser)
{
long expireTime = loginUser.getExpireTime();
long currentTime = System.currentTimeMillis();
if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
{
refreshToken(loginUser);
}
}
/**
* 刷新令牌有效期
*
* @param loginUser 登录信息
*/
public void refreshToken(LoginUser loginUser)
{
loginUser.setLoginTime(System.currentTimeMillis());
loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
// 根据uuid将loginUser缓存
String userKey = getTokenKey(loginUser.getToken());
redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
}
/**
* 设置用户代理信息
*
* @param loginUser 登录信息
*/
public void setUserAgent(LoginUser loginUser)
{
UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
String ip = IpUtils.getIpAddr();
loginUser.setIpaddr(ip);
loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
loginUser.setBrowser(userAgent.getBrowser().getName());
loginUser.setOs(userAgent.getOperatingSystem().getName());
}
/**
* 从数据声明生成令牌
*
* @param claims 数据声明
* @return 令牌
*/
private String createToken(Map<String, Object> claims)
{
String token = Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret).compact();
return token;
}
/**
* 从令牌中获取数据声明
*
* @param token 令牌
* @return 数据声明
*/
private Claims parseToken(String token)
{
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
/**
* 从令牌中获取用户名
*
* @param token 令牌
* @return 用户名
*/
public String getUsernameFromToken(String token)
{
Claims claims = parseToken(token);
return claims.getSubject();
}
/**
* 获取请求token
*
* @param request
* @return token
*/
private String getToken(HttpServletRequest request)
{
String token = request.getHeader(header);
if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
{
token = token.replace(Constants.TOKEN_PREFIX, "");
}
return token;
}
private String getTokenKey(String uuid)
{
return CacheConstants.LOGIN_TOKEN_KEY + uuid;
}
}
|
2929004360/ruoyi-sign
| 2,304
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPermissionService.java
|
package com.ruoyi.framework.web.service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysRoleService;
/**
* 用户权限处理
*
* @author ruoyi
*/
@Component
public class SysPermissionService
{
@Autowired
private ISysRoleService roleService;
@Autowired
private ISysMenuService menuService;
/**
* 获取角色数据权限
*
* @param user 用户信息
* @return 角色权限信息
*/
public Set<String> getRolePermission(SysUser user)
{
Set<String> roles = new HashSet<String>();
// 管理员拥有所有权限
if (user.isAdmin())
{
roles.add("admin");
}
else
{
roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
}
return roles;
}
/**
* 获取菜单数据权限
*
* @param user 用户信息
* @return 菜单权限信息
*/
public Set<String> getMenuPermission(SysUser user)
{
Set<String> perms = new HashSet<String>();
// 管理员拥有所有权限
if (user.isAdmin())
{
perms.add("*:*:*");
}
else
{
List<SysRole> roles = user.getRoles();
if (!CollectionUtils.isEmpty(roles))
{
// 多角色设置permissions属性,以便数据权限匹配权限
for (SysRole role : roles)
{
if (StringUtils.equals(role.getStatus(), UserConstants.ROLE_NORMAL))
{
Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
role.setPermissions(rolePerms);
perms.addAll(rolePerms);
}
}
}
else
{
perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
}
}
return perms;
}
}
|
2929004360/ruoyi-sign
| 4,230
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/PermissionService.java
|
package com.ruoyi.framework.web.service;
import java.util.Set;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.context.PermissionContextHolder;
/**
* RuoYi首创 自定义权限实现,ss取自SpringSecurity首字母
*
* @author ruoyi
*/
@Service("ss")
public class PermissionService
{
/**
* 验证用户是否具备某权限
*
* @param permission 权限字符串
* @return 用户是否具备某权限
*/
public boolean hasPermi(String permission)
{
if (StringUtils.isEmpty(permission))
{
return false;
}
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions()))
{
return false;
}
PermissionContextHolder.setContext(permission);
return hasPermissions(loginUser.getPermissions(), permission);
}
/**
* 验证用户是否不具备某权限,与 hasPermi逻辑相反
*
* @param permission 权限字符串
* @return 用户是否不具备某权限
*/
public boolean lacksPermi(String permission)
{
return hasPermi(permission) != true;
}
/**
* 验证用户是否具有以下任意一个权限
*
* @param permissions 以 PERMISSION_DELIMETER 为分隔符的权限列表
* @return 用户是否具有以下任意一个权限
*/
public boolean hasAnyPermi(String permissions)
{
if (StringUtils.isEmpty(permissions))
{
return false;
}
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions()))
{
return false;
}
PermissionContextHolder.setContext(permissions);
Set<String> authorities = loginUser.getPermissions();
for (String permission : permissions.split(Constants.PERMISSION_DELIMETER))
{
if (permission != null && hasPermissions(authorities, permission))
{
return true;
}
}
return false;
}
/**
* 判断用户是否拥有某个角色
*
* @param role 角色字符串
* @return 用户是否具备某角色
*/
public boolean hasRole(String role)
{
if (StringUtils.isEmpty(role))
{
return false;
}
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles()))
{
return false;
}
for (SysRole sysRole : loginUser.getUser().getRoles())
{
String roleKey = sysRole.getRoleKey();
if (Constants.SUPER_ADMIN.equals(roleKey) || roleKey.equals(StringUtils.trim(role)))
{
return true;
}
}
return false;
}
/**
* 验证用户是否不具备某角色,与 isRole逻辑相反。
*
* @param role 角色名称
* @return 用户是否不具备某角色
*/
public boolean lacksRole(String role)
{
return hasRole(role) != true;
}
/**
* 验证用户是否具有以下任意一个角色
*
* @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表
* @return 用户是否具有以下任意一个角色
*/
public boolean hasAnyRoles(String roles)
{
if (StringUtils.isEmpty(roles))
{
return false;
}
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles()))
{
return false;
}
for (String role : roles.split(Constants.ROLE_DELIMETER))
{
if (hasRole(role))
{
return true;
}
}
return false;
}
/**
* 判断是否包含权限
*
* @param permissions 权限列表
* @param permission 权限字符串
* @return 用户是否具备某权限
*/
private boolean hasPermissions(Set<String> permissions, String permission)
{
return permissions.contains(Constants.ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
}
}
|
281677160/openwrt-package
| 2,411
|
luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js
|
'use strict';
'require form';
'require poll';
'require rpc';
'require uci';
'require view';
var callServiceList = rpc.declare({
object: 'service',
method: 'list',
params: ['name'],
expect: { '': {} }
});
function getServiceStatus() {
return L.resolveDefault(callServiceList('filebrowser'), {}).then(function (res) {
var isRunning = false;
try {
isRunning = res['filebrowser']['instances']['instance1']['running'];
} catch (e) { }
return isRunning;
});
}
function renderStatus(isRunning, port) {
var spanTemp = '<span style="color:%s"><strong>%s %s</strong></span>';
var renderHTML;
if (isRunning) {
var button = String.format(' <a class="btn cbi-button" href="http://%s:%s" target="_blank" rel="noreferrer noopener">%s</a>',
window.location.hostname, port, _('Open Web Interface'));
renderHTML = spanTemp.format('green', _('FileBrowser'), _('RUNNING')) + button;
} else {
renderHTML = spanTemp.format('red', _('FileBrowser'), _('NOT RUNNING'));
}
return renderHTML;
}
return view.extend({
load: function() {
return uci.load('filebrowser');
},
render: function(data) {
var m, s, o;
var webport = (uci.get(data, 'config', 'listen_port') || '8989');
m = new form.Map('filebrowser', _('FileBrowser'),
_('FileBrowser provides a file managing interface within a specified directory and it can be used to upload, delete, preview, rename and edit your files..'));
s = m.section(form.TypedSection);
s.anonymous = true;
s.render = function () {
poll.add(function () {
return L.resolveDefault(getServiceStatus()).then(function (res) {
var view = document.getElementById('service_status');
view.innerHTML = renderStatus(res, webport);
});
});
return E('div', { class: 'cbi-section', id: 'status_bar' }, [
E('p', { id: 'service_status' }, _('Collecting data...'))
]);
}
s = m.section(form.NamedSection, 'config', 'filebrowser');
o = s.option(form.Flag, 'enabled', _('Enable'));
o.default = o.disabled;
o.rmempty = false;
o = s.option(form.Value, 'listen_port', _('Listen port'));
o.datatype = 'port';
o.default = '8989';
o.rmempty = false;
o = s.option(form.Value, 'root_path', _('Root directory'));
o.default = '/mnt';
o.rmempty = false;
o = s.option(form.Flag, 'disable_exec', _('Disable Command Runner feature'));
o.default = o.enabled;
o.rmempty = false;
return m.render();
}
});
|
2977094657/ZsxqCrawler
| 27,038
|
zsxq_file_database.py
|
import sqlite3
from typing import Dict, List, Any, Optional
class ZSXQFileDatabase:
"""知识星球文件列表数据库管理工具 - 完全匹配API响应结构"""
def __init__(self, db_path: str = "zsxq_files_complete.db"):
"""初始化数据库连接"""
self.db_path = db_path
self.conn = sqlite3.connect(db_path, check_same_thread=False)
self.cursor = self.conn.cursor()
self.create_tables()
def create_tables(self):
"""创建所有必需的数据表 - 完全匹配API响应结构"""
# 1. API响应记录表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS api_responses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
succeeded BOOLEAN,
index_value TEXT,
files_count INTEGER,
request_url TEXT,
request_params TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 2. 文件主表 (files数组中的file对象)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS files (
file_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
hash TEXT,
size INTEGER,
duration INTEGER,
download_count INTEGER,
create_time TEXT,
imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
download_status TEXT DEFAULT 'pending',
local_path TEXT,
download_time TIMESTAMP
)
''')
# 执行数据库迁移
self._migrate_database()
# 3. 群组表 (topic.group对象)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS groups (
group_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
type TEXT,
background_url TEXT,
imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 4. 用户表 (所有用户信息的统一表)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
alias TEXT,
avatar_url TEXT,
description TEXT,
location TEXT,
ai_comment_url TEXT,
imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 5. 话题主表 (topic对象)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS topics (
topic_id INTEGER PRIMARY KEY,
group_id INTEGER,
type TEXT NOT NULL,
title TEXT,
annotation TEXT,
likes_count INTEGER DEFAULT 0,
tourist_likes_count INTEGER DEFAULT 0,
rewards_count INTEGER DEFAULT 0,
comments_count INTEGER DEFAULT 0,
reading_count INTEGER DEFAULT 0,
readers_count INTEGER DEFAULT 0,
digested BOOLEAN DEFAULT FALSE,
sticky BOOLEAN DEFAULT FALSE,
create_time TEXT,
modify_time TEXT,
user_liked BOOLEAN DEFAULT FALSE,
user_subscribed BOOLEAN DEFAULT FALSE,
imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (group_id) REFERENCES groups (group_id)
)
''')
# 6. 文件-话题关联表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS file_topic_relations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_id INTEGER,
topic_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (file_id) REFERENCES files (file_id),
FOREIGN KEY (topic_id) REFERENCES topics (topic_id)
)
''')
# 7. 话题内容表 (talk对象)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS talks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
owner_user_id INTEGER,
text TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (owner_user_id) REFERENCES users (user_id)
)
''')
# 8. 图片表 (images数组)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS images (
image_id INTEGER PRIMARY KEY,
topic_id INTEGER,
type TEXT,
thumbnail_url TEXT,
thumbnail_width INTEGER,
thumbnail_height INTEGER,
large_url TEXT,
large_width INTEGER,
large_height INTEGER,
original_url TEXT,
original_width INTEGER,
original_height INTEGER,
original_size INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id)
)
''')
# 9. 话题文件表 (talk.files数组)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS topic_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
file_id INTEGER,
name TEXT,
hash TEXT,
size INTEGER,
duration INTEGER,
download_count INTEGER,
create_time TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id)
)
''')
# 10. 最新点赞表 (latest_likes数组)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS latest_likes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
owner_user_id INTEGER,
create_time TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (owner_user_id) REFERENCES users (user_id)
)
''')
# 11. 评论表 (show_comments数组)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS comments (
comment_id INTEGER PRIMARY KEY,
topic_id INTEGER,
owner_user_id INTEGER,
parent_comment_id INTEGER,
repliee_user_id INTEGER,
text TEXT,
create_time TEXT,
likes_count INTEGER DEFAULT 0,
rewards_count INTEGER DEFAULT 0,
replies_count INTEGER DEFAULT 0,
sticky BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (owner_user_id) REFERENCES users (user_id),
FOREIGN KEY (parent_comment_id) REFERENCES comments (comment_id),
FOREIGN KEY (repliee_user_id) REFERENCES users (user_id)
)
''')
# 12. 点赞详情表情表 (likes_detail.emojis数组)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS like_emojis (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
emoji_key TEXT,
likes_count INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id)
)
''')
# 13. 用户点赞表情表 (user_specific.liked_emojis数组)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS user_liked_emojis (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
emoji_key TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id)
)
''')
# 14. 栏目表 (columns数组)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS columns (
column_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 15. 话题-栏目关联表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS topic_columns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
column_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (column_id) REFERENCES columns (column_id)
)
''')
# 16. 解决方案表 (solution对象)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS solutions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
task_id INTEGER,
owner_user_id INTEGER,
text TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (owner_user_id) REFERENCES users (user_id)
)
''')
# 17. 解决方案文件表 (solution.files数组)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS solution_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
solution_id INTEGER,
file_id INTEGER,
name TEXT,
hash TEXT,
size INTEGER,
duration INTEGER,
download_count INTEGER,
create_time TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (solution_id) REFERENCES solutions (id)
)
''')
# 18. 收集日志表 (用于记录文件收集过程)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS collection_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
start_time TEXT NOT NULL,
end_time TEXT,
total_files INTEGER DEFAULT 0,
new_files INTEGER DEFAULT 0,
status TEXT DEFAULT 'running',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
self.conn.commit()
print("✅ 完整数据库表结构创建成功")
def insert_user(self, user_data: Dict[str, Any]) -> Optional[int]:
"""插入或更新用户信息"""
if not user_data or not user_data.get('user_id'):
return None
self.cursor.execute('''
INSERT OR REPLACE INTO users
(user_id, name, alias, avatar_url, description, location, ai_comment_url)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
user_data.get('user_id'),
user_data.get('name', ''),
user_data.get('alias'),
user_data.get('avatar_url'),
user_data.get('description'),
user_data.get('location'),
user_data.get('ai_comment_url')
))
return user_data.get('user_id')
def insert_group(self, group_data: Dict[str, Any]) -> Optional[int]:
"""插入或更新群组信息"""
if not group_data or not group_data.get('group_id'):
return None
self.cursor.execute('''
INSERT OR REPLACE INTO groups
(group_id, name, type, background_url)
VALUES (?, ?, ?, ?)
''', (
group_data.get('group_id'),
group_data.get('name', ''),
group_data.get('type'),
group_data.get('background_url')
))
return group_data.get('group_id')
def insert_file(self, file_data: Dict[str, Any]) -> Optional[int]:
"""插入或更新文件信息"""
if not file_data or not file_data.get('file_id'):
return None
self.cursor.execute('''
INSERT OR REPLACE INTO files
(file_id, name, hash, size, duration, download_count, create_time)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
file_data.get('file_id'),
file_data.get('name', ''),
file_data.get('hash'),
file_data.get('size'),
file_data.get('duration'),
file_data.get('download_count'),
file_data.get('create_time')
))
return file_data.get('file_id')
def insert_topic(self, topic_data: Dict[str, Any]) -> Optional[int]:
"""插入或更新话题信息"""
if not topic_data or not topic_data.get('topic_id'):
return None
# 处理用户特定信息
user_specific = topic_data.get('user_specific', {})
self.cursor.execute('''
INSERT OR REPLACE INTO topics
(topic_id, group_id, type, title, annotation, likes_count, tourist_likes_count,
rewards_count, comments_count, reading_count, readers_count, digested, sticky,
create_time, modify_time, user_liked, user_subscribed)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
topic_data.get('topic_id'),
topic_data.get('group', {}).get('group_id'),
topic_data.get('type'),
topic_data.get('title'),
topic_data.get('annotation'),
topic_data.get('likes_count', 0),
topic_data.get('tourist_likes_count', 0),
topic_data.get('rewards_count', 0),
topic_data.get('comments_count', 0),
topic_data.get('reading_count', 0),
topic_data.get('readers_count', 0),
topic_data.get('digested', False),
topic_data.get('sticky', False),
topic_data.get('create_time'),
topic_data.get('modify_time'), # 新增字段
user_specific.get('liked', False),
user_specific.get('subscribed', False)
))
return topic_data.get('topic_id')
def insert_talk(self, topic_id: int, talk_data: Dict[str, Any]):
"""插入话题内容"""
if not talk_data:
return
owner = talk_data.get('owner', {})
owner_id = self.insert_user(owner)
self.cursor.execute('''
INSERT OR IGNORE INTO talks (topic_id, owner_user_id, text)
VALUES (?, ?, ?)
''', (topic_id, owner_id, talk_data.get('text', '')))
def insert_images(self, topic_id: int, images_data: List[Dict[str, Any]]):
"""插入图片信息"""
for image in images_data:
if not image.get('image_id'):
continue
thumbnail = image.get('thumbnail', {})
large = image.get('large', {})
original = image.get('original', {})
self.cursor.execute('''
INSERT OR REPLACE INTO images
(image_id, topic_id, type, thumbnail_url, thumbnail_width, thumbnail_height,
large_url, large_width, large_height, original_url, original_width, original_height, original_size)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
image.get('image_id'),
topic_id,
image.get('type'),
thumbnail.get('url'),
thumbnail.get('width'),
thumbnail.get('height'),
large.get('url'),
large.get('width'),
large.get('height'),
original.get('url'),
original.get('width'),
original.get('height'),
original.get('size')
))
def insert_topic_files(self, topic_id: int, files_data: List[Dict[str, Any]]):
"""插入话题关联的文件"""
for file in files_data:
if not file.get('file_id'):
continue
self.cursor.execute('''
INSERT OR REPLACE INTO topic_files
(topic_id, file_id, name, hash, size, duration, download_count, create_time)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (
topic_id,
file.get('file_id'),
file.get('name', ''),
file.get('hash'),
file.get('size'),
file.get('duration'),
file.get('download_count'),
file.get('create_time')
))
def insert_latest_likes(self, topic_id: int, likes_data: List[Dict[str, Any]]):
"""插入最新点赞记录"""
for like in likes_data:
owner = like.get('owner', {})
owner_id = self.insert_user(owner)
self.cursor.execute('''
INSERT OR IGNORE INTO latest_likes (topic_id, owner_user_id, create_time)
VALUES (?, ?, ?)
''', (topic_id, owner_id, like.get('create_time')))
def insert_comments(self, topic_id: int, comments_data: List[Dict[str, Any]]):
"""插入评论信息"""
for comment in comments_data:
if not comment.get('comment_id'):
continue
owner = comment.get('owner', {})
owner_id = self.insert_user(owner)
repliee = comment.get('repliee', {})
repliee_id = self.insert_user(repliee) if repliee else None
self.cursor.execute('''
INSERT OR REPLACE INTO comments
(comment_id, topic_id, owner_user_id, parent_comment_id, repliee_user_id,
text, create_time, likes_count, rewards_count, replies_count, sticky)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
comment.get('comment_id'),
topic_id,
owner_id,
comment.get('parent_comment_id'),
repliee_id,
comment.get('text', ''),
comment.get('create_time'),
comment.get('likes_count', 0),
comment.get('rewards_count', 0),
comment.get('replies_count', 0),
comment.get('sticky', False)
))
def insert_like_emojis(self, topic_id: int, likes_detail: Dict[str, Any]):
"""插入点赞表情详情"""
emojis = likes_detail.get('emojis', [])
for emoji in emojis:
self.cursor.execute('''
INSERT OR REPLACE INTO like_emojis (topic_id, emoji_key, likes_count)
VALUES (?, ?, ?)
''', (topic_id, emoji.get('emoji_key'), emoji.get('likes_count', 0)))
def insert_user_liked_emojis(self, topic_id: int, liked_emojis: List[str]):
"""插入用户点赞的表情"""
for emoji_key in liked_emojis:
self.cursor.execute('''
INSERT OR IGNORE INTO user_liked_emojis (topic_id, emoji_key)
VALUES (?, ?)
''', (topic_id, emoji_key))
def insert_columns(self, topic_id: int, columns_data: List[Dict[str, Any]]):
"""插入栏目信息"""
for column in columns_data:
if not column.get('column_id'):
continue
# 插入栏目
self.cursor.execute('''
INSERT OR REPLACE INTO columns (column_id, name)
VALUES (?, ?)
''', (column.get('column_id'), column.get('name', '')))
# 插入话题-栏目关联
self.cursor.execute('''
INSERT OR IGNORE INTO topic_columns (topic_id, column_id)
VALUES (?, ?)
''', (topic_id, column.get('column_id')))
def insert_solution(self, topic_id: int, solution_data: Dict[str, Any]):
"""插入解决方案信息"""
if not solution_data:
return None
owner = solution_data.get('owner', {})
owner_id = self.insert_user(owner)
self.cursor.execute('''
INSERT OR REPLACE INTO solutions (topic_id, task_id, owner_user_id, text)
VALUES (?, ?, ?, ?)
''', (
topic_id,
solution_data.get('task_id'),
owner_id,
solution_data.get('text', '')
))
solution_id = self.cursor.lastrowid
# 插入解决方案文件
files = solution_data.get('files', [])
for file in files:
self.cursor.execute('''
INSERT OR REPLACE INTO solution_files
(solution_id, file_id, name, hash, size, duration, download_count, create_time)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (
solution_id,
file.get('file_id'),
file.get('name', ''),
file.get('hash'),
file.get('size'),
file.get('duration'),
file.get('download_count'),
file.get('create_time')
))
return solution_id
def import_file_response(self, response_data: Dict[str, Any]) -> Dict[str, int]:
"""导入文件API响应数据"""
stats = {
'files': 0,
'topics': 0,
'users': 0,
'groups': 0,
'images': 0,
'comments': 0,
'likes': 0,
'columns': 0,
'solutions': 0
}
try:
# 记录API响应
files_data = response_data.get('resp_data', {}).get('files', [])
self.cursor.execute('''
INSERT INTO api_responses (succeeded, index_value, files_count)
VALUES (?, ?, ?)
''', (
response_data.get('succeeded', False),
response_data.get('resp_data', {}).get('index'),
len(files_data)
))
# 处理每个文件和关联的话题
for item in files_data:
file_data = item.get('file', {})
topic_data = item.get('topic', {})
if not file_data.get('file_id') or not topic_data.get('topic_id'):
continue
# 插入文件
file_id = self.insert_file(file_data)
if file_id:
stats['files'] += 1
# 插入群组
group_data = topic_data.get('group', {})
if group_data:
group_id = self.insert_group(group_data)
if group_id:
stats['groups'] += 1
# 插入话题
topic_id = self.insert_topic(topic_data)
if topic_id:
stats['topics'] += 1
# 插入文件-话题关联
self.cursor.execute('''
INSERT OR IGNORE INTO file_topic_relations (file_id, topic_id)
VALUES (?, ?)
''', (file_id, topic_id))
# 处理talk信息
talk_data = topic_data.get('talk', {})
if talk_data:
self.insert_talk(topic_id, talk_data)
# 处理talk中的图片
images = talk_data.get('images', [])
if images:
self.insert_images(topic_id, images)
stats['images'] += len(images)
# 处理talk中的文件
topic_files = talk_data.get('files', [])
if topic_files:
self.insert_topic_files(topic_id, topic_files)
# 处理最新点赞
latest_likes = topic_data.get('latest_likes', [])
if latest_likes:
self.insert_latest_likes(topic_id, latest_likes)
stats['likes'] += len(latest_likes)
# 处理评论
comments = topic_data.get('show_comments', [])
if comments:
self.insert_comments(topic_id, comments)
stats['comments'] += len(comments)
# 处理点赞详情
likes_detail = topic_data.get('likes_detail', {})
if likes_detail:
self.insert_like_emojis(topic_id, likes_detail)
# 处理用户点赞表情
user_specific = topic_data.get('user_specific', {})
liked_emojis = user_specific.get('liked_emojis', [])
if liked_emojis:
self.insert_user_liked_emojis(topic_id, liked_emojis)
# 处理栏目
columns = topic_data.get('columns', [])
if columns:
self.insert_columns(topic_id, columns)
stats['columns'] += len(columns)
# 处理解决方案
solution = topic_data.get('solution', {})
if solution:
solution_id = self.insert_solution(topic_id, solution)
if solution_id:
stats['solutions'] += 1
self.conn.commit()
print(f"✅ 数据导入成功: {stats}")
return stats
except Exception as e:
self.conn.rollback()
print(f"❌ 数据导入失败: {e}")
raise e
def get_database_stats(self) -> Dict[str, Any]:
"""获取数据库统计信息"""
stats = {}
tables = [
'files', 'groups', 'users', 'topics', 'talks', 'images',
'topic_files', 'latest_likes', 'comments', 'like_emojis',
'user_liked_emojis', 'columns', 'topic_columns', 'solutions',
'solution_files', 'file_topic_relations', 'api_responses', 'collection_log'
]
for table in tables:
self.cursor.execute(f"SELECT COUNT(*) FROM {table}")
stats[table] = self.cursor.fetchone()[0]
return stats
def _migrate_database(self):
"""执行数据库迁移,添加新列"""
migrations = [
{
'table': 'files',
'column': 'download_status',
'definition': 'TEXT DEFAULT "pending"'
},
{
'table': 'files',
'column': 'local_path',
'definition': 'TEXT'
},
{
'table': 'files',
'column': 'download_time',
'definition': 'TIMESTAMP'
}
]
for migration in migrations:
try:
# 检查列是否存在
self.cursor.execute(f"PRAGMA table_info({migration['table']})")
columns = [column[1] for column in self.cursor.fetchall()]
if migration['column'] not in columns:
sql = f"ALTER TABLE {migration['table']} ADD COLUMN {migration['column']} {migration['definition']}"
self.cursor.execute(sql)
print(f"📊 添加列: {migration['table']}.{migration['column']}")
except Exception as e:
print(f"❌ 迁移失败: {migration['table']}.{migration['column']} - {e}")
self.conn.commit()
def close(self):
"""关闭数据库连接"""
if self.conn:
self.conn.close()
def main():
"""测试数据库功能"""
db = ZSXQFileDatabase()
print("📊 数据库统计:")
stats = db.get_database_stats()
for table, count in stats.items():
print(f" {table}: {count}")
db.close()
if __name__ == "__main__":
main()
|
2929004360/ruoyi-sign
| 5,011
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java
|
package com.ruoyi.framework.web.exception;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.DemoModeException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.html.EscapeUtil;
/**
* 全局异常处理器
*
* @author ruoyi
*/
@RestControllerAdvice
public class GlobalExceptionHandler
{
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 权限校验异常
*/
@ExceptionHandler(AccessDeniedException.class)
public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request)
{
String requestURI = request.getRequestURI();
log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权");
}
/**
* 请求方式不支持
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
HttpServletRequest request)
{
String requestURI = request.getRequestURI();
log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
return AjaxResult.error(e.getMessage());
}
/**
* 业务异常
*/
@ExceptionHandler(ServiceException.class)
public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request)
{
log.error(e.getMessage(), e);
Integer code = e.getCode();
return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
}
/**
* 请求路径中缺少必需的路径变量
*/
@ExceptionHandler(MissingPathVariableException.class)
public AjaxResult handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request)
{
String requestURI = request.getRequestURI();
log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);
return AjaxResult.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
}
/**
* 请求参数类型不匹配
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public AjaxResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request)
{
String requestURI = request.getRequestURI();
String value = Convert.toStr(e.getValue());
if (StringUtils.isNotEmpty(value))
{
value = EscapeUtil.clean(value);
}
log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
return AjaxResult.error(String.format("请求参数类型不匹配,参数[%s]要求类型为:'%s',但输入值为:'%s'", e.getName(), e.getRequiredType().getName(), value));
}
/**
* 拦截未知的运行时异常
*/
@ExceptionHandler(RuntimeException.class)
public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request)
{
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生未知异常.", requestURI, e);
return AjaxResult.error(e.getMessage());
}
/**
* 系统异常
*/
@ExceptionHandler(Exception.class)
public AjaxResult handleException(Exception e, HttpServletRequest request)
{
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生系统异常.", requestURI, e);
return AjaxResult.error(e.getMessage());
}
/**
* 自定义验证异常
*/
@ExceptionHandler(BindException.class)
public AjaxResult handleBindException(BindException e)
{
log.error(e.getMessage(), e);
String message = e.getAllErrors().get(0).getDefaultMessage();
return AjaxResult.error(message);
}
/**
* 自定义验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
{
log.error(e.getMessage(), e);
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return AjaxResult.error(message);
}
/**
* 演示模式异常
*/
@ExceptionHandler(DemoModeException.class)
public AjaxResult handleDemoModeException(DemoModeException e)
{
return AjaxResult.error("演示模式,不允许操作");
}
}
|
2929004360/ruoyi-sign
| 6,255
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/Server.java
|
package com.ruoyi.framework.web.domain;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.web.domain.server.Cpu;
import com.ruoyi.framework.web.domain.server.Jvm;
import com.ruoyi.framework.web.domain.server.Mem;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.framework.web.domain.server.SysFile;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;
/**
* 服务器相关信息
*
* @author ruoyi
*/
public class Server
{
private static final int OSHI_WAIT_SECOND = 1000;
/**
* CPU相关信息
*/
private Cpu cpu = new Cpu();
/**
* 內存相关信息
*/
private Mem mem = new Mem();
/**
* JVM相关信息
*/
private Jvm jvm = new Jvm();
/**
* 服务器相关信息
*/
private Sys sys = new Sys();
/**
* 磁盘相关信息
*/
private List<SysFile> sysFiles = new LinkedList<SysFile>();
public Cpu getCpu()
{
return cpu;
}
public void setCpu(Cpu cpu)
{
this.cpu = cpu;
}
public Mem getMem()
{
return mem;
}
public void setMem(Mem mem)
{
this.mem = mem;
}
public Jvm getJvm()
{
return jvm;
}
public void setJvm(Jvm jvm)
{
this.jvm = jvm;
}
public Sys getSys()
{
return sys;
}
public void setSys(Sys sys)
{
this.sys = sys;
}
public List<SysFile> getSysFiles()
{
return sysFiles;
}
public void setSysFiles(List<SysFile> sysFiles)
{
this.sysFiles = sysFiles;
}
public void copyTo() throws Exception
{
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
setCpuInfo(hal.getProcessor());
setMemInfo(hal.getMemory());
setSysInfo();
setJvmInfo();
setSysFiles(si.getOperatingSystem());
}
/**
* 设置CPU信息
*/
private void setCpuInfo(CentralProcessor processor)
{
// CPU信息
long[] prevTicks = processor.getSystemCpuLoadTicks();
Util.sleep(OSHI_WAIT_SECOND);
long[] ticks = processor.getSystemCpuLoadTicks();
long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
cpu.setCpuNum(processor.getLogicalProcessorCount());
cpu.setTotal(totalCpu);
cpu.setSys(cSys);
cpu.setUsed(user);
cpu.setWait(iowait);
cpu.setFree(idle);
}
/**
* 设置内存信息
*/
private void setMemInfo(GlobalMemory memory)
{
mem.setTotal(memory.getTotal());
mem.setUsed(memory.getTotal() - memory.getAvailable());
mem.setFree(memory.getAvailable());
}
/**
* 设置服务器信息
*/
private void setSysInfo()
{
Properties props = System.getProperties();
sys.setComputerName(IpUtils.getHostName());
sys.setComputerIp(IpUtils.getHostIp());
sys.setOsName(props.getProperty("os.name"));
sys.setOsArch(props.getProperty("os.arch"));
sys.setUserDir(props.getProperty("user.dir"));
}
/**
* 设置Java虚拟机
*/
private void setJvmInfo() throws UnknownHostException
{
Properties props = System.getProperties();
jvm.setTotal(Runtime.getRuntime().totalMemory());
jvm.setMax(Runtime.getRuntime().maxMemory());
jvm.setFree(Runtime.getRuntime().freeMemory());
jvm.setVersion(props.getProperty("java.version"));
jvm.setHome(props.getProperty("java.home"));
}
/**
* 设置磁盘信息
*/
private void setSysFiles(OperatingSystem os)
{
FileSystem fileSystem = os.getFileSystem();
List<OSFileStore> fsArray = fileSystem.getFileStores();
for (OSFileStore fs : fsArray)
{
long free = fs.getUsableSpace();
long total = fs.getTotalSpace();
long used = total - free;
SysFile sysFile = new SysFile();
sysFile.setDirName(fs.getMount());
sysFile.setSysTypeName(fs.getType());
sysFile.setTypeName(fs.getName());
sysFile.setTotal(convertFileSize(total));
sysFile.setFree(convertFileSize(free));
sysFile.setUsed(convertFileSize(used));
sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100));
sysFiles.add(sysFile);
}
}
/**
* 字节转换
*
* @param size 字节大小
* @return 转换后值
*/
public String convertFileSize(long size)
{
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (size >= gb)
{
return String.format("%.1f GB", (float) size / gb);
}
else if (size >= mb)
{
float f = (float) size / mb;
return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
}
else if (size >= kb)
{
float f = (float) size / kb;
return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
}
else
{
return String.format("%d B", size);
}
}
}
|
281677160/openwrt-package
| 1,853
|
luci-app-filebrowser/po/templates/filebrowser.pot
|
msgid ""
msgstr "Content-Type: text/plain; charset=UTF-8"
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:62
msgid "Collecting data..."
msgstr ""
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:81
msgid "Disable Command Runner feature"
msgstr ""
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:68
msgid "Enable"
msgstr ""
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:31
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:33
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:48
#: applications/luci-app-filebrowser/root/usr/share/luci/menu.d/luci-app-filebrowser.json:3
msgid "FileBrowser"
msgstr ""
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:49
msgid ""
"FileBrowser provides a file managing interface within a specified directory "
"and it can be used to upload, delete, preview, rename and edit your files.."
msgstr ""
#: applications/luci-app-filebrowser/root/usr/share/rpcd/acl.d/luci-app-filebrowser.json:3
msgid "Grant UCI access for luci-app-filebrowser"
msgstr ""
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:72
msgid "Listen port"
msgstr ""
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:33
msgid "NOT RUNNING"
msgstr ""
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:30
msgid "Open Web Interface"
msgstr ""
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:31
msgid "RUNNING"
msgstr ""
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:77
msgid "Root directory"
msgstr ""
|
2929004360/ruoyi-sign
| 1,514
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Cpu.java
|
package com.ruoyi.framework.web.domain.server;
import com.ruoyi.common.utils.Arith;
/**
* CPU相关信息
*
* @author ruoyi
*/
public class Cpu
{
/**
* 核心数
*/
private int cpuNum;
/**
* CPU总的使用率
*/
private double total;
/**
* CPU系统使用率
*/
private double sys;
/**
* CPU用户使用率
*/
private double used;
/**
* CPU当前等待率
*/
private double wait;
/**
* CPU当前空闲率
*/
private double free;
public int getCpuNum()
{
return cpuNum;
}
public void setCpuNum(int cpuNum)
{
this.cpuNum = cpuNum;
}
public double getTotal()
{
return Arith.round(Arith.mul(total, 100), 2);
}
public void setTotal(double total)
{
this.total = total;
}
public double getSys()
{
return Arith.round(Arith.mul(sys / total, 100), 2);
}
public void setSys(double sys)
{
this.sys = sys;
}
public double getUsed()
{
return Arith.round(Arith.mul(used / total, 100), 2);
}
public void setUsed(double used)
{
this.used = used;
}
public double getWait()
{
return Arith.round(Arith.mul(wait / total, 100), 2);
}
public void setWait(double wait)
{
this.wait = wait;
}
public double getFree()
{
return Arith.round(Arith.mul(free / total, 100), 2);
}
public void setFree(double free)
{
this.free = free;
}
}
|
2929004360/ruoyi-sign
| 2,184
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Jvm.java
|
package com.ruoyi.framework.web.domain.server;
import java.lang.management.ManagementFactory;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DateUtils;
/**
* JVM相关信息
*
* @author ruoyi
*/
public class Jvm
{
/**
* 当前JVM占用的内存总数(M)
*/
private double total;
/**
* JVM最大可用内存总数(M)
*/
private double max;
/**
* JVM空闲内存(M)
*/
private double free;
/**
* JDK版本
*/
private String version;
/**
* JDK路径
*/
private String home;
public double getTotal()
{
return Arith.div(total, (1024 * 1024), 2);
}
public void setTotal(double total)
{
this.total = total;
}
public double getMax()
{
return Arith.div(max, (1024 * 1024), 2);
}
public void setMax(double max)
{
this.max = max;
}
public double getFree()
{
return Arith.div(free, (1024 * 1024), 2);
}
public void setFree(double free)
{
this.free = free;
}
public double getUsed()
{
return Arith.div(total - free, (1024 * 1024), 2);
}
public double getUsage()
{
return Arith.mul(Arith.div(total - free, total, 4), 100);
}
/**
* 获取JDK名称
*/
public String getName()
{
return ManagementFactory.getRuntimeMXBean().getVmName();
}
public String getVersion()
{
return version;
}
public void setVersion(String version)
{
this.version = version;
}
public String getHome()
{
return home;
}
public void setHome(String home)
{
this.home = home;
}
/**
* JDK启动时间
*/
public String getStartTime()
{
return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getServerStartDate());
}
/**
* JDK运行时间
*/
public String getRunTime()
{
return DateUtils.timeDistance(DateUtils.getNowDate(), DateUtils.getServerStartDate());
}
/**
* 运行参数
*/
public String getInputArgs()
{
return ManagementFactory.getRuntimeMXBean().getInputArguments().toString();
}
}
|
2929004360/ruoyi-sign
| 1,216
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Sys.java
|
package com.ruoyi.framework.web.domain.server;
/**
* 系统相关信息
*
* @author ruoyi
*/
public class Sys
{
/**
* 服务器名称
*/
private String computerName;
/**
* 服务器Ip
*/
private String computerIp;
/**
* 项目路径
*/
private String userDir;
/**
* 操作系统
*/
private String osName;
/**
* 系统架构
*/
private String osArch;
public String getComputerName()
{
return computerName;
}
public void setComputerName(String computerName)
{
this.computerName = computerName;
}
public String getComputerIp()
{
return computerIp;
}
public void setComputerIp(String computerIp)
{
this.computerIp = computerIp;
}
public String getUserDir()
{
return userDir;
}
public void setUserDir(String userDir)
{
this.userDir = userDir;
}
public String getOsName()
{
return osName;
}
public void setOsName(String osName)
{
this.osName = osName;
}
public String getOsArch()
{
return osArch;
}
public void setOsArch(String osArch)
{
this.osArch = osArch;
}
}
|
2929004360/ruoyi-sign
| 1,571
|
ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/SysFile.java
|
package com.ruoyi.framework.web.domain.server;
/**
* 系统文件相关信息
*
* @author ruoyi
*/
public class SysFile
{
/**
* 盘符路径
*/
private String dirName;
/**
* 盘符类型
*/
private String sysTypeName;
/**
* 文件类型
*/
private String typeName;
/**
* 总大小
*/
private String total;
/**
* 剩余大小
*/
private String free;
/**
* 已经使用量
*/
private String used;
/**
* 资源的使用率
*/
private double usage;
public String getDirName()
{
return dirName;
}
public void setDirName(String dirName)
{
this.dirName = dirName;
}
public String getSysTypeName()
{
return sysTypeName;
}
public void setSysTypeName(String sysTypeName)
{
this.sysTypeName = sysTypeName;
}
public String getTypeName()
{
return typeName;
}
public void setTypeName(String typeName)
{
this.typeName = typeName;
}
public String getTotal()
{
return total;
}
public void setTotal(String total)
{
this.total = total;
}
public String getFree()
{
return free;
}
public void setFree(String free)
{
this.free = free;
}
public String getUsed()
{
return used;
}
public void setUsed(String used)
{
this.used = used;
}
public double getUsage()
{
return usage;
}
public void setUsage(double usage)
{
this.usage = usage;
}
}
|
281677160/openwrt-package
| 2,190
|
luci-app-filebrowser/po/zh_Hans/filebrowser.po
|
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Project-Id-Version: PACKAGE VERSION\n"
"Last-Translator: Automatically generated\n"
"Language-Team: none\n"
"Language: zh-Hans\n"
"MIME-Version: 1.0\n"
"Content-Transfer-Encoding: 8bit\n"
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:62
msgid "Collecting data..."
msgstr "正在收集数据中..."
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:81
msgid "Disable Command Runner feature"
msgstr "禁用命令执行功能"
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:68
msgid "Enable"
msgstr "启用"
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:31
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:33
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:48
#: applications/luci-app-filebrowser/root/usr/share/luci/menu.d/luci-app-filebrowser.json:3
msgid "FileBrowser"
msgstr "FileBrowser"
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:49
msgid ""
"FileBrowser provides a file managing interface within a specified directory "
"and it can be used to upload, delete, preview, rename and edit your files.."
msgstr ""
"FileBrowser 提供指定目录下的文件管理界面,可用于上传、删除、预览、重命名和编"
"辑文件。"
#: applications/luci-app-filebrowser/root/usr/share/rpcd/acl.d/luci-app-filebrowser.json:3
msgid "Grant UCI access for luci-app-filebrowser"
msgstr "授予 luci-app-filebrowser 访问 UCI 配置的权限"
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:72
msgid "Listen port"
msgstr "监听端口"
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:33
msgid "NOT RUNNING"
msgstr "未运行"
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:30
msgid "Open Web Interface"
msgstr "打开 Web 界面"
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:31
msgid "RUNNING"
msgstr "运行中"
#: applications/luci-app-filebrowser/htdocs/luci-static/resources/view/filebrowser.js:77
msgid "Root directory"
msgstr "根目录"
|
2977094657/ZsxqCrawler
| 130,364
|
main.py
|
"""
知识星球数据采集器 - FastAPI 后端服务
提供RESTful API接口来操作现有的爬虫功能
"""
import os
import sys
import asyncio
from typing import Dict, Any, Optional, List
from datetime import datetime
import json
import requests
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, Response
from pydantic import BaseModel, Field
import uvicorn
import mimetypes
import random
import time
# 添加项目根目录到Python路径(现在main.py就在根目录)
project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
sys.path.append(project_root)
# 导入现有的业务逻辑模块
from zsxq_interactive_crawler import ZSXQInteractiveCrawler, load_config
from db_path_manager import get_db_path_manager
from image_cache_manager import get_image_cache_manager
from accounts_manager import (
get_accounts as am_get_accounts,
add_account as am_add_account,
delete_account as am_delete_account,
set_default_account as am_set_default_account,
assign_group_account as am_assign_group_account,
get_account_for_group as am_get_account_for_group,
get_account_summary_for_group as am_get_account_summary_for_group,
get_default_account as am_get_default_account,
get_account_by_id as am_get_account_by_id,
)
from account_info_db import get_account_info_db
app = FastAPI(
title="知识星球数据采集器 API",
description="为知识星球数据采集器提供RESTful API接口",
version="1.0.0"
)
# 配置CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 前端地址
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 全局变量存储爬虫实例和任务状态
crawler_instance: Optional[ZSXQInteractiveCrawler] = None
current_tasks: Dict[str, Dict[str, Any]] = {}
task_counter = 0
task_logs: Dict[str, List[str]] = {} # 存储任务日志
sse_connections: Dict[str, List] = {} # 存储SSE连接
task_stop_flags: Dict[str, bool] = {} # 任务停止标志
file_downloader_instances: Dict[str, Any] = {} # 存储文件下载器实例
# =========================
# 本地群扫描(output 目录)
# =========================
# 可配置:默认 ./output;可通过环境变量 OUTPUT_DIR 覆盖
LOCAL_OUTPUT_DIR = os.environ.get("OUTPUT_DIR", "output")
# 处理上限保护,默认 10000;可通过 LOCAL_GROUPS_SCAN_LIMIT 覆盖
try:
LOCAL_SCAN_LIMIT = int(os.environ.get("LOCAL_GROUPS_SCAN_LIMIT", "10000"))
except Exception:
LOCAL_SCAN_LIMIT = 10000
# 本地群缓存
_local_groups_cache = {
"ids": set(), # set[int]
"scanned_at": 0.0 # epoch 秒
}
def _safe_listdir(path: str):
"""安全列目录,异常不抛出,返回空列表并告警"""
try:
return os.listdir(path)
except Exception as e:
print(f"⚠️ 无法读取目录 {path}: {e}")
return []
def _collect_numeric_dirs(base: str, limit: int) -> set:
"""
扫描 base 的一级子目录,收集纯数字目录名(^\d+$)作为群ID。
忽略:非目录、软链接、隐藏目录(以 . 开头)。
"""
ids = set()
if not base:
return ids
base_abs = os.path.abspath(base)
if not (os.path.exists(base_abs) and os.path.isdir(base_abs)):
# 视为空集合,不报错
print(f"⚠️ 目录不存在或不可读: {base_abs},视为空集合")
return ids
processed = 0
for name in _safe_listdir(base_abs):
# 隐藏目录
if not name or name.startswith('.'):
continue
path = os.path.join(base_abs, name)
try:
# 软链接/非目录忽略
if os.path.islink(path) or not os.path.isdir(path):
continue
# 仅纯数字目录名
if name.isdigit():
ids.add(int(name))
processed += 1
if processed >= limit:
print(f"⚠️ 子目录数量超过上限 {limit},已截断")
break
except Exception:
# 单项失败安全降级
continue
return ids
def scan_local_groups(output_dir: str = None, limit: int = None) -> set:
"""
扫描本地 output 的一级子目录,获取群ID集合。
同时兼容 output/databases 结构(如存在)。
同步执行(用于手动刷新或强制刷新),异常安全降级。
"""
try:
odir = output_dir or LOCAL_OUTPUT_DIR
lim = int(limit or LOCAL_SCAN_LIMIT)
# 主路径:仅扫描 output 的一级子目录
ids_primary = _collect_numeric_dirs(odir, lim)
# 兼容路径:output/databases 的一级子目录(若存在)
ids_secondary = _collect_numeric_dirs(os.path.join(odir, "databases"), lim)
ids = set(ids_primary) | set(ids_secondary)
# 更新缓存
_local_groups_cache["ids"] = ids
_local_groups_cache["scanned_at"] = time.time()
return ids
except Exception as e:
print(f"⚠️ 本地群扫描异常: {e}")
# 安全降级为旧缓存
return _local_groups_cache.get("ids", set())
def get_cached_local_group_ids(force_refresh: bool = False) -> set:
"""
获取缓存中的本地群ID集合;可选强制刷新。
未扫描过或要求强更时触发同步扫描。
"""
if force_refresh or not _local_groups_cache.get("ids"):
return scan_local_groups()
return _local_groups_cache.get("ids", set())
@app.on_event("startup")
async def _init_local_groups_scan():
"""
应用启动时后台异步执行一次扫描,不阻塞主线程。
"""
try:
await asyncio.to_thread(scan_local_groups)
except Exception as e:
print(f"⚠️ 启动扫描本地群失败: {e}")
# Pydantic模型定义
class ConfigModel(BaseModel):
cookie: str = Field(..., description="知识星球Cookie")
group_id: str = Field(..., description="群组ID")
db_path: str = Field(default="zsxq_interactive.db", description="数据库路径")
class CrawlHistoricalRequest(BaseModel):
pages: int = Field(default=10, ge=1, le=1000, description="爬取页数")
per_page: int = Field(default=20, ge=1, le=100, description="每页数量")
crawlIntervalMin: Optional[float] = Field(default=None, ge=1.0, le=60.0, description="爬取间隔最小值(秒)")
crawlIntervalMax: Optional[float] = Field(default=None, ge=1.0, le=60.0, description="爬取间隔最大值(秒)")
longSleepIntervalMin: Optional[float] = Field(default=None, ge=60.0, le=3600.0, description="长休眠间隔最小值(秒)")
longSleepIntervalMax: Optional[float] = Field(default=None, ge=60.0, le=3600.0, description="长休眠间隔最大值(秒)")
pagesPerBatch: Optional[int] = Field(default=None, ge=5, le=50, description="每批次页面数")
class CrawlSettingsRequest(BaseModel):
crawlIntervalMin: Optional[float] = Field(default=None, ge=1.0, le=60.0, description="爬取间隔最小值(秒)")
crawlIntervalMax: Optional[float] = Field(default=None, ge=1.0, le=60.0, description="爬取间隔最大值(秒)")
longSleepIntervalMin: Optional[float] = Field(default=None, ge=60.0, le=3600.0, description="长休眠间隔最小值(秒)")
longSleepIntervalMax: Optional[float] = Field(default=None, ge=60.0, le=3600.0, description="长休眠间隔最大值(秒)")
pagesPerBatch: Optional[int] = Field(default=None, ge=5, le=50, description="每批次页面数")
class FileDownloadRequest(BaseModel):
max_files: Optional[int] = Field(default=None, description="最大下载文件数")
sort_by: str = Field(default="download_count", description="排序方式: download_count 或 time")
download_interval: float = Field(default=1.0, ge=0.1, le=300.0, description="单次下载间隔(秒)")
long_sleep_interval: float = Field(default=60.0, ge=10.0, le=3600.0, description="长休眠间隔(秒)")
files_per_batch: int = Field(default=10, ge=1, le=100, description="下载多少文件后触发长休眠")
# 随机间隔范围参数(可选)
download_interval_min: Optional[float] = Field(default=None, ge=1.0, le=300.0, description="随机下载间隔最小值(秒)")
download_interval_max: Optional[float] = Field(default=None, ge=1.0, le=300.0, description="随机下载间隔最大值(秒)")
long_sleep_interval_min: Optional[float] = Field(default=None, ge=10.0, le=3600.0, description="随机长休眠间隔最小值(秒)")
long_sleep_interval_max: Optional[float] = Field(default=None, ge=10.0, le=3600.0, description="随机长休眠间隔最大值(秒)")
class AccountCreateRequest(BaseModel):
cookie: str = Field(..., description="账号Cookie")
name: Optional[str] = Field(default=None, description="账号名称")
make_default: Optional[bool] = Field(default=False, description="是否设为默认账号")
class AssignGroupAccountRequest(BaseModel):
account_id: str = Field(..., description="账号ID")
class GroupInfo(BaseModel):
group_id: int
name: str
type: str
background_url: Optional[str] = None
owner: Optional[dict] = None
statistics: Optional[dict] = None
class TaskResponse(BaseModel):
task_id: str
status: str # pending, running, completed, failed
message: str
result: Optional[Dict[str, Any]] = None
created_at: datetime
updated_at: datetime
# 辅助函数
def get_crawler(log_callback=None) -> ZSXQInteractiveCrawler:
"""获取爬虫实例"""
global crawler_instance
if crawler_instance is None:
config = load_config()
if not config:
raise HTTPException(status_code=500, detail="配置文件加载失败")
auth_config = config.get('auth', {})
cookie = auth_config.get('cookie', '')
group_id = auth_config.get('group_id', '')
if cookie == "your_cookie_here" or group_id == "your_group_id_here" or not cookie or not group_id:
raise HTTPException(status_code=400, detail="请先在config.toml中配置Cookie和群组ID")
# 使用路径管理器获取数据库路径
path_manager = get_db_path_manager()
db_path = path_manager.get_topics_db_path(group_id)
crawler_instance = ZSXQInteractiveCrawler(cookie, group_id, db_path, log_callback)
return crawler_instance
def get_crawler_for_group(group_id: str, log_callback=None) -> ZSXQInteractiveCrawler:
"""为指定群组获取爬虫实例"""
config = load_config()
if not config:
raise HTTPException(status_code=500, detail="配置文件加载失败")
# 自动匹配该群组所属账号,获取对应Cookie
cookie = get_cookie_for_group(group_id)
if not cookie or cookie == "your_cookie_here":
raise HTTPException(status_code=400, detail="未找到可用Cookie,请先在账号管理或config.toml中配置")
# 使用路径管理器获取指定群组的数据库路径
path_manager = get_db_path_manager()
db_path = path_manager.get_topics_db_path(group_id)
return ZSXQInteractiveCrawler(cookie, group_id, db_path, log_callback)
def get_crawler_safe() -> Optional[ZSXQInteractiveCrawler]:
"""安全获取爬虫实例,配置未设置时返回None"""
try:
return get_crawler()
except HTTPException:
return None
def is_configured() -> bool:
"""检查是否已配置认证信息"""
try:
config = load_config()
if not config:
return False
auth_config = config.get('auth', {})
cookie = auth_config.get('cookie', '')
group_id = auth_config.get('group_id', '')
return (cookie != "your_cookie_here" and
group_id != "your_group_id_here" and
cookie and group_id)
except:
return False
def create_task(task_type: str, description: str) -> str:
"""创建新任务"""
global task_counter
task_counter += 1
task_id = f"task_{task_counter}_{int(datetime.now().timestamp())}"
current_tasks[task_id] = {
"task_id": task_id,
"type": task_type,
"status": "pending",
"message": description,
"result": None,
"created_at": datetime.now(),
"updated_at": datetime.now()
}
# 初始化任务日志和停止标志
task_logs[task_id] = []
task_stop_flags[task_id] = False
add_task_log(task_id, f"任务创建: {description}")
return task_id
def add_task_log(task_id: str, log_message: str):
"""添加任务日志"""
if task_id not in task_logs:
task_logs[task_id] = []
timestamp = datetime.now().strftime("%H:%M:%S")
formatted_log = f"[{timestamp}] {log_message}"
task_logs[task_id].append(formatted_log)
# 广播日志到所有SSE连接
broadcast_log(task_id, formatted_log)
def broadcast_log(task_id: str, log_message: str):
"""广播日志到SSE连接"""
# 这个函数现在主要用于存储日志,实际的SSE广播在stream端点中实现
pass
def build_stealth_headers(cookie: str) -> Dict[str, str]:
"""构造更接近官网的请求头,提升成功率"""
user_agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
]
headers = {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7",
"Cache-Control": "no-cache",
"Cookie": cookie,
"Origin": "https://wx.zsxq.com",
"Pragma": "no-cache",
"Priority": "u=1, i",
"Referer": "https://wx.zsxq.com/",
"Sec-Ch-Ua": "\"Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24\"",
"Sec-Ch-Ua-Mobile": "?0",
"Sec-Ch-Ua-Platform": "\"Windows\"",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-site",
"User-Agent": random.choice(user_agents),
"X-Aduid": "a3be07cd6-dd67-3912-0093-862d844e7fe",
"X-Request-Id": f"dcc5cb6ab-1bc3-8273-cc26-{random.randint(100000000000, 999999999999)}",
"X-Signature": "733fd672ddf6d4e367730d9622cdd1e28a4b6203",
"X-Timestamp": str(int(time.time())),
"X-Version": "2.77.0",
}
return headers
def update_task(task_id: str, status: str, message: str, result: Optional[Dict[str, Any]] = None):
"""更新任务状态"""
if task_id in current_tasks:
current_tasks[task_id].update({
"status": status,
"message": message,
"result": result,
"updated_at": datetime.now()
})
# 添加状态变更日志
add_task_log(task_id, f"状态更新: {message}")
def stop_task(task_id: str) -> bool:
"""停止任务"""
if task_id not in current_tasks:
return False
task = current_tasks[task_id]
if task["status"] not in ["pending", "running"]:
return False
# 设置停止标志
task_stop_flags[task_id] = True
add_task_log(task_id, "🛑 收到停止请求,正在停止任务...")
# 如果有爬虫实例,也设置爬虫的停止标志
global crawler_instance, file_downloader_instances
if crawler_instance:
crawler_instance.set_stop_flag()
# 如果有文件下载器实例,也设置停止标志
if task_id in file_downloader_instances:
downloader = file_downloader_instances[task_id]
downloader.set_stop_flag()
update_task(task_id, "cancelled", "任务已被用户停止")
return True
def is_task_stopped(task_id: str) -> bool:
"""检查任务是否被停止"""
stopped = task_stop_flags.get(task_id, False)
return stopped
# API路由定义
@app.get("/")
async def root():
"""根路径"""
return {"message": "知识星球数据采集器 API 服务", "version": "1.0.0"}
@app.get("/api/health")
async def health_check():
"""健康检查"""
return {"status": "healthy", "timestamp": datetime.now()}
@app.get("/api/config")
async def get_config():
"""获取当前配置"""
try:
config = load_config()
if not config:
raise HTTPException(status_code=500, detail="配置文件不存在")
auth_config = config.get('auth', {})
cookie = auth_config.get('cookie', '')
group_id = auth_config.get('group_id', '')
# 检查配置状态
configured = is_configured()
# 隐藏敏感信息
safe_config = {
"configured": configured,
"auth": {
"cookie": "***" if configured else "未配置",
"group_id": group_id if group_id != "your_group_id_here" else "未配置"
},
"database": config.get('database', {}),
"download": config.get('download', {})
}
return safe_config
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")
@app.post("/api/config")
async def update_config(config: ConfigModel):
"""更新配置"""
try:
# 使用路径管理器获取数据库路径
path_manager = get_db_path_manager()
topics_db_path = path_manager.get_topics_db_path(config.group_id)
from pathlib import Path
safe_topics_db_path = Path(topics_db_path).as_posix()
# 创建配置内容
config_content = f"""# 知识星球数据采集器配置文件
# 通过Web界面自动生成
[auth]
# 知识星球登录Cookie
cookie = "{config.cookie}"
# 知识星球群组ID
group_id = "{config.group_id}"
[database]
# 数据库文件路径(由路径管理器自动管理)
path = "{safe_topics_db_path}"
[download]
# 下载目录
dir = "downloads"
"""
# 保存配置文件
config_path = "config.toml"
with open(config_path, 'w', encoding='utf-8') as f:
f.write(config_content)
# 重置爬虫实例,强制重新加载配置
global crawler_instance
crawler_instance = None
return {"message": "配置更新成功", "success": True}
except Exception as e:
raise HTTPException(status_code=500, detail=f"更新配置失败: {str(e)}")
# 账号管理 API
@app.get("/api/accounts")
async def list_accounts():
try:
accounts = am_get_accounts(mask_cookie=True)
# 若未添加本地账号,但在 config.toml 中存在默认 Cookie,则返回一个“默认账号”占位
if not accounts:
cfg = load_config()
auth = cfg.get('auth', {}) if cfg else {}
default_cookie = auth.get('cookie', '')
if default_cookie and default_cookie != "your_cookie_here":
accounts = [{
"id": "default",
"name": "默认账号",
"cookie": "***",
"is_default": True,
"created_at": None,
}]
return {"accounts": accounts}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取账号列表失败: {str(e)}")
@app.post("/api/accounts")
async def create_account(request: AccountCreateRequest):
try:
acc = am_add_account(request.cookie, request.name, request.make_default or False)
safe_acc = am_get_account_by_id(acc.get("id"), mask_cookie=True)
return {"account": safe_acc}
except Exception as e:
raise HTTPException(status_code=500, detail=f"新增账号失败: {str(e)}")
@app.delete("/api/accounts/{account_id}")
async def remove_account(account_id: str):
try:
ok = delete_account_success = am_delete_account(account_id)
if not ok:
raise HTTPException(status_code=404, detail="账号不存在")
return {"success": True}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"删除账号失败: {str(e)}")
@app.post("/api/accounts/{account_id}/default")
async def make_default_account(account_id: str):
try:
ok = am_set_default_account(account_id)
if not ok:
raise HTTPException(status_code=404, detail="账号不存在")
return {"success": True}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"设置默认账号失败: {str(e)}")
@app.post("/api/groups/{group_id}/assign-account")
async def assign_account_to_group(group_id: str, request: AssignGroupAccountRequest):
try:
ok, msg = am_assign_group_account(group_id, request.account_id)
if not ok:
raise HTTPException(status_code=400, detail=msg)
return {"success": True, "message": msg}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"分配账号失败: {str(e)}")
@app.get("/api/groups/{group_id}/account")
async def get_group_account(group_id: str):
try:
summary = get_account_summary_for_group_auto(group_id)
return {"account": summary}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取群组账号失败: {str(e)}")
# 账号“自我信息”持久化 (/v3/users/self)
@app.get("/api/accounts/{account_id}/self")
async def get_account_self(account_id: str):
"""获取并返回指定账号的已持久化自我信息;若无则尝试抓取并保存"""
try:
db = get_account_info_db()
info = db.get_self_info(account_id)
if info:
return {"self": info}
# 若数据库无记录则抓取,支持 'default' 伪账号(来自 config.toml)
cookie = None
acc = am_get_account_by_id(account_id, mask_cookie=False)
if acc:
cookie = acc.get("cookie", "")
elif account_id == "default":
cfg = load_config()
auth = cfg.get('auth', {}) if cfg else {}
cookie = auth.get('cookie', '')
else:
raise HTTPException(status_code=404, detail="账号不存在")
if not cookie:
raise HTTPException(status_code=400, detail="账号未配置Cookie")
headers = build_stealth_headers(cookie)
resp = requests.get('https://api.zsxq.com/v3/users/self', headers=headers, timeout=30)
resp.raise_for_status()
data = resp.json()
if not data.get('succeeded'):
raise HTTPException(status_code=400, detail="API返回失败")
rd = data.get('resp_data', {}) or {}
user = rd.get('user', {}) or {}
wechat = (rd.get('accounts', {}) or {}).get('wechat', {}) or {}
self_info = {
"uid": user.get("uid"),
"name": user.get("name") or wechat.get("name"),
"avatar_url": user.get("avatar_url") or wechat.get("avatar_url"),
"location": user.get("location"),
"user_sid": user.get("user_sid"),
"grade": user.get("grade"),
}
db.upsert_self_info(account_id, self_info, raw_json=data)
return {"self": db.get_self_info(account_id)}
except HTTPException:
raise
except requests.RequestException as e:
raise HTTPException(status_code=502, detail=f"网络请求失败: {str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取账号信息失败: {str(e)}")
@app.post("/api/accounts/{account_id}/self/refresh")
async def refresh_account_self(account_id: str):
"""强制抓取 /v3/users/self 并更新持久化"""
try:
# 支持 'default' 伪账号(来自 config.toml)
cookie = None
acc = am_get_account_by_id(account_id, mask_cookie=False)
if acc:
cookie = acc.get("cookie", "")
elif account_id == "default":
cfg = load_config()
auth = cfg.get('auth', {}) if cfg else {}
cookie = auth.get('cookie', '')
else:
raise HTTPException(status_code=404, detail="账号不存在")
if not cookie:
raise HTTPException(status_code=400, detail="账号未配置Cookie")
headers = build_stealth_headers(cookie)
resp = requests.get('https://api.zsxq.com/v3/users/self', headers=headers, timeout=30)
resp.raise_for_status()
data = resp.json()
if not data.get('succeeded'):
raise HTTPException(status_code=400, detail="API返回失败")
rd = data.get('resp_data', {}) or {}
user = rd.get('user', {}) or {}
wechat = (rd.get('accounts', {}) or {}).get('wechat', {}) or {}
self_info = {
"uid": user.get("uid"),
"name": user.get("name") or wechat.get("name"),
"avatar_url": user.get("avatar_url") or wechat.get("avatar_url"),
"location": user.get("location"),
"user_sid": user.get("user_sid"),
"grade": user.get("grade"),
}
db = get_account_info_db()
db.upsert_self_info(account_id, self_info, raw_json=data)
return {"self": db.get_self_info(account_id)}
except HTTPException:
raise
except requests.RequestException as e:
raise HTTPException(status_code=502, detail=f"网络请求失败: {str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"刷新账号信息失败: {str(e)}")
@app.get("/api/groups/{group_id}/self")
async def get_group_account_self(group_id: str):
"""获取群组当前使用账号的自我信息(若无则尝试抓取并保存)"""
try:
summary = get_account_summary_for_group_auto(group_id)
cookie = get_cookie_for_group(group_id)
account_id = (summary or {}).get('id', 'default')
if not cookie:
raise HTTPException(status_code=400, detail="未找到可用Cookie,请先配置账号或默认Cookie")
db = get_account_info_db()
info = db.get_self_info(account_id)
if info:
return {"self": info}
# 抓取并写入
headers = build_stealth_headers(cookie)
resp = requests.get('https://api.zsxq.com/v3/users/self', headers=headers, timeout=30)
resp.raise_for_status()
data = resp.json()
if not data.get('succeeded'):
raise HTTPException(status_code=400, detail="API返回失败")
rd = data.get('resp_data', {}) or {}
user = rd.get('user', {}) or {}
wechat = (rd.get('accounts', {}) or {}).get('wechat', {}) or {}
self_info = {
"uid": user.get("uid"),
"name": user.get("name") or wechat.get("name"),
"avatar_url": user.get("avatar_url") or wechat.get("avatar_url"),
"location": user.get("location"),
"user_sid": user.get("user_sid"),
"grade": user.get("grade"),
}
db.upsert_self_info(account_id, self_info, raw_json=data)
return {"self": db.get_self_info(account_id)}
except HTTPException:
raise
except requests.RequestException as e:
raise HTTPException(status_code=502, detail=f"网络请求失败: {str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取群组账号信息失败: {str(e)}")
@app.post("/api/groups/{group_id}/self/refresh")
async def refresh_group_account_self(group_id: str):
"""强制抓取群组当前使用账号的自我信息并持久化"""
try:
summary = get_account_summary_for_group_auto(group_id)
cookie = get_cookie_for_group(group_id)
account_id = (summary or {}).get('id', 'default')
if not cookie:
raise HTTPException(status_code=400, detail="未找到可用Cookie,请先配置账号或默认Cookie")
headers = build_stealth_headers(cookie)
resp = requests.get('https://api.zsxq.com/v3/users/self', headers=headers, timeout=30)
resp.raise_for_status()
data = resp.json()
if not data.get('succeeded'):
raise HTTPException(status_code=400, detail="API返回失败")
rd = data.get('resp_data', {}) or {}
user = rd.get('user', {}) or {}
wechat = (rd.get('accounts', {}) or {}).get('wechat', {}) or {}
self_info = {
"uid": user.get("uid"),
"name": user.get("name") or wechat.get("name"),
"avatar_url": user.get("avatar_url") or wechat.get("avatar_url"),
"location": user.get("location"),
"user_sid": user.get("user_sid"),
"grade": user.get("grade"),
}
db = get_account_info_db()
db.upsert_self_info(account_id, self_info, raw_json=data)
return {"self": db.get_self_info(account_id)}
except HTTPException:
raise
except requests.RequestException as e:
raise HTTPException(status_code=502, detail=f"网络请求失败: {str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"刷新群组账号信息失败: {str(e)}")
@app.get("/api/database/stats")
async def get_database_stats():
"""获取数据库统计信息"""
try:
# 检查是否已配置
if not is_configured():
return {
"configured": False,
"topic_database": {
"stats": {},
"timestamp_info": {
"total_topics": 0,
"oldest_timestamp": "",
"newest_timestamp": "",
"has_data": False
}
},
"file_database": {
"stats": {}
}
}
crawler = get_crawler_safe()
if not crawler:
return {
"configured": False,
"topic_database": {
"stats": {},
"timestamp_info": {
"total_topics": 0,
"oldest_timestamp": "",
"newest_timestamp": "",
"has_data": False
}
},
"file_database": {
"stats": {}
}
}
# 获取话题数据库统计
topic_stats = crawler.db.get_database_stats()
timestamp_info = crawler.db.get_timestamp_range_info()
# 获取文件数据库统计
file_downloader = crawler.get_file_downloader()
file_stats = file_downloader.file_db.get_database_stats()
return {
"configured": True,
"topic_database": {
"stats": topic_stats,
"timestamp_info": timestamp_info
},
"file_database": {
"stats": file_stats
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取数据库统计失败: {str(e)}")
@app.get("/api/tasks")
async def get_tasks():
"""获取所有任务状态"""
return list(current_tasks.values())
@app.get("/api/tasks/{task_id}")
async def get_task(task_id: str):
"""获取特定任务状态"""
if task_id not in current_tasks:
raise HTTPException(status_code=404, detail="任务不存在")
return current_tasks[task_id]
@app.post("/api/tasks/{task_id}/stop")
async def stop_task_api(task_id: str):
"""停止任务"""
if stop_task(task_id):
return {"message": "任务停止请求已发送", "task_id": task_id}
else:
raise HTTPException(status_code=404, detail="任务不存在或无法停止")
# 后台任务执行函数
def run_crawl_historical_task(task_id: str, group_id: str, pages: int, per_page: int, crawl_settings: CrawlHistoricalRequest = None):
"""后台执行历史数据爬取任务"""
try:
# 检查任务是否被停止
if is_task_stopped(task_id):
return
update_task(task_id, "running", f"开始爬取历史数据 {pages} 页...")
add_task_log(task_id, f"🚀 开始获取历史数据,{pages} 页,每页 {per_page} 条")
# 检查任务是否被停止
if is_task_stopped(task_id):
return
# 设置日志回调函数
def log_callback(message: str):
add_task_log(task_id, message)
# 设置停止检查函数
def stop_check():
return is_task_stopped(task_id)
# 为每个任务创建独立的爬虫实例,使用传入的group_id
# 自动匹配该群组所属账号,获取对应Cookie
cookie = get_cookie_for_group(group_id)
# 使用传入的group_id而不是配置文件中的固定值
path_manager = get_db_path_manager()
db_path = path_manager.get_topics_db_path(group_id)
crawler = ZSXQInteractiveCrawler(cookie, group_id, db_path, log_callback)
# 设置停止检查函数
crawler.stop_check_func = stop_check
# 设置自定义间隔参数
if crawl_settings:
crawler.set_custom_intervals(
crawl_interval_min=crawl_settings.crawlIntervalMin,
crawl_interval_max=crawl_settings.crawlIntervalMax,
long_sleep_interval_min=crawl_settings.longSleepIntervalMin,
long_sleep_interval_max=crawl_settings.longSleepIntervalMax,
pages_per_batch=crawl_settings.pagesPerBatch
)
# 检查任务是否在设置过程中被停止
if is_task_stopped(task_id):
add_task_log(task_id, "🛑 任务在初始化过程中被停止")
return
add_task_log(task_id, "📡 连接到知识星球API...")
add_task_log(task_id, "🔍 检查数据库状态...")
# 检查任务是否被停止
if is_task_stopped(task_id):
return
result = crawler.crawl_incremental(pages, per_page)
# 检查任务是否被停止
if is_task_stopped(task_id):
return
# 检查是否是会员过期错误
if result and result.get('expired'):
add_task_log(task_id, f"❌ 会员已过期: {result.get('message', '成员体验已到期')}")
update_task(task_id, "failed", "会员已过期", {"expired": True, "code": result.get('code'), "message": result.get('message')})
return
add_task_log(task_id, f"✅ 获取完成!新增话题: {result.get('new_topics', 0)}, 更新话题: {result.get('updated_topics', 0)}")
update_task(task_id, "completed", "历史数据爬取完成", result)
except Exception as e:
if not is_task_stopped(task_id):
add_task_log(task_id, f"❌ 获取失败: {str(e)}")
update_task(task_id, "failed", f"爬取失败: {str(e)}")
def run_file_download_task(task_id: str, group_id: str, max_files: Optional[int], sort_by: str,
download_interval: float = 1.0, long_sleep_interval: float = 60.0,
files_per_batch: int = 10, download_interval_min: Optional[float] = None,
download_interval_max: Optional[float] = None,
long_sleep_interval_min: Optional[float] = None,
long_sleep_interval_max: Optional[float] = None):
"""后台执行文件下载任务"""
try:
update_task(task_id, "running", "开始文件下载...")
def log_callback(message: str):
add_task_log(task_id, message)
# 设置停止检查函数
def stop_check():
return is_task_stopped(task_id)
# 为每个任务创建独立的文件下载器实例,使用传入的group_id
# 自动匹配该群组所属账号,获取对应Cookie
cookie = get_cookie_for_group(group_id)
# 使用传入的group_id而不是配置文件中的固定值
from zsxq_file_downloader import ZSXQFileDownloader
from db_path_manager import get_db_path_manager
path_manager = get_db_path_manager()
db_path = path_manager.get_files_db_path(group_id)
downloader = ZSXQFileDownloader(
cookie=cookie,
group_id=group_id,
db_path=db_path,
download_interval=download_interval,
long_sleep_interval=long_sleep_interval,
files_per_batch=files_per_batch,
download_interval_min=download_interval_min,
download_interval_max=download_interval_max,
long_sleep_interval_min=long_sleep_interval_min,
long_sleep_interval_max=long_sleep_interval_max
)
# 设置日志回调和停止检查函数
downloader.log_callback = log_callback
downloader.stop_check_func = stop_check
add_task_log(task_id, f"⚙️ 下载配置:")
add_task_log(task_id, f" ⏱️ 单次下载间隔: {download_interval}秒")
add_task_log(task_id, f" 😴 长休眠间隔: {long_sleep_interval}秒")
add_task_log(task_id, f" 📦 批次大小: {files_per_batch}个文件")
# 将下载器实例存储到全局字典中
global file_downloader_instances
file_downloader_instances[task_id] = downloader
# 检查任务是否在设置过程中被停止
if is_task_stopped(task_id):
add_task_log(task_id, "🛑 任务在初始化过程中被停止")
return
add_task_log(task_id, "📡 连接到知识星球API...")
add_task_log(task_id, "🔍 开始收集文件列表...")
# 先收集文件列表
collect_result = downloader.collect_incremental_files()
# 检查任务是否被停止
if is_task_stopped(task_id):
return
add_task_log(task_id, f"📊 文件收集完成: {collect_result}")
add_task_log(task_id, "🚀 开始下载文件...")
# 根据排序方式下载文件
if sort_by == "download_count":
result = downloader.download_files_from_database(max_files=max_files, status_filter='pending')
else:
result = downloader.download_files_from_database(max_files=max_files, status_filter='pending')
# 检查任务是否被停止
if is_task_stopped(task_id):
return
add_task_log(task_id, f"✅ 文件下载完成!")
update_task(task_id, "completed", "文件下载完成", {"downloaded_files": result})
except Exception as e:
if not is_task_stopped(task_id):
add_task_log(task_id, f"❌ 文件下载失败: {str(e)}")
update_task(task_id, "failed", f"文件下载失败: {str(e)}")
finally:
# 清理下载器实例
if task_id in file_downloader_instances:
del file_downloader_instances[task_id]
def run_single_file_download_task(task_id: str, group_id: str, file_id: int):
"""运行单个文件下载任务"""
try:
update_task(task_id, "running", f"开始下载文件 (ID: {file_id})...")
def log_callback(message: str):
add_task_log(task_id, message)
# 设置停止检查函数
def stop_check():
return is_task_stopped(task_id)
# 创建文件下载器实例
# 自动匹配该群组所属账号,获取对应Cookie
cookie = get_cookie_for_group(group_id)
from zsxq_file_downloader import ZSXQFileDownloader
from db_path_manager import get_db_path_manager
path_manager = get_db_path_manager()
db_path = path_manager.get_files_db_path(group_id)
downloader = ZSXQFileDownloader(
cookie=cookie,
group_id=group_id,
db_path=db_path
)
# 设置日志回调和停止检查函数
downloader.log_callback = log_callback
downloader.stop_check_func = stop_check
# 将下载器实例存储到全局字典中
global file_downloader_instances
file_downloader_instances[task_id] = downloader
# 检查任务是否在设置过程中被停止
if is_task_stopped(task_id):
add_task_log(task_id, "🛑 任务在初始化过程中被停止")
return
# 尝试从数据库获取文件信息
downloader.file_db.cursor.execute('''
SELECT file_id, name, size, download_count
FROM files
WHERE file_id = ?
''', (file_id,))
result = downloader.file_db.cursor.fetchone()
if result:
# 如果数据库中有文件信息,使用数据库信息
file_id_db, file_name, file_size, download_count = result
add_task_log(task_id, f"📄 从数据库获取文件信息: {file_name} ({file_size} bytes)")
# 构造文件信息结构
file_info = {
'file': {
'id': file_id,
'name': file_name,
'size': file_size,
'download_count': download_count
}
}
else:
# 如果数据库中没有文件信息,直接尝试下载
add_task_log(task_id, f"📄 数据库中无文件信息,尝试直接下载文件 ID: {file_id}")
# 构造最小文件信息结构
file_info = {
'file': {
'id': file_id,
'name': f'file_{file_id}', # 使用默认文件名
'size': 0, # 未知大小
'download_count': 0
}
}
# 下载文件
result = downloader.download_file(file_info)
if result == "skipped":
add_task_log(task_id, "✅ 文件已存在,跳过下载")
update_task(task_id, "completed", "文件已存在")
elif result:
add_task_log(task_id, "✅ 文件下载成功")
# 获取实际下载的文件信息
actual_file_info = file_info['file']
actual_file_name = actual_file_info.get('name', f'file_{file_id}')
actual_file_size = actual_file_info.get('size', 0)
# 检查本地文件获取实际大小
import os
safe_filename = "".join(c for c in actual_file_name if c.isalnum() or c in '._-()()[]{}')
if not safe_filename:
safe_filename = f"file_{file_id}"
local_path = os.path.join(downloader.download_dir, safe_filename)
if os.path.exists(local_path):
actual_file_size = os.path.getsize(local_path)
# 更新或插入文件状态
downloader.file_db.cursor.execute('''
INSERT OR REPLACE INTO files
(file_id, name, size, download_status, local_path, download_time, download_count)
VALUES (?, ?, ?, 'downloaded', ?, CURRENT_TIMESTAMP, ?)
''', (file_id, actual_file_name, actual_file_size, local_path,
actual_file_info.get('download_count', 0)))
downloader.file_db.conn.commit()
update_task(task_id, "completed", "下载成功")
else:
add_task_log(task_id, "❌ 文件下载失败")
update_task(task_id, "failed", "下载失败")
except Exception as e:
if not is_task_stopped(task_id):
add_task_log(task_id, f"❌ 任务执行失败: {str(e)}")
update_task(task_id, "failed", f"任务失败: {str(e)}")
finally:
# 清理下载器实例
if task_id in file_downloader_instances:
del file_downloader_instances[task_id]
def run_single_file_download_task_with_info(task_id: str, group_id: str, file_id: int,
file_name: Optional[str] = None, file_size: Optional[int] = None):
"""运行单个文件下载任务(带文件信息)"""
try:
update_task(task_id, "running", f"开始下载文件 (ID: {file_id})...")
def log_callback(message: str):
add_task_log(task_id, message)
# 设置停止检查函数
def stop_check():
return is_task_stopped(task_id)
# 创建文件下载器实例
# 自动匹配该群组所属账号,获取对应Cookie
cookie = get_cookie_for_group(group_id)
from zsxq_file_downloader import ZSXQFileDownloader
from db_path_manager import get_db_path_manager
path_manager = get_db_path_manager()
db_path = path_manager.get_files_db_path(group_id)
downloader = ZSXQFileDownloader(
cookie=cookie,
group_id=group_id,
db_path=db_path
)
# 设置日志回调和停止检查函数
downloader.log_callback = log_callback
downloader.stop_check_func = stop_check
# 将下载器实例存储到全局字典中
global file_downloader_instances
file_downloader_instances[task_id] = downloader
# 检查任务是否在设置过程中被停止
if is_task_stopped(task_id):
add_task_log(task_id, "🛑 任务在初始化过程中被停止")
return
# 构造文件信息结构
if file_name and file_size:
add_task_log(task_id, f"📄 使用提供的文件信息: {file_name} ({file_size} bytes)")
file_info = {
'file': {
'id': file_id,
'name': file_name,
'size': file_size,
'download_count': 0
}
}
else:
# 尝试从数据库获取文件信息
downloader.file_db.cursor.execute('''
SELECT file_id, name, size, download_count
FROM files
WHERE file_id = ?
''', (file_id,))
result = downloader.file_db.cursor.fetchone()
if result:
file_id_db, db_file_name, db_file_size, download_count = result
add_task_log(task_id, f"📄 从数据库获取文件信息: {db_file_name} ({db_file_size} bytes)")
file_info = {
'file': {
'id': file_id,
'name': db_file_name,
'size': db_file_size,
'download_count': download_count
}
}
else:
add_task_log(task_id, f"📄 直接下载文件 ID: {file_id}")
file_info = {
'file': {
'id': file_id,
'name': f'file_{file_id}',
'size': 0,
'download_count': 0
}
}
# 下载文件
result = downloader.download_file(file_info)
if result == "skipped":
add_task_log(task_id, "✅ 文件已存在,跳过下载")
update_task(task_id, "completed", "文件已存在")
elif result:
add_task_log(task_id, "✅ 文件下载成功")
# 获取实际下载的文件信息
actual_file_info = file_info['file']
actual_file_name = actual_file_info.get('name', f'file_{file_id}')
actual_file_size = actual_file_info.get('size', 0)
# 检查本地文件获取实际大小
import os
safe_filename = "".join(c for c in actual_file_name if c.isalnum() or c in '._-()()[]{}')
if not safe_filename:
safe_filename = f"file_{file_id}"
local_path = os.path.join(downloader.download_dir, safe_filename)
if os.path.exists(local_path):
actual_file_size = os.path.getsize(local_path)
# 更新或插入文件状态
downloader.file_db.cursor.execute('''
INSERT OR REPLACE INTO files
(file_id, name, size, download_status, local_path, download_time, download_count)
VALUES (?, ?, ?, 'downloaded', ?, CURRENT_TIMESTAMP, ?)
''', (file_id, actual_file_name, actual_file_size, local_path,
actual_file_info.get('download_count', 0)))
downloader.file_db.conn.commit()
update_task(task_id, "completed", "下载成功")
else:
add_task_log(task_id, "❌ 文件下载失败")
update_task(task_id, "failed", "下载失败")
except Exception as e:
if not is_task_stopped(task_id):
add_task_log(task_id, f"❌ 任务执行失败: {str(e)}")
update_task(task_id, "failed", f"任务失败: {str(e)}")
finally:
# 清理下载器实例
if task_id in file_downloader_instances:
del file_downloader_instances[task_id]
# 群组相关辅助函数
def fetch_groups_from_api(cookie: str) -> List[dict]:
"""从知识星球API获取群组列表"""
import requests
# 如果是测试Cookie,返回模拟数据
if cookie == "test_cookie":
return [
{
"group_id": 123456,
"name": "测试知识星球群组",
"type": "public",
"background_url": "https://via.placeholder.com/400x200/4f46e5/ffffff?text=Test+Group",
"description": "这是一个用于测试的知识星球群组,包含各种技术讨论和学习资源分享。",
"create_time": "2023-01-15T10:30:00+08:00",
"subscription_time": "2024-01-01T00:00:00+08:00",
"expiry_time": "2024-12-31T23:59:59+08:00",
"status": "active",
"owner": {
"user_id": 1001,
"name": "测试群主",
"avatar_url": "https://via.placeholder.com/64x64/10b981/ffffff?text=Owner"
},
"statistics": {
"members_count": 1250,
"topics_count": 89,
"files_count": 156
}
},
{
"group_id": 789012,
"name": "技术交流群",
"type": "private",
"background_url": "https://via.placeholder.com/400x200/059669/ffffff?text=Tech+Group",
"description": "专注于前端、后端、移动开发等技术领域的深度交流与实践分享。",
"create_time": "2023-03-20T14:15:00+08:00",
"subscription_time": "2024-02-15T00:00:00+08:00",
"expiry_time": "2025-02-14T23:59:59+08:00",
"status": "active",
"owner": {
"user_id": 1002,
"name": "技术专家",
"avatar_url": "https://via.placeholder.com/64x64/dc2626/ffffff?text=Tech"
},
"statistics": {
"members_count": 856,
"topics_count": 234,
"files_count": 67
}
},
{
"group_id": 345678,
"name": "产品设计讨论",
"type": "public",
"background_url": "https://via.placeholder.com/400x200/7c3aed/ffffff?text=Design+Group",
"description": "UI/UX设计、产品思维、用户体验等设计相关话题的专业讨论社区。",
"create_time": "2023-06-10T09:45:00+08:00",
"subscription_time": "2024-03-01T00:00:00+08:00",
"expiry_time": "2024-08-31T23:59:59+08:00",
"status": "active",
"owner": {
"user_id": 1003,
"name": "设计师",
"avatar_url": "https://via.placeholder.com/64x64/ea580c/ffffff?text=Design"
},
"statistics": {
"members_count": 432,
"topics_count": 156,
"files_count": 89
}
},
{
"group_id": 456789,
"name": "创业投资圈",
"type": "private",
"background_url": "https://via.placeholder.com/400x200/dc2626/ffffff?text=Startup",
"description": "创业者、投资人、行业专家的交流平台,分享创业经验和投资见解。",
"create_time": "2023-08-05T16:20:00+08:00",
"subscription_time": "2024-01-10T00:00:00+08:00",
"expiry_time": "2024-07-09T23:59:59+08:00",
"status": "expiring_soon",
"owner": {
"user_id": 1004,
"name": "投资人",
"avatar_url": "https://via.placeholder.com/64x64/f59e0b/ffffff?text=VC"
},
"statistics": {
"members_count": 298,
"topics_count": 78,
"files_count": 45
}
},
{
"group_id": 567890,
"name": "AI人工智能研究",
"type": "public",
"background_url": "https://via.placeholder.com/400x200/06b6d4/ffffff?text=AI+Research",
"description": "人工智能、机器学习、深度学习等前沿技术的研究与应用讨论。",
"create_time": "2023-09-12T11:30:00+08:00",
"subscription_time": "2024-04-01T00:00:00+08:00",
"expiry_time": "2025-03-31T23:59:59+08:00",
"status": "active",
"owner": {
"user_id": 1005,
"name": "AI研究员",
"avatar_url": "https://via.placeholder.com/64x64/8b5cf6/ffffff?text=AI"
},
"statistics": {
"members_count": 1876,
"topics_count": 345,
"files_count": 234
}
}
]
headers = build_stealth_headers(cookie)
try:
response = requests.get('https://api.zsxq.com/v2/groups', headers=headers, timeout=30)
response.raise_for_status()
data = response.json()
if data.get('succeeded'):
return data.get('resp_data', {}).get('groups', [])
else:
raise Exception(f"API返回失败: {data.get('error_message', '未知错误')}")
except requests.RequestException as e:
raise Exception(f"网络请求失败: {str(e)}")
except Exception as e:
raise Exception(f"获取群组列表失败: {str(e)}")
# 爬取相关API路由
@app.post("/api/crawl/historical/{group_id}")
async def crawl_historical(group_id: str, request: CrawlHistoricalRequest, background_tasks: BackgroundTasks):
"""爬取历史数据"""
try:
task_id = create_task("crawl_historical", f"爬取历史数据 {request.pages} 页 (群组: {group_id})")
# 添加后台任务
background_tasks.add_task(run_crawl_historical_task, task_id, group_id, request.pages, request.per_page, request)
return {"task_id": task_id, "message": "任务已创建,正在后台执行"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"创建爬取任务失败: {str(e)}")
@app.post("/api/crawl/all/{group_id}")
async def crawl_all(group_id: str, request: CrawlSettingsRequest, background_tasks: BackgroundTasks):
"""全量爬取所有历史数据"""
try:
task_id = create_task("crawl_all", f"全量爬取所有历史数据 (群组: {group_id})")
def run_crawl_all_task(task_id: str, group_id: str, crawl_settings: CrawlSettingsRequest = None):
try:
update_task(task_id, "running", "开始全量爬取...")
add_task_log(task_id, "🚀 开始全量爬取...")
add_task_log(task_id, "⚠️ 警告:此模式将持续爬取直到没有数据,可能需要很长时间")
# 创建日志回调函数
def log_callback(message):
add_task_log(task_id, message)
# 设置停止检查函数
def stop_check():
return is_task_stopped(task_id)
# 为这个任务创建新的爬虫实例(带日志回调),使用传入的group_id
config = load_config()
auth_config = config.get('auth', {})
default_cookie = auth_config.get('cookie', '')
account = am_get_account_for_group(group_id)
cookie = account.get('cookie', '') if account else default_cookie
# 使用传入的group_id而不是配置文件中的固定值
path_manager = get_db_path_manager()
db_path = path_manager.get_topics_db_path(group_id)
crawler = ZSXQInteractiveCrawler(cookie, group_id, db_path, log_callback)
# 设置停止检查函数
crawler.stop_check_func = stop_check
# 设置自定义间隔参数
if crawl_settings:
crawler.set_custom_intervals(
crawl_interval_min=crawl_settings.crawlIntervalMin,
crawl_interval_max=crawl_settings.crawlIntervalMax,
long_sleep_interval_min=crawl_settings.longSleepIntervalMin,
long_sleep_interval_max=crawl_settings.longSleepIntervalMax,
pages_per_batch=crawl_settings.pagesPerBatch
)
# 检查任务是否在设置过程中被停止
if is_task_stopped(task_id):
add_task_log(task_id, "🛑 任务在初始化过程中被停止")
return
add_task_log(task_id, "📡 连接到知识星球API...")
add_task_log(task_id, "🔍 检查数据库状态...")
# 检查任务是否被停止
if is_task_stopped(task_id):
return
# 获取数据库状态
db_stats = crawler.db.get_database_stats()
add_task_log(task_id, f"📊 当前数据库状态: 话题: {db_stats.get('topics', 0)}, 用户: {db_stats.get('users', 0)}")
# 检查任务是否被停止
if is_task_stopped(task_id):
return
add_task_log(task_id, "🌊 开始无限历史爬取...")
result = crawler.crawl_all_historical(per_page=20, auto_confirm=True)
# 检查任务是否被停止
if is_task_stopped(task_id):
return
# 检查是否是会员过期错误
if result and result.get('expired'):
add_task_log(task_id, f"❌ 会员已过期: {result.get('message', '成员体验已到期')}")
update_task(task_id, "failed", "会员已过期", {"expired": True, "code": result.get('code'), "message": result.get('message')})
return
add_task_log(task_id, f"🎉 全量爬取完成!")
add_task_log(task_id, f"📊 最终统计: 新增话题: {result.get('new_topics', 0)}, 更新话题: {result.get('updated_topics', 0)}, 总页数: {result.get('pages', 0)}")
update_task(task_id, "completed", "全量爬取完成", result)
except Exception as e:
add_task_log(task_id, f"❌ 全量爬取失败: {str(e)}")
update_task(task_id, "failed", f"全量爬取失败: {str(e)}")
# 添加后台任务
background_tasks.add_task(run_crawl_all_task, task_id, group_id, request)
return {"task_id": task_id, "message": "任务已创建,正在后台执行"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"创建全量爬取任务失败: {str(e)}")
@app.post("/api/crawl/incremental/{group_id}")
async def crawl_incremental(group_id: str, request: CrawlHistoricalRequest, background_tasks: BackgroundTasks):
"""增量爬取历史数据"""
try:
task_id = create_task("crawl_incremental", f"增量爬取历史数据 {request.pages} 页 (群组: {group_id})")
def run_crawl_incremental_task(task_id: str, group_id: str, pages: int, per_page: int, crawl_settings: CrawlHistoricalRequest = None):
try:
update_task(task_id, "running", "开始增量爬取...")
def log_callback(message: str):
add_task_log(task_id, message)
# 设置停止检查函数
def stop_check():
return is_task_stopped(task_id)
# 为每个任务创建独立的爬虫实例
config = load_config()
auth_config = config.get('auth', {})
default_cookie = auth_config.get('cookie', '')
account = am_get_account_for_group(group_id)
cookie = account.get('cookie', '') if account else default_cookie
# 使用传入的group_id而不是配置文件中的固定值
path_manager = get_db_path_manager()
db_path = path_manager.get_topics_db_path(group_id)
crawler = ZSXQInteractiveCrawler(cookie, group_id, db_path, log_callback)
# 设置停止检查函数
crawler.stop_check_func = stop_check
# 设置自定义间隔参数
if crawl_settings:
crawler.set_custom_intervals(
crawl_interval_min=crawl_settings.crawlIntervalMin,
crawl_interval_max=crawl_settings.crawlIntervalMax,
long_sleep_interval_min=crawl_settings.longSleepIntervalMin,
long_sleep_interval_max=crawl_settings.longSleepIntervalMax,
pages_per_batch=crawl_settings.pagesPerBatch
)
# 检查任务是否在设置过程中被停止
if is_task_stopped(task_id):
add_task_log(task_id, "🛑 任务在初始化过程中被停止")
return
add_task_log(task_id, "📡 连接到知识星球API...")
add_task_log(task_id, "🔍 检查数据库状态...")
result = crawler.crawl_incremental(pages, per_page)
# 检查任务是否被停止
if is_task_stopped(task_id):
return
add_task_log(task_id, f"✅ 增量爬取完成!新增话题: {result.get('new_topics', 0)}, 更新话题: {result.get('updated_topics', 0)}")
update_task(task_id, "completed", "增量爬取完成", result)
except Exception as e:
if not is_task_stopped(task_id):
add_task_log(task_id, f"❌ 增量爬取失败: {str(e)}")
update_task(task_id, "failed", f"增量爬取失败: {str(e)}")
# 添加后台任务
background_tasks.add_task(run_crawl_incremental_task, task_id, group_id, request.pages, request.per_page, request)
return {"task_id": task_id, "message": "任务已创建,正在后台执行"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"创建增量爬取任务失败: {str(e)}")
@app.post("/api/crawl/latest-until-complete/{group_id}")
async def crawl_latest_until_complete(group_id: str, request: CrawlSettingsRequest, background_tasks: BackgroundTasks):
"""获取最新记录:智能增量更新"""
try:
task_id = create_task("crawl_latest_until_complete", f"获取最新记录 (群组: {group_id})")
def run_crawl_latest_task(task_id: str, group_id: str, crawl_settings: CrawlSettingsRequest = None):
try:
update_task(task_id, "running", "开始获取最新记录...")
def log_callback(message: str):
add_task_log(task_id, message)
# 设置停止检查函数
def stop_check():
return is_task_stopped(task_id)
# 为每个任务创建独立的爬虫实例,使用传入的group_id
config = load_config()
auth_config = config.get('auth', {})
default_cookie = auth_config.get('cookie', '')
account = am_get_account_for_group(group_id)
cookie = account.get('cookie', '') if account else default_cookie
# 使用传入的group_id而不是配置文件中的固定值
path_manager = get_db_path_manager()
db_path = path_manager.get_topics_db_path(group_id)
crawler = ZSXQInteractiveCrawler(cookie, group_id, db_path, log_callback)
# 设置停止检查函数
crawler.stop_check_func = stop_check
# 设置自定义间隔参数
if crawl_settings:
crawler.set_custom_intervals(
crawl_interval_min=crawl_settings.crawlIntervalMin,
crawl_interval_max=crawl_settings.crawlIntervalMax,
long_sleep_interval_min=crawl_settings.longSleepIntervalMin,
long_sleep_interval_max=crawl_settings.longSleepIntervalMax,
pages_per_batch=crawl_settings.pagesPerBatch
)
# 检查任务是否在设置过程中被停止
if is_task_stopped(task_id):
add_task_log(task_id, "🛑 任务在初始化过程中被停止")
return
add_task_log(task_id, "📡 连接到知识星球API...")
add_task_log(task_id, "🔍 检查数据库状态...")
result = crawler.crawl_latest_until_complete()
# 检查任务是否被停止
if is_task_stopped(task_id):
return
# 检查是否是会员过期错误
if result and result.get('expired'):
add_task_log(task_id, f"❌ 会员已过期: {result.get('message', '成员体验已到期')}")
update_task(task_id, "failed", "会员已过期", {"expired": True, "code": result.get('code'), "message": result.get('message')})
return
add_task_log(task_id, f"✅ 获取最新记录完成!新增话题: {result.get('new_topics', 0)}, 更新话题: {result.get('updated_topics', 0)}")
update_task(task_id, "completed", "获取最新记录完成", result)
except Exception as e:
if not is_task_stopped(task_id):
add_task_log(task_id, f"❌ 获取最新记录失败: {str(e)}")
update_task(task_id, "failed", f"获取最新记录失败: {str(e)}")
# 添加后台任务
background_tasks.add_task(run_crawl_latest_task, task_id, group_id, request)
return {"task_id": task_id, "message": "任务已创建,正在后台执行"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"创建获取最新记录任务失败: {str(e)}")
# 文件相关API路由
@app.post("/api/files/collect/{group_id}")
async def collect_files(group_id: str, background_tasks: BackgroundTasks):
"""收集文件列表"""
try:
task_id = create_task("collect_files", "收集文件列表")
def run_collect_files_task(task_id: str, group_id: str):
try:
update_task(task_id, "running", "开始收集文件列表...")
def log_callback(message: str):
add_task_log(task_id, message)
# 设置停止检查函数
def stop_check():
return is_task_stopped(task_id)
# 为每个任务创建独立的文件下载器实例
config = load_config()
auth_config = config.get('auth', {})
default_cookie = auth_config.get('cookie', '')
account = am_get_account_for_group(group_id)
cookie = account.get('cookie', '') if account else default_cookie
from zsxq_file_downloader import ZSXQFileDownloader
from db_path_manager import get_db_path_manager
path_manager = get_db_path_manager()
db_path = path_manager.get_files_db_path(group_id)
downloader = ZSXQFileDownloader(cookie, group_id, db_path)
downloader.log_callback = log_callback
downloader.stop_check_func = stop_check
# 将下载器实例存储到全局字典中
global file_downloader_instances
file_downloader_instances[task_id] = downloader
# 检查任务是否在设置过程中被停止
if is_task_stopped(task_id):
add_task_log(task_id, "🛑 任务在初始化过程中被停止")
return
add_task_log(task_id, "📡 连接到知识星球API...")
result = downloader.collect_incremental_files()
# 检查任务是否被停止
if is_task_stopped(task_id):
return
add_task_log(task_id, f"✅ 文件列表收集完成!")
update_task(task_id, "completed", "文件列表收集完成", result)
except Exception as e:
if not is_task_stopped(task_id):
add_task_log(task_id, f"❌ 文件列表收集失败: {str(e)}")
update_task(task_id, "failed", f"文件列表收集失败: {str(e)}")
finally:
# 清理下载器实例
if task_id in file_downloader_instances:
del file_downloader_instances[task_id]
# 添加后台任务
background_tasks.add_task(run_collect_files_task, task_id, group_id)
return {"task_id": task_id, "message": "任务已创建,正在后台执行"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"创建文件收集任务失败: {str(e)}")
@app.post("/api/files/download/{group_id}")
async def download_files(group_id: str, request: FileDownloadRequest, background_tasks: BackgroundTasks):
"""下载文件"""
try:
task_id = create_task("download_files", f"下载文件 (排序: {request.sort_by})")
# 添加后台任务
background_tasks.add_task(
run_file_download_task,
task_id,
group_id,
request.max_files,
request.sort_by,
request.download_interval,
request.long_sleep_interval,
request.files_per_batch,
request.download_interval_min,
request.download_interval_max,
request.long_sleep_interval_min,
request.long_sleep_interval_max
)
return {"task_id": task_id, "message": "任务已创建,正在后台执行"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"创建文件下载任务失败: {str(e)}")
@app.post("/api/files/download-single/{group_id}/{file_id}")
async def download_single_file(group_id: str, file_id: int, background_tasks: BackgroundTasks,
file_name: Optional[str] = None, file_size: Optional[int] = None):
"""下载单个文件"""
try:
task_id = create_task("download_single_file", f"下载单个文件 (ID: {file_id})")
# 添加后台任务
background_tasks.add_task(
run_single_file_download_task_with_info,
task_id,
group_id,
file_id,
file_name,
file_size
)
return {"task_id": task_id, "message": "单个文件下载任务已创建"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"创建单个文件下载任务失败: {str(e)}")
@app.get("/api/files/status/{group_id}/{file_id}")
async def get_file_status(group_id: str, file_id: int):
"""获取文件下载状态"""
try:
crawler = get_crawler_for_group(group_id)
downloader = crawler.get_file_downloader()
# 查询文件信息
downloader.file_db.cursor.execute('''
SELECT name, size, download_status
FROM files
WHERE file_id = ?
''', (file_id,))
result = downloader.file_db.cursor.fetchone()
if not result:
# 文件不在数据库中,检查是否有同名文件在下载目录
import os
download_dir = downloader.download_dir
# 尝试从话题详情中获取文件名(这里需要额外的逻辑)
# 暂时返回文件不存在的状态
return {
"file_id": file_id,
"name": f"file_{file_id}",
"size": 0,
"download_status": "not_collected",
"local_exists": False,
"local_size": 0,
"local_path": None,
"is_complete": False,
"message": "文件信息未收集,请先运行文件收集任务"
}
file_name, file_size, download_status = result
# 检查本地文件是否存在
import os
safe_filename = "".join(c for c in file_name if c.isalnum() or c in '._-()()[]{}')
if not safe_filename:
safe_filename = f"file_{file_id}"
download_dir = downloader.download_dir
file_path = os.path.join(download_dir, safe_filename)
local_exists = os.path.exists(file_path)
local_size = os.path.getsize(file_path) if local_exists else 0
return {
"file_id": file_id,
"name": file_name,
"size": file_size,
"download_status": download_status or "pending",
"local_exists": local_exists,
"local_size": local_size,
"local_path": file_path if local_exists else None,
"is_complete": local_exists and local_size == file_size
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取文件状态失败: {str(e)}")
@app.get("/api/files/check-local/{group_id}")
async def check_local_file_status(group_id: str, file_name: str, file_size: int):
"""检查本地文件状态(不依赖数据库)"""
try:
crawler = get_crawler_for_group(group_id)
downloader = crawler.get_file_downloader()
# 清理文件名
import os
safe_filename = "".join(c for c in file_name if c.isalnum() or c in '._-()()[]{}')
if not safe_filename:
safe_filename = file_name
download_dir = downloader.download_dir
file_path = os.path.join(download_dir, safe_filename)
local_exists = os.path.exists(file_path)
local_size = os.path.getsize(file_path) if local_exists else 0
return {
"file_name": file_name,
"safe_filename": safe_filename,
"expected_size": file_size,
"local_exists": local_exists,
"local_size": local_size,
"local_path": file_path if local_exists else None,
"is_complete": local_exists and (file_size == 0 or local_size == file_size),
"download_dir": download_dir
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"检查本地文件失败: {str(e)}")
@app.get("/api/files/stats/{group_id}")
async def get_file_stats(group_id: str):
"""获取指定群组的文件统计信息"""
crawler = None
try:
crawler = get_crawler_for_group(group_id)
downloader = crawler.get_file_downloader()
# 获取文件数据库统计
stats = downloader.file_db.get_database_stats()
# 获取下载状态统计
# 首先检查是否有download_status列
downloader.file_db.cursor.execute("PRAGMA table_info(files)")
columns = [col[1] for col in downloader.file_db.cursor.fetchall()]
if 'download_status' in columns:
# 新版本数据库,有download_status列
downloader.file_db.cursor.execute("""
SELECT
COUNT(*) as total_files,
COUNT(CASE WHEN download_status = 'completed' THEN 1 END) as downloaded,
COUNT(CASE WHEN download_status = 'pending' THEN 1 END) as pending,
COUNT(CASE WHEN download_status = 'failed' THEN 1 END) as failed
FROM files
""")
download_stats = downloader.file_db.cursor.fetchone()
else:
# 旧版本数据库,没有download_status列,只统计总数
downloader.file_db.cursor.execute("SELECT COUNT(*) FROM files")
total_files = downloader.file_db.cursor.fetchone()[0]
download_stats = (total_files, 0, 0, 0) # 总数, 已下载, 待下载, 失败
result = {
"database_stats": stats,
"download_stats": {
"total_files": download_stats[0] if download_stats else 0,
"downloaded": download_stats[1] if download_stats else 0,
"pending": download_stats[2] if download_stats else 0,
"failed": download_stats[3] if download_stats else 0
}
}
return result
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取文件统计失败: {str(e)}")
finally:
# 确保关闭数据库连接
if crawler:
try:
if hasattr(crawler, 'file_downloader') and crawler.file_downloader:
if hasattr(crawler.file_downloader, 'file_db') and crawler.file_downloader.file_db:
crawler.file_downloader.file_db.close()
if hasattr(crawler, 'db') and crawler.db:
crawler.db.close()
print(f"🔒 已关闭群组 {group_id} 的数据库连接")
except Exception as e:
print(f"⚠️ 关闭数据库连接时出错: {e}")
@app.post("/api/files/clear/{group_id}")
async def clear_file_database(group_id: str):
"""删除指定群组的文件数据库文件"""
try:
path_manager = get_db_path_manager()
db_path = path_manager.get_files_db_path(group_id)
print(f"🗑️ 尝试删除文件数据库: {db_path}")
if os.path.exists(db_path):
# 强制关闭所有可能的数据库连接
import gc
import sqlite3
# 尝试多种方式关闭连接
try:
# 方式1:通过爬虫实例关闭
crawler = get_crawler_for_group(group_id)
downloader = crawler.get_file_downloader()
if hasattr(downloader, 'file_db') and downloader.file_db:
downloader.file_db.close()
if hasattr(crawler, 'db') and crawler.db:
crawler.db.close()
print(f"✅ 已关闭爬虫实例的数据库连接")
except Exception as e:
print(f"⚠️ 关闭爬虫数据库连接时出错: {e}")
# 方式2:强制垃圾回收
gc.collect()
# 方式3:等待一小段时间让连接释放
import time
time.sleep(0.5)
# 删除数据库文件
try:
os.remove(db_path)
print(f"✅ 文件数据库已删除: {db_path}")
# 同时删除该群组的图片缓存
try:
from image_cache_manager import get_image_cache_manager, clear_group_cache_manager
cache_manager = get_image_cache_manager(group_id)
success, message = cache_manager.clear_cache()
if success:
print(f"✅ 图片缓存已清空: {message}")
else:
print(f"⚠️ 清空图片缓存失败: {message}")
# 清除缓存管理器实例
clear_group_cache_manager(group_id)
except Exception as cache_error:
print(f"⚠️ 清空图片缓存时出错: {cache_error}")
return {"message": f"群组 {group_id} 的文件数据库和图片缓存已删除"}
except PermissionError as pe:
print(f"❌ 文件被占用,无法删除: {pe}")
raise HTTPException(status_code=500, detail=f"文件被占用,无法删除数据库文件。请稍后重试。")
else:
print(f"ℹ️ 文件数据库不存在: {db_path}")
return {"message": f"群组 {group_id} 的文件数据库不存在"}
except HTTPException:
raise
except Exception as e:
print(f"❌ 删除文件数据库失败: {str(e)}")
raise HTTPException(status_code=500, detail=f"删除文件数据库失败: {str(e)}")
@app.post("/api/topics/clear/{group_id}")
async def clear_topic_database(group_id: str):
"""删除指定群组的话题数据库文件"""
try:
path_manager = get_db_path_manager()
db_path = path_manager.get_topics_db_path(group_id)
print(f"🗑️ 尝试删除话题数据库: {db_path}")
if os.path.exists(db_path):
# 强制关闭所有可能的数据库连接
import gc
import time
# 尝试多种方式关闭连接
try:
# 方式1:通过爬虫实例关闭
crawler = get_crawler_for_group(group_id)
if hasattr(crawler, 'db') and crawler.db:
crawler.db.close()
if hasattr(crawler, 'file_downloader') and crawler.file_downloader:
if hasattr(crawler.file_downloader, 'file_db') and crawler.file_downloader.file_db:
crawler.file_downloader.file_db.close()
print(f"✅ 已关闭爬虫实例的数据库连接")
except Exception as e:
print(f"⚠️ 关闭爬虫数据库连接时出错: {e}")
# 方式2:强制垃圾回收
gc.collect()
# 方式3:等待一小段时间让连接释放
time.sleep(0.5)
# 删除数据库文件
try:
os.remove(db_path)
print(f"✅ 话题数据库已删除: {db_path}")
# 同时删除该群组的图片缓存
try:
from image_cache_manager import get_image_cache_manager, clear_group_cache_manager
cache_manager = get_image_cache_manager(group_id)
success, message = cache_manager.clear_cache()
if success:
print(f"✅ 图片缓存已清空: {message}")
else:
print(f"⚠️ 清空图片缓存失败: {message}")
# 清除缓存管理器实例
clear_group_cache_manager(group_id)
except Exception as cache_error:
print(f"⚠️ 清空图片缓存时出错: {cache_error}")
return {"message": f"群组 {group_id} 的话题数据库和图片缓存已删除"}
except PermissionError as pe:
print(f"❌ 文件被占用,无法删除: {pe}")
raise HTTPException(status_code=500, detail=f"文件被占用,无法删除数据库文件。请稍后重试。")
else:
print(f"ℹ️ 话题数据库不存在: {db_path}")
return {"message": f"群组 {group_id} 的话题数据库不存在"}
except HTTPException:
raise
except Exception as e:
print(f"❌ 删除话题数据库失败: {str(e)}")
raise HTTPException(status_code=500, detail=f"删除话题数据库失败: {str(e)}")
# 数据查询API路由
@app.get("/api/topics")
async def get_topics(page: int = 1, per_page: int = 20, search: Optional[str] = None):
"""获取话题列表"""
try:
crawler = get_crawler()
offset = (page - 1) * per_page
# 构建查询SQL
if search:
query = """
SELECT topic_id, title, create_time, likes_count, comments_count, reading_count
FROM topics
WHERE title LIKE ?
ORDER BY create_time DESC
LIMIT ? OFFSET ?
"""
params = (f"%{search}%", per_page, offset)
else:
query = """
SELECT topic_id, title, create_time, likes_count, comments_count, reading_count
FROM topics
ORDER BY create_time DESC
LIMIT ? OFFSET ?
"""
params = (per_page, offset)
crawler.db.cursor.execute(query, params)
topics = crawler.db.cursor.fetchall()
# 获取总数
if search:
crawler.db.cursor.execute("SELECT COUNT(*) FROM topics WHERE title LIKE ?", (f"%{search}%",))
else:
crawler.db.cursor.execute("SELECT COUNT(*) FROM topics")
total = crawler.db.cursor.fetchone()[0]
return {
"topics": [
{
"topic_id": topic[0],
"title": topic[1],
"create_time": topic[2],
"likes_count": topic[3],
"comments_count": topic[4],
"reading_count": topic[5]
}
for topic in topics
],
"pagination": {
"page": page,
"per_page": per_page,
"total": total,
"pages": (total + per_page - 1) // per_page
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取话题列表失败: {str(e)}")
@app.get("/api/files/{group_id}")
async def get_files(group_id: str, page: int = 1, per_page: int = 20, status: Optional[str] = None):
"""获取指定群组的文件列表"""
try:
crawler = get_crawler_for_group(group_id)
downloader = crawler.get_file_downloader()
offset = (page - 1) * per_page
# 构建查询SQL
if status:
query = """
SELECT file_id, name, size, download_count, create_time, download_status
FROM files
WHERE download_status = ?
ORDER BY create_time DESC
LIMIT ? OFFSET ?
"""
params = (status, per_page, offset)
else:
query = """
SELECT file_id, name, size, download_count, create_time, download_status
FROM files
ORDER BY create_time DESC
LIMIT ? OFFSET ?
"""
params = (per_page, offset)
downloader.file_db.cursor.execute(query, params)
files = downloader.file_db.cursor.fetchall()
# 获取总数
if status:
downloader.file_db.cursor.execute("SELECT COUNT(*) FROM files WHERE download_status = ?", (status,))
else:
downloader.file_db.cursor.execute("SELECT COUNT(*) FROM files")
total = downloader.file_db.cursor.fetchone()[0]
return {
"files": [
{
"file_id": file[0],
"name": file[1],
"size": file[2],
"download_count": file[3],
"create_time": file[4],
"download_status": file[5] if len(file) > 5 else "unknown"
}
for file in files
],
"pagination": {
"page": page,
"per_page": per_page,
"total": total,
"pages": (total + per_page - 1) // per_page
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取文件列表失败: {str(e)}")
# 群组相关API端点
@app.post("/api/local-groups/refresh")
async def refresh_local_groups():
"""
手动刷新本地群(output)扫描缓存;不抛错,异常时返回旧缓存。
"""
try:
ids = await asyncio.to_thread(scan_local_groups)
return {"success": True, "count": len(ids), "groups": sorted(list(ids))}
except Exception as e:
cached = get_cached_local_group_ids(force_refresh=False) or set()
# 不报错,返回降级结果
return {"success": False, "count": len(cached), "groups": sorted(list(cached)), "error": str(e)}
@app.get("/api/groups")
async def get_groups():
"""获取群组列表:账号群 ∪ 本地目录群(去重合并)"""
try:
# 自动构建群组→账号映射(多账号支持)
group_account_map = build_account_group_detection()
local_ids = get_cached_local_group_ids(force_refresh=False)
# 获取“当前账号”的群列表(若未配置则视为空集合)
groups_data: List[dict] = []
try:
if is_configured():
config = load_config()
auth_config = config.get('auth', {}) if config else {}
cookie = auth_config.get('cookie', '') or ''
if cookie and cookie != "your_cookie_here":
groups_data = fetch_groups_from_api(cookie)
except Exception as e:
# 不阻断,记录告警
print(f"⚠️ 获取账号群失败,降级为本地集合: {e}")
groups_data = []
# 组装账号侧群为字典(id -> info)
by_id: Dict[int, dict] = {}
for group in groups_data or []:
# 提取用户特定信息
user_specific = group.get('user_specific', {}) or {}
validity = user_specific.get('validity', {}) or {}
trial = user_specific.get('trial', {}) or {}
# 过期信息与状态
actual_expiry_time = trial.get('end_time') or validity.get('end_time')
is_trial = bool(trial.get('end_time'))
status = None
if actual_expiry_time:
from datetime import datetime, timezone
try:
end_time = datetime.fromisoformat(actual_expiry_time.replace('Z', '+00:00'))
now = datetime.now(timezone.utc)
days_until_expiry = (end_time - now).days
if days_until_expiry < 0:
status = 'expired'
elif days_until_expiry <= 7:
status = 'expiring_soon'
else:
status = 'active'
except Exception:
pass
gid = group.get('group_id')
try:
gid = int(gid)
except Exception:
continue
info = {
"group_id": gid,
"name": group.get('name', ''),
"type": group.get('type', ''),
"background_url": group.get('background_url', ''),
"owner": group.get('owner', {}) or {},
"statistics": group.get('statistics', {}) or {},
"status": status,
"create_time": group.get('create_time'),
"subscription_time": validity.get('begin_time'),
"expiry_time": actual_expiry_time,
"join_time": user_specific.get('join_time'),
"last_active_time": user_specific.get('last_active_time'),
"description": group.get('description', ''),
"is_trial": is_trial,
"trial_end_time": trial.get('end_time'),
"membership_end_time": validity.get('end_time'),
"account": group_account_map.get(str(gid)),
"source": "account"
}
by_id[gid] = info
# 合并本地目录群
for gid in local_ids or []:
try:
gid_int = int(gid)
except Exception:
continue
if gid_int in by_id:
# 标注来源为 account|local
src = by_id[gid_int].get("source", "account")
if "local" not in src:
by_id[gid_int]["source"] = "account|local"
else:
# 仅存在于本地
by_id[gid_int] = {
"group_id": gid_int,
"name": "本地群(未绑定账号)",
"type": "local",
"background_url": "",
"owner": {},
"statistics": {},
"status": None,
"create_time": None,
"subscription_time": None,
"expiry_time": None,
"join_time": None,
"last_active_time": None,
"description": "",
"is_trial": False,
"trial_end_time": None,
"membership_end_time": None,
"account": None,
"source": "local"
}
# 排序:按群ID升序;如需二级排序再按来源(账号优先)
merged = [by_id[k] for k in sorted(by_id.keys())]
return {
"groups": merged,
"total": len(merged)
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取群组列表失败: {str(e)}")
@app.get("/api/topics/{topic_id}/{group_id}")
async def get_topic_detail(topic_id: int, group_id: str):
"""获取话题详情"""
try:
crawler = get_crawler_for_group(group_id)
topic_detail = crawler.db.get_topic_detail(topic_id)
if not topic_detail:
raise HTTPException(status_code=404, detail="话题不存在")
return topic_detail
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取话题详情失败: {str(e)}")
@app.post("/api/topics/{topic_id}/{group_id}/refresh")
async def refresh_topic(topic_id: int, group_id: str):
"""实时更新单个话题信息"""
try:
crawler = get_crawler_for_group(group_id)
# 使用知识星球API获取最新话题信息
url = f"https://api.zsxq.com/v2/topics/{topic_id}/info"
headers = crawler.get_stealth_headers()
response = requests.get(url, headers=headers, timeout=30)
if response.status_code == 200:
data = response.json()
if data.get('succeeded') and data.get('resp_data'):
topic_data = data['resp_data']['topic']
# 只更新话题的统计信息,避免创建重复记录
success = crawler.db.update_topic_stats(topic_data)
if not success:
return {"success": False, "message": "话题不存在或更新失败"}
crawler.db.conn.commit()
return {
"success": True,
"message": "话题信息已更新",
"updated_data": {
"likes_count": topic_data.get('likes_count', 0),
"comments_count": topic_data.get('comments_count', 0),
"reading_count": topic_data.get('reading_count', 0),
"readers_count": topic_data.get('readers_count', 0)
}
}
else:
return {"success": False, "message": "API返回数据格式错误"}
else:
return {"success": False, "message": f"API请求失败: {response.status_code}"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"更新话题失败: {str(e)}")
@app.post("/api/topics/{topic_id}/{group_id}/fetch-comments")
async def fetch_more_comments(topic_id: int, group_id: str):
"""手动获取话题的更多评论"""
try:
crawler = get_crawler_for_group(group_id)
# 先获取话题基本信息
topic_detail = crawler.db.get_topic_detail(topic_id)
if not topic_detail:
raise HTTPException(status_code=404, detail="话题不存在")
comments_count = topic_detail.get('comments_count', 0)
if comments_count <= 8:
return {
"success": True,
"message": f"话题只有 {comments_count} 条评论,无需获取更多",
"comments_fetched": 0
}
# 获取更多评论
try:
additional_comments = crawler.fetch_all_comments(topic_id, comments_count)
if additional_comments:
crawler.db.import_additional_comments(topic_id, additional_comments)
crawler.db.conn.commit()
return {
"success": True,
"message": f"成功获取并导入 {len(additional_comments)} 条评论",
"comments_fetched": len(additional_comments)
}
else:
return {
"success": False,
"message": "获取评论失败,可能是权限限制或网络问题",
"comments_fetched": 0
}
except Exception as e:
return {
"success": False,
"message": f"获取评论时出错: {str(e)}",
"comments_fetched": 0
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取更多评论失败: {str(e)}")
@app.delete("/api/topics/{topic_id}/{group_id}")
async def delete_single_topic(topic_id: int, group_id: int):
"""删除单个话题及其所有关联数据"""
crawler = None
try:
# 使用指定群组的爬虫实例,以便复用其数据库连接
crawler = get_crawler_for_group(str(group_id))
# 检查话题是否存在且属于该群组
crawler.db.cursor.execute('SELECT COUNT(*) FROM topics WHERE topic_id = ? AND group_id = ?', (topic_id, group_id))
exists = crawler.db.cursor.fetchone()[0] > 0
if not exists:
return {"success": False, "message": "话题不存在"}
# 依赖顺序删除关联数据
tables_to_clean = [
'user_liked_emojis',
'like_emojis',
'likes',
'images',
'comments',
'answers',
'questions',
'articles',
'talks',
'topic_files',
'topic_tags'
]
for table in tables_to_clean:
crawler.db.cursor.execute(f'DELETE FROM {table} WHERE topic_id = ?', (topic_id,))
# 最后删除话题本身(限定群组)
crawler.db.cursor.execute('DELETE FROM topics WHERE topic_id = ? AND group_id = ?', (topic_id, group_id))
deleted = crawler.db.cursor.rowcount
crawler.db.conn.commit()
return {"success": True, "deleted_topic_id": topic_id, "deleted": deleted > 0}
except Exception as e:
try:
if crawler and hasattr(crawler, 'db') and crawler.db:
crawler.db.conn.rollback()
except Exception:
pass
raise HTTPException(status_code=500, detail=f"删除话题失败: {str(e)}")
# 单个话题采集 API
@app.post("/api/topics/fetch-single/{group_id}/{topic_id}")
async def fetch_single_topic(group_id: str, topic_id: int, fetch_comments: bool = True):
"""爬取并导入单个话题(用于特殊话题测试),可选拉取完整评论"""
try:
# 使用该群的自动匹配账号
crawler = get_crawler_for_group(str(group_id))
# 拉取话题详细信息
url = f"https://api.zsxq.com/v2/topics/{topic_id}/info"
headers = crawler.get_stealth_headers()
response = requests.get(url, headers=headers, timeout=30)
if response.status_code != 200:
raise HTTPException(status_code=response.status_code, detail="API请求失败")
data = response.json()
if not data.get("succeeded") or not data.get("resp_data"):
raise HTTPException(status_code=400, detail="API返回失败")
topic = (data.get("resp_data", {}) or {}).get("topic", {}) or {}
if not topic:
raise HTTPException(status_code=404, detail="未获取到有效话题数据")
# 校验话题所属群组一致性
topic_group_id = str((topic.get("group") or {}).get("group_id", ""))
if topic_group_id and topic_group_id != str(group_id):
raise HTTPException(status_code=400, detail="该话题不属于当前群组")
# 判断话题是否已存在
crawler.db.cursor.execute('SELECT topic_id FROM topics WHERE topic_id = ?', (topic_id,))
existed = crawler.db.cursor.fetchone() is not None
# 导入话题完整数据
crawler.db.import_topic_data(topic)
crawler.db.conn.commit()
# 可选:获取完整评论
comments_fetched = 0
if fetch_comments:
comments_count = topic.get("comments_count", 0) or 0
if comments_count > 0:
try:
additional_comments = crawler.fetch_all_comments(topic_id, comments_count)
if additional_comments:
crawler.db.import_additional_comments(topic_id, additional_comments)
crawler.db.conn.commit()
comments_fetched = len(additional_comments)
except Exception as e:
# 不阻塞主流程
print(f"⚠️ 单话题评论获取失败: {e}")
return {
"success": True,
"topic_id": topic_id,
"group_id": int(group_id),
"imported": "updated" if existed else "created",
"comments_fetched": comments_fetched
}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"单个话题采集失败: {str(e)}")
# 标签相关API端点
@app.get("/api/groups/{group_id}/tags")
async def get_group_tags(group_id: str):
"""获取指定群组的所有标签"""
try:
crawler = get_crawler_for_group(group_id)
tags = crawler.db.get_tags_by_group(int(group_id))
return {
"tags": tags,
"total": len(tags)
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取标签列表失败: {str(e)}")
@app.get("/api/groups/{group_id}/tags/{tag_id}/topics")
async def get_topics_by_tag(group_id: int, tag_id: int, page: int = 1, per_page: int = 20):
"""根据标签获取指定群组的话题列表"""
try:
# 使用指定群组的爬虫实例
crawler = get_crawler_for_group(str(group_id))
# 验证标签是否存在于该群组中
crawler.db.cursor.execute('SELECT COUNT(*) FROM tags WHERE tag_id = ? AND group_id = ?', (tag_id, group_id))
tag_count = crawler.db.cursor.fetchone()[0]
if tag_count == 0:
raise HTTPException(status_code=404, detail="标签在该群组中不存在")
result = crawler.db.get_topics_by_tag(tag_id, page, per_page)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=f"根据标签获取话题失败: {str(e)}")
@app.get("/api/proxy-image")
async def proxy_image(url: str, group_id: str = None):
"""代理图片请求,支持本地缓存"""
try:
cache_manager = get_image_cache_manager(group_id)
# 检查是否已缓存
if cache_manager.is_cached(url):
cached_path = cache_manager.get_cached_path(url)
if cached_path and cached_path.exists():
# 返回缓存的图片
content_type = mimetypes.guess_type(str(cached_path))[0] or 'image/jpeg'
with open(cached_path, 'rb') as f:
content = f.read()
return Response(
content=content,
media_type=content_type,
headers={
'Cache-Control': 'public, max-age=86400', # 缓存24小时
'Access-Control-Allow-Origin': '*',
'X-Cache-Status': 'HIT'
}
)
# 下载并缓存图片
success, cached_path, error = cache_manager.download_and_cache(url)
if success and cached_path and cached_path.exists():
content_type = mimetypes.guess_type(str(cached_path))[0] or 'image/jpeg'
with open(cached_path, 'rb') as f:
content = f.read()
return Response(
content=content,
media_type=content_type,
headers={
'Cache-Control': 'public, max-age=86400',
'Access-Control-Allow-Origin': '*',
'X-Cache-Status': 'MISS'
}
)
else:
raise HTTPException(status_code=404, detail=f"图片加载失败: {error}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"代理图片失败: {str(e)}")
@app.get("/api/cache/images/info/{group_id}")
async def get_image_cache_info(group_id: str):
"""获取指定群组的图片缓存统计信息"""
try:
cache_manager = get_image_cache_manager(group_id)
return cache_manager.get_cache_info()
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取缓存信息失败: {str(e)}")
@app.delete("/api/cache/images/{group_id}")
async def clear_image_cache(group_id: str):
"""清空指定群组的图片缓存"""
try:
cache_manager = get_image_cache_manager(group_id)
success, message = cache_manager.clear_cache()
if success:
return {"success": True, "message": message}
else:
raise HTTPException(status_code=500, detail=message)
except Exception as e:
raise HTTPException(status_code=500, detail=f"清空缓存失败: {str(e)}")
@app.get("/api/settings/crawl")
async def get_crawl_settings():
"""获取话题爬取设置"""
try:
# 返回默认设置
return {
"crawl_interval_min": 2.0,
"crawl_interval_max": 5.0,
"long_sleep_interval_min": 180.0,
"long_sleep_interval_max": 300.0,
"pages_per_batch": 15
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取爬取设置失败: {str(e)}")
@app.post("/api/settings/crawl")
async def update_crawl_settings(settings: dict):
"""更新话题爬取设置"""
try:
# 这里可以将设置保存到配置文件或数据库
# 目前只是返回成功,实际设置通过API参数传递
return {"success": True, "message": "爬取设置已更新"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"更新爬取设置失败: {str(e)}")
@app.get("/api/groups/{group_id}/info")
async def get_group_info(group_id: str):
"""获取群组信息(带本地回退,避免401/500导致前端报错)"""
try:
# 自动匹配该群组所属账号,获取对应Cookie
cookie = get_cookie_for_group(group_id)
# 本地回退数据构造(不访问官方API)
def build_fallback(source: str = "fallback", note: str = None) -> dict:
files_count = 0
try:
crawler = get_crawler_for_group(group_id)
downloader = crawler.get_file_downloader()
try:
downloader.file_db.cursor.execute("SELECT COUNT(*) FROM files")
row = downloader.file_db.cursor.fetchone()
files_count = (row[0] or 0) if row else 0
except Exception:
files_count = 0
except Exception:
files_count = 0
try:
gid = int(group_id)
except Exception:
gid = group_id
result = {
"group_id": gid,
"name": f"群组 {group_id}",
"description": "",
"statistics": {"files": {"count": files_count}},
"background_url": None,
"account": am_get_account_summary_for_group(group_id),
"source": source,
}
if note:
result["note"] = note
return result
# 若没有可用 Cookie,直接返回本地回退,避免抛 400/500
if not cookie:
return build_fallback(note="no_cookie")
# 调用官方接口
url = f"https://api.zsxq.com/v2/groups/{group_id}"
headers = {
'Cookie': cookie,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers, timeout=30)
if response.status_code == 200:
data = response.json()
if data.get('succeeded'):
group_data = data.get('resp_data', {}).get('group', {})
return {
"group_id": group_data.get('group_id'),
"name": group_data.get('name'),
"description": group_data.get('description'),
"statistics": group_data.get('statistics', {}),
"background_url": group_data.get('background_url'),
"account": am_get_account_summary_for_group(group_id),
"source": "remote"
}
# 官方返回非 succeeded,也走回退
return build_fallback(note="remote_response_failed")
else:
# 授权失败/权限不足 → 使用本地回退(200返回,减少前端告警)
if response.status_code in (401, 403):
return build_fallback(note=f"remote_api_{response.status_code}")
# 其他状态码也回退
return build_fallback(note=f"remote_api_{response.status_code}")
except Exception:
# 任何异常都回退为本地信息,避免 500
return build_fallback(note="exception_fallback")
@app.get("/api/groups/{group_id}/topics")
async def get_group_topics(group_id: int, page: int = 1, per_page: int = 20, search: Optional[str] = None):
"""获取指定群组的话题列表"""
try:
# 使用指定群组的爬虫实例
crawler = get_crawler_for_group(str(group_id))
offset = (page - 1) * per_page
# 构建查询SQL - 包含所有内容类型
if search:
query = """
SELECT
t.topic_id, t.title, t.create_time, t.likes_count, t.comments_count,
t.reading_count, t.type, t.digested, t.sticky,
q.text as question_text,
a.text as answer_text,
tk.text as talk_text,
u.user_id, u.name, u.avatar_url, t.imported_at
FROM topics t
LEFT JOIN questions q ON t.topic_id = q.topic_id
LEFT JOIN answers a ON t.topic_id = a.topic_id
LEFT JOIN talks tk ON t.topic_id = tk.topic_id
LEFT JOIN users u ON tk.owner_user_id = u.user_id
WHERE t.group_id = ? AND (t.title LIKE ? OR q.text LIKE ? OR tk.text LIKE ?)
ORDER BY t.create_time DESC
LIMIT ? OFFSET ?
"""
params = (group_id, f"%{search}%", f"%{search}%", f"%{search}%", per_page, offset)
else:
query = """
SELECT
t.topic_id, t.title, t.create_time, t.likes_count, t.comments_count,
t.reading_count, t.type, t.digested, t.sticky,
q.text as question_text,
a.text as answer_text,
tk.text as talk_text,
u.user_id, u.name, u.avatar_url, t.imported_at
FROM topics t
LEFT JOIN questions q ON t.topic_id = q.topic_id
LEFT JOIN answers a ON t.topic_id = a.topic_id
LEFT JOIN talks tk ON t.topic_id = tk.topic_id
LEFT JOIN users u ON tk.owner_user_id = u.user_id
WHERE t.group_id = ?
ORDER BY t.create_time DESC
LIMIT ? OFFSET ?
"""
params = (group_id, per_page, offset)
crawler.db.cursor.execute(query, params)
topics = crawler.db.cursor.fetchall()
# 获取总数
if search:
crawler.db.cursor.execute("SELECT COUNT(*) FROM topics WHERE group_id = ? AND title LIKE ?", (group_id, f"%{search}%"))
else:
crawler.db.cursor.execute("SELECT COUNT(*) FROM topics WHERE group_id = ?", (group_id,))
total = crawler.db.cursor.fetchone()[0]
# 处理话题数据
topics_list = []
for topic in topics:
topic_data = {
"topic_id": topic[0],
"title": topic[1],
"create_time": topic[2],
"likes_count": topic[3],
"comments_count": topic[4],
"reading_count": topic[5],
"type": topic[6],
"digested": bool(topic[7]) if topic[7] is not None else False,
"sticky": bool(topic[8]) if topic[8] is not None else False,
"imported_at": topic[15] if len(topic) > 15 else None # 获取时间
}
# 添加内容文本
if topic[6] == 'q&a':
# 问答类型话题
topic_data['question_text'] = topic[9] if topic[9] else ''
topic_data['answer_text'] = topic[10] if topic[10] else ''
else:
# 其他类型话题(talk、article等)
topic_data['talk_text'] = topic[11] if topic[11] else ''
if topic[12]: # 有作者信息
topic_data['author'] = {
'user_id': topic[12],
'name': topic[13],
'avatar_url': topic[14]
}
topics_list.append(topic_data)
return {
"topics": topics_list,
"pagination": {
"page": page,
"per_page": per_page,
"total": total,
"pages": (total + per_page - 1) // per_page
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取群组话题失败: {str(e)}")
@app.get("/api/groups/{group_id}/stats")
async def get_group_stats(group_id: int):
"""获取指定群组的统计信息"""
try:
# 使用指定群组的爬虫实例
crawler = get_crawler_for_group(str(group_id))
cursor = crawler.db.cursor
# 获取话题统计
cursor.execute("SELECT COUNT(*) FROM topics WHERE group_id = ?", (group_id,))
topics_count = cursor.fetchone()[0]
# 获取用户统计 - 从talks表获取,因为topics表没有user_id字段
cursor.execute("""
SELECT COUNT(DISTINCT t.owner_user_id)
FROM talks t
JOIN topics tp ON t.topic_id = tp.topic_id
WHERE tp.group_id = ?
""", (group_id,))
users_count = cursor.fetchone()[0]
# 获取最新话题时间
cursor.execute("SELECT MAX(create_time) FROM topics WHERE group_id = ?", (group_id,))
latest_topic_time = cursor.fetchone()[0]
# 获取最早话题时间
cursor.execute("SELECT MIN(create_time) FROM topics WHERE group_id = ?", (group_id,))
earliest_topic_time = cursor.fetchone()[0]
# 获取总点赞数
cursor.execute("SELECT SUM(likes_count) FROM topics WHERE group_id = ?", (group_id,))
total_likes = cursor.fetchone()[0] or 0
# 获取总评论数
cursor.execute("SELECT SUM(comments_count) FROM topics WHERE group_id = ?", (group_id,))
total_comments = cursor.fetchone()[0] or 0
# 获取总阅读数
cursor.execute("SELECT SUM(reading_count) FROM topics WHERE group_id = ?", (group_id,))
total_readings = cursor.fetchone()[0] or 0
return {
"group_id": group_id,
"topics_count": topics_count,
"users_count": users_count,
"latest_topic_time": latest_topic_time,
"earliest_topic_time": earliest_topic_time,
"total_likes": total_likes,
"total_comments": total_comments,
"total_readings": total_readings
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取群组统计失败: {str(e)}")
@app.get("/api/groups/{group_id}/database-info")
async def get_group_database_info(group_id: int):
"""获取指定群组的数据库信息"""
try:
path_manager = get_db_path_manager()
db_info = path_manager.get_database_info(str(group_id))
return {
"group_id": group_id,
"database_info": db_info
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取数据库信息失败: {str(e)}")
@app.delete("/api/groups/{group_id}/topics")
async def delete_group_topics(group_id: int):
"""删除指定群组的所有话题数据"""
try:
# 使用指定群组的爬虫实例
crawler = get_crawler_for_group(str(group_id))
# 获取删除前的统计信息
crawler.db.cursor.execute('SELECT COUNT(*) FROM topics WHERE group_id = ?', (group_id,))
topics_count = crawler.db.cursor.fetchone()[0]
if topics_count == 0:
return {
"message": "该群组没有话题数据",
"deleted_count": 0
}
# 删除相关数据(按照外键依赖顺序)
tables_to_clean = [
('user_liked_emojis', 'topic_id'),
('like_emojis', 'topic_id'),
('likes', 'topic_id'),
('images', 'topic_id'),
('comments', 'topic_id'),
('answers', 'topic_id'),
('questions', 'topic_id'),
('articles', 'topic_id'),
('talks', 'topic_id'),
('topic_files', 'topic_id'), # 添加话题文件表
('topic_tags', 'topic_id'), # 添加话题标签关联表
('topics', 'group_id')
]
deleted_counts = {}
for table, id_column in tables_to_clean:
if id_column == 'group_id':
# 直接按group_id删除
crawler.db.cursor.execute(f'DELETE FROM {table} WHERE {id_column} = ?', (group_id,))
else:
# 按topic_id删除,需要先找到该群组的所有topic_id
crawler.db.cursor.execute(f'''
DELETE FROM {table}
WHERE {id_column} IN (
SELECT topic_id FROM topics WHERE group_id = ?
)
''', (group_id,))
deleted_counts[table] = crawler.db.cursor.rowcount
# 提交事务
crawler.db.conn.commit()
return {
"message": f"成功删除群组 {group_id} 的所有话题数据",
"deleted_topics_count": topics_count,
"deleted_details": deleted_counts
}
except Exception as e:
# 回滚事务
crawler.db.conn.rollback()
raise HTTPException(status_code=500, detail=f"删除话题数据失败: {str(e)}")
@app.get("/api/tasks/{task_id}/logs")
async def get_task_logs(task_id: str):
"""获取任务日志"""
if task_id not in task_logs:
raise HTTPException(status_code=404, detail="任务不存在")
return {
"task_id": task_id,
"logs": task_logs[task_id]
}
@app.get("/api/tasks/{task_id}/stream")
async def stream_task_logs(task_id: str):
"""SSE流式传输任务日志"""
async def event_stream():
# 初始化连接
if task_id not in sse_connections:
sse_connections[task_id] = []
# 发送历史日志
if task_id in task_logs:
for log in task_logs[task_id]:
yield f"data: {json.dumps({'type': 'log', 'message': log})}\n\n"
# 发送任务状态
if task_id in current_tasks:
task = current_tasks[task_id]
yield f"data: {json.dumps({'type': 'status', 'status': task['status'], 'message': task['message']})}\n\n"
# 记录当前日志数量,用于检测新日志
last_log_count = len(task_logs.get(task_id, []))
# 保持连接活跃
try:
while True:
# 检查是否有新日志
current_log_count = len(task_logs.get(task_id, []))
if current_log_count > last_log_count:
# 发送新日志
new_logs = task_logs[task_id][last_log_count:]
for log in new_logs:
yield f"data: {json.dumps({'type': 'log', 'message': log})}\n\n"
last_log_count = current_log_count
# 检查任务状态变化
if task_id in current_tasks:
task = current_tasks[task_id]
yield f"data: {json.dumps({'type': 'status', 'status': task['status'], 'message': task['message']})}\n\n"
if task['status'] in ['completed', 'failed', 'cancelled']:
break
# 发送心跳
yield f"data: {json.dumps({'type': 'heartbeat'})}\n\n"
await asyncio.sleep(0.5) # 更频繁的检查
except asyncio.CancelledError:
# 客户端断开连接
pass
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
}
)
# 图片代理API
@app.get("/api/proxy/image")
async def proxy_image(url: str):
"""图片代理,解决盗链问题"""
import requests
from fastapi.responses import Response
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Referer': 'https://wx.zsxq.com/',
'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
return Response(
content=response.content,
media_type=response.headers.get('content-type', 'image/jpeg'),
headers={
'Cache-Control': 'public, max-age=3600',
'Access-Control-Allow-Origin': '*'
}
)
except Exception as e:
raise HTTPException(status_code=404, detail=f"图片加载失败: {str(e)}")
# 设置相关API路由
@app.get("/api/settings/crawler")
async def get_crawler_settings():
"""获取爬虫设置"""
try:
crawler = get_crawler_safe()
if not crawler:
return {
"min_delay": 2.0,
"max_delay": 5.0,
"long_delay_interval": 15,
"timestamp_offset_ms": 1,
"debug_mode": False
}
return {
"min_delay": crawler.min_delay,
"max_delay": crawler.max_delay,
"long_delay_interval": crawler.long_delay_interval,
"timestamp_offset_ms": crawler.timestamp_offset_ms,
"debug_mode": crawler.debug_mode
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取爬虫设置失败: {str(e)}")
class CrawlerSettingsRequest(BaseModel):
min_delay: float = Field(default=2.0, ge=0.5, le=10.0)
max_delay: float = Field(default=5.0, ge=1.0, le=20.0)
long_delay_interval: int = Field(default=15, ge=5, le=100)
timestamp_offset_ms: int = Field(default=1, ge=0, le=1000)
debug_mode: bool = Field(default=False)
@app.post("/api/settings/crawler")
async def update_crawler_settings(request: CrawlerSettingsRequest):
"""更新爬虫设置"""
try:
crawler = get_crawler_safe()
if not crawler:
raise HTTPException(status_code=404, detail="爬虫未初始化")
# 验证设置
if request.min_delay >= request.max_delay:
raise HTTPException(status_code=400, detail="最小延迟必须小于最大延迟")
# 更新设置
crawler.min_delay = request.min_delay
crawler.max_delay = request.max_delay
crawler.long_delay_interval = request.long_delay_interval
crawler.timestamp_offset_ms = request.timestamp_offset_ms
crawler.debug_mode = request.debug_mode
return {
"message": "爬虫设置已更新",
"settings": {
"min_delay": crawler.min_delay,
"max_delay": crawler.max_delay,
"long_delay_interval": crawler.long_delay_interval,
"timestamp_offset_ms": crawler.timestamp_offset_ms,
"debug_mode": crawler.debug_mode
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"更新爬虫设置失败: {str(e)}")
@app.get("/api/settings/downloader")
async def get_downloader_settings():
"""获取文件下载器设置"""
try:
crawler = get_crawler_safe()
if not crawler:
return {
"download_interval_min": 30,
"download_interval_max": 60,
"long_delay_interval": 10,
"long_delay_min": 300,
"long_delay_max": 600
}
downloader = crawler.get_file_downloader()
return {
"download_interval_min": downloader.download_interval_min,
"download_interval_max": downloader.download_interval_max,
"long_delay_interval": downloader.long_delay_interval,
"long_delay_min": downloader.long_delay_min,
"long_delay_max": downloader.long_delay_max
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取下载器设置失败: {str(e)}")
class DownloaderSettingsRequest(BaseModel):
download_interval_min: int = Field(default=30, ge=1, le=300)
download_interval_max: int = Field(default=60, ge=5, le=600)
long_delay_interval: int = Field(default=10, ge=1, le=100)
long_delay_min: int = Field(default=300, ge=60, le=1800)
long_delay_max: int = Field(default=600, ge=120, le=3600)
@app.post("/api/settings/downloader")
async def update_downloader_settings(request: DownloaderSettingsRequest):
"""更新文件下载器设置"""
try:
crawler = get_crawler_safe()
if not crawler:
raise HTTPException(status_code=404, detail="爬虫未初始化")
# 验证设置
if request.download_interval_min >= request.download_interval_max:
raise HTTPException(status_code=400, detail="最小下载间隔必须小于最大下载间隔")
if request.long_delay_min >= request.long_delay_max:
raise HTTPException(status_code=400, detail="最小长休眠时间必须小于最大长休眠时间")
downloader = crawler.get_file_downloader()
# 更新设置
downloader.download_interval_min = request.download_interval_min
downloader.download_interval_max = request.download_interval_max
downloader.long_delay_interval = request.long_delay_interval
downloader.long_delay_min = request.long_delay_min
downloader.long_delay_max = request.long_delay_max
return {
"message": "下载器设置已更新",
"settings": {
"download_interval_min": downloader.download_interval_min,
"download_interval_max": downloader.download_interval_max,
"long_delay_interval": downloader.long_delay_interval,
"long_delay_min": downloader.long_delay_min,
"long_delay_max": downloader.long_delay_max
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"更新下载器设置失败: {str(e)}")
# =========================
# 自动账号匹配缓存与辅助函数
# =========================
ACCOUNT_DETECT_TTL_SECONDS = 300
_account_detect_cache: Dict[str, Any] = {
"built_at": 0,
"group_to_account": {},
"cookie_by_account": {}
}
def _get_all_account_sources() -> List[Dict[str, Any]]:
"""组合账号来源:accounts.json + config.toml默认账号"""
sources: List[Dict[str, Any]] = []
try:
# 账号管理中的账号(含cookie)
accounts = am_get_accounts(mask_cookie=False)
if accounts:
sources.extend(accounts)
except Exception:
pass
# 追加 config.toml 的默认cookie作为伪账号
try:
cfg = load_config()
auth = cfg.get('auth', {}) if cfg else {}
default_cookie = auth.get('cookie', '')
if default_cookie and default_cookie != "your_cookie_here":
sources.append({
"id": "default",
"name": "默认账号",
"cookie": default_cookie,
"is_default": True,
"created_at": None
})
except Exception:
pass
return sources
def build_account_group_detection(force_refresh: bool = False) -> Dict[str, Dict[str, Any]]:
"""
构建自动匹配映射:group_id -> 账号摘要
遍历所有账号来源,调用官方 /v2/groups 获取其可访问群组进行比对。
使用内存缓存减少频繁请求。
"""
now = time.time()
cache = _account_detect_cache
if (not force_refresh
and cache.get("group_to_account")
and now - cache.get("built_at", 0) < ACCOUNT_DETECT_TTL_SECONDS):
return cache["group_to_account"]
group_to_account: Dict[str, Dict[str, Any]] = {}
cookie_by_account: Dict[str, str] = {}
sources = _get_all_account_sources()
for src in sources:
cookie = src.get("cookie", "")
acc_id = src.get("id", "default")
if not cookie or cookie == "your_cookie_here":
continue
# 记录账号对应cookie
cookie_by_account[acc_id] = cookie
try:
groups = fetch_groups_from_api(cookie)
for g in groups or []:
gid = str(g.get("group_id"))
if gid and gid not in group_to_account:
group_to_account[gid] = {
"id": acc_id,
"name": src.get("name") or ("默认账号" if acc_id == "default" else acc_id),
"is_default": bool(src.get("is_default") or acc_id == "default"),
"created_at": src.get("created_at"),
"cookie": "***"
}
except Exception:
# 忽略单个账号失败
continue
cache["group_to_account"] = group_to_account
cache["cookie_by_account"] = cookie_by_account
cache["built_at"] = now
return group_to_account
def get_cookie_for_group(group_id: str) -> str:
"""根据自动匹配结果选择用于该群组的Cookie,失败则回退到config.toml"""
mapping = build_account_group_detection(force_refresh=False)
summary = mapping.get(str(group_id))
cookie = None
if summary:
cookie = _account_detect_cache.get("cookie_by_account", {}).get(summary["id"])
if not cookie:
cfg = load_config()
auth = cfg.get('auth', {}) if cfg else {}
cookie = auth.get('cookie', '')
return cookie
def get_account_summary_for_group_auto(group_id: str) -> Optional[Dict[str, Any]]:
"""返回自动匹配到的账号摘要;若无命中且存在默认cookie,则返回默认占位摘要"""
mapping = build_account_group_detection(force_refresh=False)
summary = mapping.get(str(group_id))
if summary:
return summary
cfg = load_config()
auth = cfg.get('auth', {}) if cfg else {}
default_cookie = auth.get('cookie', '')
if default_cookie:
return {
"id": "default",
"name": "默认账号",
"is_default": True,
"created_at": None,
"cookie": "***"
}
return None
# =========================
# 新增:按时间区间爬取
# =========================
class CrawlTimeRangeRequest(BaseModel):
startTime: Optional[str] = Field(default=None, description="开始时间,支持 YYYY-MM-DD 或 ISO8601,缺省则按 lastDays 推导")
endTime: Optional[str] = Field(default=None, description="结束时间,默认当前时间(本地东八区)")
lastDays: Optional[int] = Field(default=None, ge=1, le=3650, description="最近N天(与 startTime/endTime 互斥优先;当 startTime 缺省时可用)")
perPage: Optional[int] = Field(default=20, ge=1, le=100, description="每页数量")
# 可选的随机间隔设置(与其他爬取接口保持一致)
crawlIntervalMin: Optional[float] = Field(default=None, ge=1.0, le=60.0, description="爬取间隔最小值(秒)")
crawlIntervalMax: Optional[float] = Field(default=None, ge=1.0, le=60.0, description="爬取间隔最大值(秒)")
longSleepIntervalMin: Optional[float] = Field(default=None, ge=60.0, le=3600.0, description="长休眠间隔最小值(秒)")
longSleepIntervalMax: Optional[float] = Field(default=None, ge=60.0, le=3600.0, description="长休眠间隔最大值(秒)")
pagesPerBatch: Optional[int] = Field(default=None, ge=5, le=50, description="每批次页面数")
def run_crawl_time_range_task(task_id: str, group_id: str, request: "CrawlTimeRangeRequest"):
"""后台执行“按时间区间爬取”任务:仅导入位于区间 [startTime, endTime] 内的话题"""
try:
from datetime import datetime, timedelta, timezone
# 解析用户输入时间
def parse_user_time(s: Optional[str]) -> Optional[datetime]:
if not s:
return None
t = s.strip()
try:
# 仅日期:YYYY-MM-DD -> 当天00:00:00(东八区)
if len(t) == 10 and t[4] == '-' and t[7] == '-':
dt = datetime.strptime(t, '%Y-%m-%d')
return dt.replace(tzinfo=timezone(timedelta(hours=8)))
# datetime-local (无秒):YYYY-MM-DDTHH:MM
if 'T' in t and len(t) == 16:
t = t + ':00'
# 尾部Z -> +00:00
if t.endswith('Z'):
t = t.replace('Z', '+00:00')
# 兼容 +0800 -> +08:00
if len(t) >= 24 and (t[-5] in ['+', '-']) and t[-3] != ':':
t = t[:-2] + ':' + t[-2:]
dt = datetime.fromisoformat(t)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone(timedelta(hours=8)))
return dt
except Exception:
return None
bj_tz = timezone(timedelta(hours=8))
now_bj = datetime.now(bj_tz)
start_dt = parse_user_time(request.startTime)
end_dt = parse_user_time(request.endTime) if request.endTime else None
# 若指定了最近N天,以 end_dt(默认现在)为终点推导 start_dt
if request.lastDays and request.lastDays > 0:
if end_dt is None:
end_dt = now_bj
start_dt = end_dt - timedelta(days=request.lastDays)
# 默认 end_dt = 现在
if end_dt is None:
end_dt = now_bj
# 默认 start_dt = end_dt - 30天
if start_dt is None:
start_dt = end_dt - timedelta(days=30)
# 保证时间顺序
if start_dt > end_dt:
start_dt, end_dt = end_dt, start_dt
update_task(task_id, "running", "开始按时间区间爬取...")
add_task_log(task_id, f"🗓️ 时间范围: {start_dt.isoformat()} ~ {end_dt.isoformat()}")
# 停止检查
def stop_check():
return is_task_stopped(task_id)
# 爬虫实例(绑定该群组)
def log_callback(message: str):
add_task_log(task_id, message)
cookie = get_cookie_for_group(group_id)
path_manager = get_db_path_manager()
db_path = path_manager.get_topics_db_path(group_id)
crawler = ZSXQInteractiveCrawler(cookie, group_id, db_path, log_callback)
crawler.stop_check_func = stop_check
# 可选:应用自定义间隔设置
if any([
request.crawlIntervalMin, request.crawlIntervalMax,
request.longSleepIntervalMin, request.longSleepIntervalMax,
request.pagesPerBatch
]):
crawler.set_custom_intervals(
crawl_interval_min=request.crawlIntervalMin,
crawl_interval_max=request.crawlIntervalMax,
long_sleep_interval_min=request.longSleepIntervalMin,
long_sleep_interval_max=request.longSleepIntervalMax,
pages_per_batch=request.pagesPerBatch
)
per_page = request.perPage or 20
total_stats = {'new_topics': 0, 'updated_topics': 0, 'errors': 0, 'pages': 0}
end_time_param = None # 从最新开始
max_retries_per_page = 10
while True:
if is_task_stopped(task_id):
add_task_log(task_id, "🛑 任务已停止")
break
retry = 0
page_processed = False
last_time_dt_in_page = None
while retry < max_retries_per_page:
if is_task_stopped(task_id):
break
data = crawler.fetch_topics_safe(
scope="all",
count=per_page,
end_time=end_time_param,
is_historical=True if end_time_param else False
)
# 会员过期
if data and isinstance(data, dict) and data.get('expired'):
add_task_log(task_id, f"❌ 会员已过期: {data.get('message')}")
update_task(task_id, "failed", "会员已过期", data)
return
if not data:
retry += 1
total_stats['errors'] += 1
add_task_log(task_id, f"❌ 页面获取失败 (重试{retry}/{max_retries_per_page})")
continue
topics = (data.get('resp_data', {}) or {}).get('topics', []) or []
if not topics:
add_task_log(task_id, "📭 无更多数据,任务结束")
page_processed = True
break
# 过滤时间范围
from datetime import datetime
filtered = []
for t in topics:
ts = t.get('create_time')
dt = None
try:
if ts:
ts_fixed = ts.replace('+0800', '+08:00') if ts.endswith('+0800') else ts
dt = datetime.fromisoformat(ts_fixed)
except Exception:
dt = None
if dt:
last_time_dt_in_page = dt # 该页数据按时间降序;循环结束后持有最后(最老)时间
if start_dt <= dt <= end_dt:
filtered.append(t)
# 仅导入时间范围内的数据
if filtered:
filtered_data = {'succeeded': True, 'resp_data': {'topics': filtered}}
page_stats = crawler.store_batch_data(filtered_data)
total_stats['new_topics'] += page_stats.get('new_topics', 0)
total_stats['updated_topics'] += page_stats.get('updated_topics', 0)
total_stats['errors'] += page_stats.get('errors', 0)
total_stats['pages'] += 1
page_processed = True
# 计算下一页的 end_time(使用该页最老话题时间 - 偏移毫秒)
oldest_in_page = topics[-1].get('create_time')
try:
dt_oldest = datetime.fromisoformat(oldest_in_page.replace('+0800', '+08:00'))
dt_oldest = dt_oldest - timedelta(milliseconds=crawler.timestamp_offset_ms)
end_time_param = dt_oldest.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
except Exception:
end_time_param = oldest_in_page
# 若该页最老时间已早于 start_dt,则后续更老数据均不在范围内,结束
if last_time_dt_in_page and last_time_dt_in_page < start_dt:
add_task_log(task_id, "✅ 已到达起始时间之前,任务结束")
break
# 成功处理后进行长休眠检查
crawler.check_page_long_delay()
break # 成功后跳出重试循环
if not page_processed:
add_task_log(task_id, "🚫 当前页面达到最大重试次数,终止任务")
break
# 结束条件:没有下一页时间或已越过起始边界
if not end_time_param or (last_time_dt_in_page and last_time_dt_in_page < start_dt):
break
update_task(task_id, "completed", "时间区间爬取完成", total_stats)
except Exception as e:
if not is_task_stopped(task_id):
add_task_log(task_id, f"❌ 时间区间爬取失败: {str(e)}")
update_task(task_id, "failed", f"时间区间爬取失败: {str(e)}")
@app.post("/api/crawl/range/{group_id}")
async def crawl_by_time_range(group_id: str, request: CrawlTimeRangeRequest, background_tasks: BackgroundTasks):
"""按时间区间爬取话题(支持最近N天或自定义开始/结束时间)"""
try:
task_id = create_task("crawl_time_range", f"按时间区间爬取 (群组: {group_id})")
background_tasks.add_task(run_crawl_time_range_task, task_id, group_id, request)
return {"task_id": task_id, "message": "任务已创建,正在后台执行"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"创建时间区间爬取任务失败: {str(e)}")
if __name__ == "__main__":
import sys
port = 8001 if len(sys.argv) > 1 and sys.argv[1] == "--port" and len(sys.argv) > 2 else 8000
if len(sys.argv) > 2 and sys.argv[1] == "--port":
try:
port = int(sys.argv[2])
except ValueError:
port = 8000
uvicorn.run(app, host="0.0.0.0", port=port)
|
2977094657/ZsxqCrawler
| 48,151
|
zsxq_file_downloader.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
知识星球文件下载器
Author: AI Assistant
Date: 2024-12-19
Description: 专门用于下载知识星球文件的工具
"""
import datetime
import json
import os
import random
import time
from typing import Dict, Optional, Any
import requests
from zsxq_file_database import ZSXQFileDatabase
class ZSXQFileDownloader:
"""知识星球文件下载器"""
def __init__(self, cookie: str, group_id: str, db_path: str = None, download_dir: str = "downloads",
download_interval: float = 1.0, long_sleep_interval: float = 60.0,
files_per_batch: int = 10, download_interval_min: float = None,
download_interval_max: float = None, long_sleep_interval_min: float = None,
long_sleep_interval_max: float = None):
"""
初始化文件下载器
Args:
cookie: 登录凭证
group_id: 星球ID
db_path: 数据库文件路径(如果为None,使用默认路径)
download_dir: 下载目录
download_interval: 单次下载间隔(秒),默认1秒
long_sleep_interval: 长休眠间隔(秒),默认60秒
files_per_batch: 下载多少文件后触发长休眠,默认10个文件
download_interval_min: 随机下载间隔最小值(秒)
download_interval_max: 随机下载间隔最大值(秒)
long_sleep_interval_min: 随机长休眠间隔最小值(秒)
long_sleep_interval_max: 随机长休眠间隔最大值(秒)
"""
self.cookie = self.clean_cookie(cookie)
self.group_id = group_id
# 下载间隔控制参数
self.download_interval = download_interval
self.long_sleep_interval = long_sleep_interval
self.files_per_batch = files_per_batch
self.current_batch_count = 0 # 当前批次已下载文件数
# 随机间隔范围参数(如果提供了范围参数,则使用随机间隔)
self.use_random_interval = download_interval_min is not None
if self.use_random_interval:
self.download_interval_min = download_interval_min
self.download_interval_max = download_interval_max
self.long_sleep_interval_min = long_sleep_interval_min
self.long_sleep_interval_max = long_sleep_interval_max
else:
# 使用固定间隔时的默认范围值(保持向后兼容)
self.download_interval_min = 60 # 下载间隔最小值(1分钟)
self.download_interval_max = 180 # 下载间隔最大值(3分钟)
self.long_sleep_interval_min = 180 # 长休眠最小值(3分钟)
self.long_sleep_interval_max = 300 # 长休眠最大值(5分钟)
# 如果没有指定数据库路径,使用默认路径
if db_path is None:
from db_path_manager import get_db_path_manager
path_manager = get_db_path_manager()
self.db_path = path_manager.get_files_db_path(group_id)
else:
self.db_path = db_path
# 为每个群组创建专属的下载目录
if download_dir == "downloads": # 默认目录
from db_path_manager import get_db_path_manager
path_manager = get_db_path_manager()
group_dir = path_manager.get_group_dir(group_id)
self.download_dir = os.path.join(group_dir, "downloads")
else:
# 如果指定了自定义目录,也在其下创建群组子目录
self.download_dir = os.path.join(download_dir, f"group_{group_id}")
print(f"📁 群组 {group_id} 下载目录: {self.download_dir}")
self.base_url = "https://api.zsxq.com"
# 日志回调和停止检查函数
self.log_callback = None
self.stop_check_func = None
self.stop_flag = False # 本地停止标志
# 反检测设置
self.min_delay = 2.0 # 最小延迟(秒)
self.max_delay = 5.0 # 最大延迟(秒)
self.long_delay_interval = 5 # 每N个文件进行长休眠
# 统计
self.request_count = 0
self.download_count = 0
self.debug_mode = False
# 创建session
self.session = requests.Session()
# 确保下载目录存在
os.makedirs(self.download_dir, exist_ok=True)
self.log(f"📁 下载目录: {os.path.abspath(self.download_dir)}")
# 使用完整的文件数据库
self.file_db = ZSXQFileDatabase(self.db_path)
self.log(f"📊 完整文件数据库初始化完成: {self.db_path}")
def log(self, message: str):
"""统一的日志输出方法"""
if self.log_callback:
self.log_callback(message)
else:
print(message)
def set_stop_flag(self):
"""设置停止标志"""
self.stop_flag = True
self.log("🛑 收到停止信号,任务将在下一个检查点停止")
def is_stopped(self):
"""检查是否被停止(综合检查本地标志和外部函数)"""
# 首先检查本地停止标志
if self.stop_flag:
return True
# 然后检查外部停止检查函数
if self.stop_check_func and self.stop_check_func():
self.stop_flag = True # 同步本地标志
return True
return False
def check_stop(self):
"""检查是否需要停止(兼容旧方法名)"""
return self.is_stopped()
def clean_cookie(self, cookie: str) -> str:
"""清理Cookie字符串,去除不合法字符
Args:
cookie (str): 原始Cookie字符串
Returns:
str: 清理后的Cookie字符串
"""
try:
# 如果是bytes类型,先解码
if isinstance(cookie, bytes):
cookie = cookie.decode('utf-8')
# 去除多余的空格和换行符
cookie = cookie.strip()
# 如果有多行,只取第一行
if '\n' in cookie:
cookie = cookie.split('\n')[0]
# 去除末尾的反斜杠
cookie = cookie.rstrip('\\')
# 去除可能的前缀b和引号
if cookie.startswith("b'") and cookie.endswith("'"):
cookie = cookie[2:-1]
elif cookie.startswith('b"') and cookie.endswith('"'):
cookie = cookie[2:-1]
elif cookie.startswith("'") and cookie.endswith("'"):
cookie = cookie[1:-1]
elif cookie.startswith('"') and cookie.endswith('"'):
cookie = cookie[1:-1]
# 处理转义字符
cookie = cookie.replace('\\n', '')
cookie = cookie.replace('\\"', '"')
cookie = cookie.replace("\\'", "'")
# 确保分号后有空格
cookie = '; '.join(part.strip() for part in cookie.split(';'))
return cookie
except Exception as e:
print(f"Cookie清理失败: {e}")
return cookie # 返回原始值
def get_stealth_headers(self) -> Dict[str, str]:
"""获取反检测请求头(每次调用随机化)"""
# 更丰富的User-Agent池
user_agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:131.0) Gecko/20100101 Firefox/131.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:132.0) Gecko/20100101 Firefox/132.0"
]
# 随机选择User-Agent
selected_ua = random.choice(user_agents)
# 根据User-Agent生成对应的Sec-Ch-Ua
if "Chrome" in selected_ua:
if "131.0.0.0" in selected_ua:
sec_ch_ua = '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"'
elif "130.0.0.0" in selected_ua:
sec_ch_ua = '"Google Chrome";v="130", "Chromium";v="130", "Not?A_Brand";v="99"'
elif "129.0.0.0" in selected_ua:
sec_ch_ua = '"Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"'
else:
sec_ch_ua = '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"'
else:
sec_ch_ua = '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"'
# 随机化其他头部
accept_languages = [
'zh-CN,zh;q=0.9,en;q=0.8',
'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2'
]
platforms = ['"Windows"', '"macOS"', '"Linux"']
# 基础头部
headers = {
'Accept': 'application/json, text/plain, */*',
'Accept-Language': random.choice(accept_languages),
'Accept-Encoding': 'gzip, deflate, br',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Cookie': self.cookie,
'Host': 'api.zsxq.com',
'Origin': 'https://wx.zsxq.com',
'Pragma': 'no-cache',
'Referer': f'https://wx.zsxq.com/dweb2/index/group/{self.group_id}',
'Sec-Ch-Ua': sec_ch_ua,
'Sec-Ch-Ua-Mobile': '?0',
'Sec-Ch-Ua-Platform': random.choice(platforms),
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-site',
'User-Agent': selected_ua
}
# 随机添加可选头部
optional_headers = {
'DNT': '1',
'Sec-GPC': '1',
'Upgrade-Insecure-Requests': '1',
'X-Requested-With': 'XMLHttpRequest'
}
for key, value in optional_headers.items():
if random.random() > 0.5: # 50%概率添加
headers[key] = value
# 随机调整时间戳相关头部
if random.random() > 0.7: # 30%概率添加
headers['X-Timestamp'] = str(int(time.time()) + random.randint(-30, 30))
if random.random() > 0.6: # 40%概率添加
headers['X-Request-Id'] = f"req-{random.randint(100000000000, 999999999999)}"
return headers
def smart_delay(self):
"""智能延迟"""
delay = random.uniform(self.min_delay, self.max_delay)
if self.debug_mode:
print(f" ⏱️ 延迟 {delay:.1f}秒")
time.sleep(delay)
def download_delay(self):
"""下载间隔延迟"""
if self.use_random_interval:
# 使用API传入的随机间隔范围
delay = random.uniform(self.download_interval_min, self.download_interval_max)
print(f"⏳ 下载间隔: {delay:.0f}秒 ({delay/60:.1f}分钟) [随机范围: {self.download_interval_min}-{self.download_interval_max}秒]")
else:
# 使用固定间隔
delay = self.download_interval
print(f"⏳ 下载间隔: {delay:.1f}秒 [固定间隔]")
start_time = datetime.datetime.now()
end_time = start_time + datetime.timedelta(seconds=delay)
print(f" ⏰ 开始时间: {start_time.strftime('%H:%M:%S')}")
print(f" 🕐 预计恢复: {end_time.strftime('%H:%M:%S')}")
time.sleep(delay)
actual_end_time = datetime.datetime.now()
print(f" 🕐 实际结束: {actual_end_time.strftime('%H:%M:%S')}")
def check_long_delay(self):
"""检查是否需要长休眠"""
if self.download_count > 0 and self.download_count % self.long_delay_interval == 0:
if self.use_random_interval:
# 使用API传入的随机长休眠间隔范围
delay = random.uniform(self.long_sleep_interval_min, self.long_sleep_interval_max)
print(f"🛌 长休眠开始: {delay:.0f}秒 ({delay/60:.1f}分钟) [随机范围: {self.long_sleep_interval_min/60:.1f}-{self.long_sleep_interval_max/60:.1f}分钟]")
else:
# 使用固定长休眠间隔
delay = self.long_sleep_interval
print(f"🛌 长休眠开始: {delay:.0f}秒 ({delay/60:.1f}分钟) [固定间隔]")
start_time = datetime.datetime.now()
end_time = start_time + datetime.timedelta(seconds=delay)
print(f" 已下载 {self.download_count} 个文件,进入长休眠模式...")
print(f" ⏰ 开始时间: {start_time.strftime('%H:%M:%S')}")
print(f" 🕐 预计恢复: {end_time.strftime('%H:%M:%S')}")
time.sleep(delay)
actual_end_time = datetime.datetime.now()
print(f"😴 长休眠结束,继续下载...")
print(f" 🕐 实际结束: {actual_end_time.strftime('%H:%M:%S')}")
def fetch_file_list(self, count: int = 20, index: Optional[str] = None, sort: str = "by_download_count") -> Optional[Dict[str, Any]]:
"""获取文件列表(带重试机制)"""
url = f"{self.base_url}/v2/groups/{self.group_id}/files"
max_retries = 10
params = {
"count": str(count),
"sort": sort
}
if index:
params["index"] = index
self.log(f"🌐 获取文件列表")
self.log(f" 📊 参数: count={count}, sort={sort}")
if index:
self.log(f" 📑 索引: {index}")
self.log(f" 🌐 请求URL: {url}")
for attempt in range(max_retries):
if attempt > 0:
# 重试延迟:15-30秒
retry_delay = random.uniform(15, 30)
print(f" 🔄 第{attempt}次重试,等待{retry_delay:.1f}秒...")
time.sleep(retry_delay)
# 每次重试都获取新的请求头(包含新的User-Agent等)
self.smart_delay()
self.request_count += 1
headers = self.get_stealth_headers()
if attempt > 0:
print(f" 🔄 重试#{attempt}: 使用新的User-Agent: {headers.get('User-Agent', 'N/A')[:50]}...")
try:
response = self.session.get(url, headers=headers, params=params, timeout=30)
print(f" 📊 响应状态: {response.status_code}")
if response.status_code == 200:
try:
data = response.json()
# 只在第一次尝试或最后一次失败时显示完整响应
if attempt == 0 or attempt == max_retries - 1 or data.get('succeeded'):
print(f" 📋 响应内容: {json.dumps(data, ensure_ascii=False, indent=2)}")
if data.get('succeeded'):
files = data.get('resp_data', {}).get('files', [])
next_index = data.get('resp_data', {}).get('index')
if attempt > 0:
print(f" ✅ 重试成功!第{attempt}次重试获取到文件列表")
else:
print(f" ✅ 获取成功: {len(files)}个文件")
return data
else:
error_msg = data.get('message', data.get('error', '未知错误'))
error_code = data.get('code', 'N/A')
print(f" ❌ API返回失败: {error_msg} (代码: {error_code})")
# 检查是否是可重试的错误
if error_code in [1059, 500, 502, 503, 504]: # 内部错误、服务器错误等
if attempt < max_retries - 1:
print(f" 🔄 检测到可重试错误,准备重试...")
continue
else:
print(f" 🚫 非可重试错误,停止重试")
return None
except json.JSONDecodeError as e:
print(f" ❌ JSON解析失败: {e}")
print(f" 📄 原始响应: {response.text[:500]}...")
if attempt < max_retries - 1:
print(f" 🔄 JSON解析失败,准备重试...")
continue
elif response.status_code in [429, 500, 502, 503, 504]: # 频率限制或服务器错误
print(f" ❌ HTTP错误: {response.status_code}")
print(f" 📄 响应内容: {response.text[:200]}...")
if attempt < max_retries - 1:
print(f" 🔄 服务器错误,准备重试...")
continue
else:
print(f" ❌ HTTP错误: {response.status_code}")
print(f" 📄 响应内容: {response.text[:200]}...")
print(f" 🚫 非可重试HTTP错误,停止重试")
return None
except Exception as e:
print(f" ❌ 请求异常: {e}")
if attempt < max_retries - 1:
print(f" 🔄 请求异常,准备重试...")
continue
print(f" 🚫 已重试{max_retries}次,全部失败")
return None
def get_download_url(self, file_id: int) -> Optional[str]:
"""获取文件下载链接(带重试机制)
注意:file_id 参数在不同场景下含义不同:
- 边获取边下载时:传入的是真实的 file_id
- 从数据库下载时:传入的是 topic_id
"""
url = f"{self.base_url}/v2/files/{file_id}/download_url"
max_retries = 10
self.log(f" 🔗 获取下载链接: ID={file_id}")
self.log(f" 🌐 请求URL: {url}")
for attempt in range(max_retries):
if attempt > 0:
# 重试延迟:15-30秒
retry_delay = random.uniform(15, 30)
print(f" 🔄 第{attempt}次重试,等待{retry_delay:.1f}秒...")
time.sleep(retry_delay)
# 每次重试都获取新的请求头(包含新的User-Agent等)
self.smart_delay()
self.request_count += 1
headers = self.get_stealth_headers()
if attempt > 0:
print(f" 🔄 重试#{attempt}: 使用新的User-Agent: {headers.get('User-Agent', 'N/A')[:50]}...")
try:
response = self.session.get(url, headers=headers, timeout=30)
print(f" 📊 响应状态: {response.status_code}")
if response.status_code == 200:
try:
data = response.json()
# 只在第一次尝试或最后一次失败时显示完整响应
if attempt == 0 or attempt == max_retries - 1 or data.get('succeeded'):
print(f" 📋 响应内容: {json.dumps(data, ensure_ascii=False, indent=2)}")
if data.get('succeeded'):
download_url = data.get('resp_data', {}).get('download_url')
if download_url:
if attempt > 0:
print(f" ✅ 重试成功!第{attempt}次重试获取到下载链接")
else:
print(f" ✅ 获取下载链接成功")
return download_url
else:
print(f" ❌ 响应中无下载链接字段")
else:
error_msg = data.get('message', data.get('error', '未知错误'))
error_code = data.get('code', 'N/A')
self.log(f" ❌ API返回失败: {error_msg} (代码: {error_code})")
# 检查是否是1030权限错误
if error_code == 1030:
self.log(f" 🚫 权限不足错误(1030):此文件只能在手机端下载,任务将自动停止")
# 设置停止标志,让整个任务停止
self.set_stop_flag()
return None
# 检查是否是可重试的错误
if error_code in [1059, 500, 502, 503, 504]: # 内部错误、服务器错误等
if attempt < max_retries - 1:
self.log(f" 🔄 检测到可重试错误,准备重试...")
continue
else:
self.log(f" 🚫 非可重试错误,停止重试")
return None
except json.JSONDecodeError as e:
print(f" ❌ JSON解析失败: {e}")
print(f" 📄 原始响应: {response.text[:500]}...")
if attempt < max_retries - 1:
print(f" 🔄 JSON解析失败,准备重试...")
continue
elif response.status_code in [429, 500, 502, 503, 504]: # 频率限制或服务器错误
print(f" ❌ HTTP错误: {response.status_code}")
print(f" 📄 响应内容: {response.text[:200]}...")
if attempt < max_retries - 1:
print(f" 🔄 服务器错误,准备重试...")
continue
else:
print(f" ❌ HTTP错误: {response.status_code}")
print(f" 📄 响应内容: {response.text[:200]}...")
print(f" 🚫 非可重试HTTP错误,停止重试")
return None
except Exception as e:
print(f" ❌ 请求异常: {e}")
if attempt < max_retries - 1:
print(f" 🔄 请求异常,准备重试...")
continue
print(f" 🚫 已重试{max_retries}次,全部失败")
return None
def download_file(self, file_info: Dict[str, Any]) -> bool:
"""下载单个文件"""
file_data = file_info.get('file', {})
file_id = file_data.get('id')
file_name = file_data.get('name', 'Unknown')
file_size = file_data.get('size', 0)
download_count = file_data.get('download_count', 0)
self.log(f"📥 准备下载文件:")
self.log(f" 📄 名称: {file_name}")
self.log(f" 📊 大小: {file_size:,} bytes ({file_size/1024/1024:.2f} MB)")
self.log(f" 📈 下载次数: {download_count}")
# 检查是否需要停止
if self.check_stop():
self.log("🛑 下载任务被停止")
return False
# 清理文件名(移除非法字符)
safe_filename = "".join(c for c in file_name if c.isalnum() or c in '._-()()[]{}')
if not safe_filename:
safe_filename = f"file_{file_id}"
file_path = os.path.join(self.download_dir, safe_filename)
# 🚀 优化:先检查本地文件,避免无意义的API请求
if os.path.exists(file_path):
existing_size = os.path.getsize(file_path)
if existing_size == file_size:
self.log(f" ✅ 文件已存在且大小匹配,跳过下载")
return "skipped" # 返回特殊值表示跳过
else:
self.log(f" ⚠️ 文件已存在但大小不匹配,重新下载")
# 只有在需要下载时才获取下载链接
download_url = self.get_download_url(file_id)
if not download_url:
self.log(f" ❌ 无法获取下载链接")
return False
try:
# 下载文件
self.log(f" 🚀 开始下载...")
response = self.session.get(download_url, timeout=300, stream=True)
# 如果文件名是默认的,尝试从响应头获取真实文件名
if file_name.startswith('file_') and 'content-disposition' in response.headers:
content_disposition = response.headers['content-disposition']
if 'filename=' in content_disposition:
# 提取文件名
import re
filename_match = re.search(r'filename[*]?=([^;]+)', content_disposition)
if filename_match:
real_filename = filename_match.group(1).strip('"\'')
if real_filename:
file_name = real_filename
safe_filename = "".join(c for c in file_name if c.isalnum() or c in '._-()()[]{}')
if not safe_filename:
safe_filename = f"file_{file_id}"
file_path = os.path.join(self.download_dir, safe_filename)
self.log(f" 📝 从响应头获取到真实文件名: {file_name}")
if response.status_code == 200:
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(file_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
downloaded_size += len(chunk)
# 显示进度(每10MB显示一次)
if downloaded_size % (10 * 1024 * 1024) == 0 or downloaded_size == total_size:
if total_size > 0:
progress = (downloaded_size / total_size) * 100
self.log(f" 📊 进度: {progress:.1f}% ({downloaded_size:,}/{total_size:,} bytes)")
# 检查是否需要停止
if self.check_stop():
self.log("🛑 下载过程中被停止")
return False
if downloaded_size % (10 * 1024 * 1024) != 0 and downloaded_size != total_size:
if total_size == 0:
self.log(f" 📊 已下载: {downloaded_size:,} bytes")
# 验证文件大小
final_size = os.path.getsize(file_path)
if file_size > 0 and final_size != file_size:
self.log(f" ⚠️ 文件大小不匹配: 预期{file_size:,}, 实际{final_size:,}")
self.log(f" ✅ 下载完成: {safe_filename}")
self.log(f" 💾 保存路径: {file_path}")
self.download_count += 1
self.current_batch_count += 1
# 下载间隔控制
self._apply_download_intervals()
return True
else:
self.log(f" ❌ 下载失败: HTTP {response.status_code}")
return False
except Exception as e:
self.log(f" ❌ 下载异常: {e}")
if os.path.exists(file_path):
os.remove(file_path)
self.log(f" 🗑️ 删除不完整文件")
return False
def _apply_download_intervals(self):
"""应用下载间隔控制"""
import time
# 检查是否需要长休眠
if self.current_batch_count >= self.files_per_batch:
self.log(f"⏰ 已下载 {self.current_batch_count} 个文件,开始长休眠 {self.long_sleep_interval} 秒...")
time.sleep(self.long_sleep_interval)
self.current_batch_count = 0 # 重置批次计数
self.log(f"😴 长休眠结束,继续下载")
else:
# 普通下载间隔
if self.download_interval > 0:
self.log(f"⏱️ 下载间隔休眠 {self.download_interval} 秒...")
time.sleep(self.download_interval)
def download_files_batch(self, max_files: Optional[int] = None, start_index: Optional[str] = None) -> Dict[str, int]:
"""批量下载文件"""
if max_files is None:
self.log(f"📥 开始无限下载文件 (直到没有更多文件)")
else:
self.log(f"📥 开始批量下载文件 (最多{max_files}个)")
# 检查是否需要停止
if self.check_stop():
self.log("🛑 任务被停止")
return {'total_files': 0, 'downloaded': 0, 'skipped': 0, 'failed': 0}
stats = {'total_files': 0, 'downloaded': 0, 'skipped': 0, 'failed': 0}
current_index = start_index
downloaded_in_batch = 0
while max_files is None or downloaded_in_batch < max_files:
# 检查是否需要停止
if self.check_stop():
self.log("🛑 批量下载任务被停止")
break
# 获取文件列表
data = self.fetch_file_list(count=20, index=current_index)
if not data:
self.log("❌ 获取文件列表失败")
break
files = data.get('resp_data', {}).get('files', [])
next_index = data.get('resp_data', {}).get('index')
if not files:
self.log("📭 没有更多文件")
break
self.log(f"📋 当前批次: {len(files)} 个文件")
for i, file_info in enumerate(files):
# 检查是否需要停止
if self.check_stop():
self.log("🛑 文件下载过程中被停止")
break
if max_files is not None and downloaded_in_batch >= max_files:
break
file_data = file_info.get('file', {})
file_name = file_data.get('name', 'Unknown')
if max_files is None:
self.log(f"【第{downloaded_in_batch + 1}个文件】{file_name}")
else:
self.log(f"【{downloaded_in_batch + 1}/{max_files}】{file_name}")
# 下载文件
result = self.download_file(file_info)
if result == "skipped":
stats['skipped'] += 1
self.log(f" ⚠️ 文件已跳过,继续下一个")
elif result:
stats['downloaded'] += 1
downloaded_in_batch += 1
# 检查长休眠
self.check_long_delay()
# 如果不是最后一个文件,进行下载间隔
has_more_in_batch = (i + 1) < len(files)
not_reached_limit = max_files is None or downloaded_in_batch < max_files
if has_more_in_batch and not_reached_limit:
self.download_delay()
else:
stats['failed'] += 1
stats['total_files'] += 1
# 准备下一页
should_continue = max_files is None or downloaded_in_batch < max_files
if next_index and should_continue:
current_index = next_index
self.log(f"📄 准备获取下一页: {next_index}")
time.sleep(2) # 页面间短暂延迟
else:
break
self.log(f"🎉 批量下载完成:")
self.log(f" 📊 总文件数: {stats['total_files']}")
self.log(f" ✅ 下载成功: {stats['downloaded']}")
self.log(f" ⚠️ 跳过: {stats['skipped']}")
self.log(f" ❌ 失败: {stats['failed']}")
return stats
def show_file_list(self, count: int = 20, index: Optional[str] = None) -> Optional[str]:
"""显示文件列表"""
data = self.fetch_file_list(count=count, index=index)
if not data:
return None
files = data.get('resp_data', {}).get('files', [])
next_index = data.get('resp_data', {}).get('index')
print(f"\n📋 文件列表 ({len(files)} 个文件):")
print("="*80)
for i, file_info in enumerate(files, 1):
file_data = file_info.get('file', {})
topic_data = file_info.get('topic', {})
file_name = file_data.get('name', 'Unknown')
file_size = file_data.get('size', 0)
download_count = file_data.get('download_count', 0)
create_time = file_data.get('create_time', 'Unknown')
topic_title = topic_data.get('talk', {}).get('text', '')[:50] if topic_data.get('talk') else ''
print(f"{i:2d}. 📄 {file_name}")
print(f" 📊 大小: {file_size:,} bytes ({file_size/1024/1024:.2f} MB)")
print(f" 📈 下载: {download_count} 次")
print(f" ⏰ 时间: {create_time}")
if topic_title:
print(f" 💬 话题: {topic_title}...")
print()
if next_index:
print(f"📑 下一页索引: {next_index}")
else:
print("📭 没有更多文件")
return next_index
def collect_all_files_to_database(self) -> Dict[str, int]:
"""收集所有文件信息到数据库"""
print(f"\n📊 开始收集文件列表到数据库...")
# 创建收集记录
self.file_db.cursor.execute("INSERT INTO collection_log (start_time) VALUES (?)",
(datetime.datetime.now().isoformat(),))
log_id = self.file_db.cursor.lastrowid
self.file_db.conn.commit()
stats = {'total_files': 0, 'new_files': 0, 'skipped_files': 0}
current_index = None
page_count = 0
try:
while True:
page_count += 1
print(f"\n📄 收集第{page_count}页文件列表...")
# 获取文件列表
data = self.fetch_file_list(count=20, index=current_index)
if not data:
print(f"❌ 第{page_count}页获取失败,收集过程中断")
print(f"💾 已成功收集前{page_count-1}页的数据")
break
files = data.get('resp_data', {}).get('files', [])
next_index = data.get('resp_data', {}).get('index')
if not files:
print("📭 没有更多文件")
break
print(f" 📋 当前页面: {len(files)} 个文件")
# 使用完整数据库导入整个API响应
try:
page_stats = self.file_db.import_file_response(data)
stats['new_files'] += page_stats.get('files', 0)
stats['total_files'] += len(files)
print(f" ✅ 新增文件: {page_stats.get('files', 0)}")
print(f" 📊 其他数据: 话题+{page_stats.get('topics', 0)}, 用户+{page_stats.get('users', 0)}")
except Exception as e:
print(f" ❌ 第{page_count}页存储失败: {e}")
continue
print(f" ✅ 第{page_count}页存储完成")
# 准备下一页
if next_index:
current_index = next_index
# 页面间短暂延迟
time.sleep(random.uniform(2, 5))
else:
break
except KeyboardInterrupt:
print(f"\n⏹️ 用户中断收集")
except Exception as e:
print(f"\n❌ 收集过程异常: {e}")
# 更新收集记录
self.file_db.cursor.execute('''
UPDATE collection_log SET
end_time = ?, total_files = ?, new_files = ?, status = 'completed'
WHERE id = ?
''', (datetime.datetime.now().isoformat(), stats['total_files'],
stats['new_files'], log_id))
self.file_db.conn.commit()
print(f"\n🎉 文件列表收集完成:")
print(f" 📊 处理文件数: {stats['total_files']}")
print(f" ✅ 新增文件: {stats['new_files']}")
print(f" ⚠️ 跳过重复: {stats.get('skipped_files', 0)}")
print(f" 📄 收集页数: {page_count}")
return stats
def get_database_time_range(self) -> Dict[str, Any]:
"""获取完整数据库中文件的时间范围信息"""
# 使用新数据库检查是否有数据
stats = self.file_db.get_database_stats()
total_files = stats.get('files', 0)
if total_files == 0:
return {'has_data': False, 'total_files': 0}
# 获取时间范围
self.file_db.cursor.execute('''
SELECT MIN(create_time) as oldest_time,
MAX(create_time) as newest_time,
COUNT(*) as total_count
FROM files
WHERE create_time IS NOT NULL AND create_time != ''
''')
result = self.file_db.cursor.fetchone()
return {
'has_data': True,
'total_files': total_files,
'oldest_time': result[0] if result else None,
'newest_time': result[1] if result else None,
'time_based_count': result[2] if result else 0
}
def collect_files_by_time(self, sort: str = "by_create_time", start_time: Optional[str] = None) -> Dict[str, int]:
"""按时间顺序收集文件列表到数据库(使用完整的数据库结构)"""
self.log(f"📊 开始按时间顺序收集文件列表到完整数据库...")
self.log(f" 📅 排序方式: {sort}")
if start_time:
self.log(f" ⏰ 起始时间: {start_time}")
# 检查是否需要停止
if self.check_stop():
self.log("🛑 任务被停止")
return {'total_files': 0, 'new_files': 0}
# 使用完整数据库的统计信息
initial_stats = self.file_db.get_database_stats()
initial_files = initial_stats.get('files', 0)
self.log(f" 📊 数据库初始状态: {initial_files} 个文件")
total_imported_stats = {
'files': 0, 'topics': 0, 'users': 0, 'groups': 0,
'images': 0, 'comments': 0, 'likes': 0, 'columns': 0, 'solutions': 0
}
current_index = start_time # 使用时间戳作为index
page_count = 0
try:
while True:
# 检查是否需要停止
if self.check_stop():
self.log("🛑 文件收集任务被停止")
break
page_count += 1
self.log(f"📄 收集第{page_count}页文件列表...")
# 获取文件列表(按时间排序)
data = self.fetch_file_list(count=20, index=current_index, sort=sort)
if not data:
self.log(f"❌ 第{page_count}页获取失败,收集过程中断")
self.log(f"💾 已成功收集前{page_count-1}页的数据")
break
files = data.get('resp_data', {}).get('files', [])
next_index = data.get('resp_data', {}).get('index')
if not files:
self.log("📭 没有更多文件")
break
self.log(f" 📋 当前页面: {len(files)} 个文件")
# 使用完整数据库导入整个API响应
try:
page_stats = self.file_db.import_file_response(data)
# 累计统计
for key in total_imported_stats:
total_imported_stats[key] += page_stats.get(key, 0)
self.log(f" ✅ 第{page_count}页存储完成: 文件+{page_stats.get('files', 0)}, 话题+{page_stats.get('topics', 0)}")
except Exception as e:
self.log(f" ❌ 第{page_count}页存储失败: {e}")
continue
# 准备下一页
if next_index:
current_index = next_index
self.log(f" ⏭️ 下一页时间戳: {current_index}")
# 页面间短暂延迟
time.sleep(random.uniform(2, 5))
else:
self.log("📭 已到达最后一页")
break
except KeyboardInterrupt:
self.log(f"⏹️ 用户中断收集")
except Exception as e:
self.log(f"❌ 收集过程异常: {e}")
# 最终统计
final_stats = self.file_db.get_database_stats()
final_files = final_stats.get('files', 0)
new_files = final_files - initial_files
self.log(f"🎉 完整文件列表收集完成:")
self.log(f" 📊 处理页数: {page_count}")
self.log(f" 📁 新增文件: {new_files} (总计: {final_files})")
self.log(f" 📋 累计导入统计:")
for key, value in total_imported_stats.items():
if value > 0:
self.log(f" {key}: +{value}")
print(f"\n📊 当前数据库状态:")
for table, count in final_stats.items():
if count > 0:
print(f" {table}: {count}")
return {
'total_files': final_files,
'new_files': new_files,
'pages': page_count,
**total_imported_stats
}
def collect_incremental_files(self) -> Dict[str, int]:
"""增量收集:从数据库最老时间戳开始继续收集"""
self.log(f"🔄 开始增量文件收集...")
# 检查是否需要停止
if self.check_stop():
self.log("🛑 任务被停止")
return {'total_files': 0, 'new_files': 0}
# 获取数据库时间范围
time_info = self.get_database_time_range()
if not time_info['has_data']:
self.log("📊 数据库为空,将进行全量收集")
return self.collect_files_by_time()
oldest_time = time_info['oldest_time']
newest_time = time_info['newest_time']
total_files = time_info['total_files']
self.log(f"📊 数据库现状:")
self.log(f" 现有文件数: {total_files}")
self.log(f" 最老时间: {oldest_time}")
self.log(f" 最新时间: {newest_time}")
if not oldest_time:
self.log("⚠️ 数据库中没有有效的时间信息,进行全量收集")
return self.collect_files_by_time()
# 从最老时间戳开始收集更早的文件
self.log(f"🎯 将从最老时间戳开始收集更早的文件...")
# 将时间戳转换为毫秒数用作index
try:
if '+' in oldest_time:
# 处理带时区的时间戳
from datetime import datetime
dt = datetime.fromisoformat(oldest_time.replace('+0800', '+08:00'))
timestamp_ms = int(dt.timestamp() * 1000)
else:
# 如果已经是毫秒时间戳
timestamp_ms = int(oldest_time)
start_index = str(timestamp_ms)
self.log(f"🚀 增量收集起始时间戳: {start_index}")
return self.collect_files_by_time(start_time=start_index)
except Exception as e:
self.log(f"⚠️ 时间戳处理失败: {e}")
self.log("🔄 改为全量收集")
return self.collect_files_by_time()
def download_files_from_database(self, max_files: Optional[int] = None, status_filter: str = 'pending') -> Dict[str, int]:
"""从完整数据库下载文件(使用file_id字段)"""
self.log(f"📥 开始从完整数据库下载文件...")
if max_files:
self.log(f" 🎯 下载限制: {max_files}个文件")
self.log(f" 🔍 状态筛选: {status_filter}")
# 检查是否需要停止
if self.check_stop():
self.log("🛑 任务被停止")
return {'total_files': 0, 'downloaded': 0, 'skipped': 0, 'failed': 0}
# 从完整数据库获取文件列表
if max_files:
self.file_db.cursor.execute('''
SELECT file_id, name, size, download_count, create_time
FROM files
ORDER BY download_count DESC, size ASC
LIMIT ?
''', (max_files,))
else:
self.file_db.cursor.execute('''
SELECT file_id, name, size, download_count, create_time
FROM files
ORDER BY download_count DESC, size ASC
''')
files_to_download = self.file_db.cursor.fetchall()
if not files_to_download:
self.log(f"📭 数据库中没有文件可下载")
return {'total_files': 0, 'downloaded': 0, 'skipped': 0, 'failed': 0}
self.log(f"📋 找到 {len(files_to_download)} 个待下载文件")
stats = {'total_files': len(files_to_download), 'downloaded': 0, 'skipped': 0, 'failed': 0}
for i, (file_id, file_name, file_size, download_count, create_time) in enumerate(files_to_download, 1):
# 检查是否需要停止
if self.check_stop():
self.log("🛑 下载任务被停止")
break
try:
self.log(f"【{i}/{len(files_to_download)}】{file_name}")
self.log(f" 📊 文件ID: {file_id}, 大小: {file_size/1024:.1f}KB, 下载次数: {download_count}")
# 构造文件信息结构(使用正确的file_id)
file_info = {
'file': {
'id': file_id, # 使用正确的file_id
'name': file_name,
'size': file_size,
'download_count': download_count
}
}
# 下载文件
result = self.download_file(file_info)
if result == "skipped":
stats['skipped'] += 1
self.log(f" ⚠️ 文件已跳过")
elif result:
stats['downloaded'] += 1
# 检查长休眠
self.check_long_delay()
# 如果不是最后一个文件,进行下载间隔
if i < len(files_to_download):
self.download_delay()
else:
stats['failed'] += 1
self.log(f" ❌ 下载失败")
except KeyboardInterrupt:
self.log(f"⏹️ 用户中断下载")
break
except Exception as e:
self.log(f" ❌ 处理文件异常: {e}")
stats['failed'] += 1
continue
self.log(f"🎉 数据库下载完成:")
self.log(f" 📊 总文件数: {stats['total_files']}")
self.log(f" ✅ 下载成功: {stats['downloaded']}")
self.log(f" ⚠️ 跳过: {stats['skipped']}")
self.log(f" ❌ 失败: {stats['failed']}")
return stats
def show_database_stats(self):
"""显示完整数据库统计信息"""
print(f"\n📊 完整数据库统计信息:")
print("="*60)
print(f"📁 数据库文件: {self.db_path}")
# 使用新数据库的统计方法
stats = self.file_db.get_database_stats()
# 主要数据统计
total_files = stats.get('files', 0)
total_topics = stats.get('topics', 0)
total_users = stats.get('users', 0)
total_groups = stats.get('groups', 0)
print(f"📈 核心数据:")
print(f" 📄 文件数量: {total_files:,}")
print(f" 💬 话题数量: {total_topics:,}")
print(f" 👥 用户数量: {total_users:,}")
print(f" 🏠 群组数量: {total_groups:,}")
# 文件大小统计
self.file_db.cursor.execute("SELECT SUM(size) FROM files WHERE size IS NOT NULL")
result = self.file_db.cursor.fetchone()
total_size = result[0] if result and result[0] else 0
if total_size > 0:
print(f"💾 总文件大小: {total_size/1024/1024:.2f} MB")
# 详细表统计
print(f"\n📋 详细表统计:")
for table_name, count in stats.items():
if count > 0:
# 添加表情符号
emoji_map = {
'files': '📄', 'groups': '🏠', 'users': '👥', 'topics': '💬',
'talks': '💭', 'images': '🖼️', 'topic_files': '📎',
'latest_likes': '👍', 'comments': '💬', 'like_emojis': '😊',
'user_liked_emojis': '❤️', 'columns': '📚', 'topic_columns': '🔗',
'solutions': '💡', 'solution_files': '📋', 'file_topic_relations': '🔗',
'api_responses': '📡'
}
emoji = emoji_map.get(table_name, '📊')
print(f" {emoji} {table_name}: {count:,}")
# 文件创建时间范围
self.file_db.cursor.execute('''
SELECT MIN(create_time), MAX(create_time), COUNT(*)
FROM files
WHERE create_time IS NOT NULL
''')
time_result = self.file_db.cursor.fetchone()
if time_result and time_result[2] > 0:
min_time, max_time, time_count = time_result
print(f"\n⏰ 文件时间范围:")
print(f" 最早文件: {min_time}")
print(f" 最新文件: {max_time}")
print(f" 有时间信息的文件: {time_count:,}")
# API响应统计
self.file_db.cursor.execute('''
SELECT succeeded, COUNT(*)
FROM api_responses
GROUP BY succeeded
''')
api_stats = self.file_db.cursor.fetchall()
if api_stats:
print(f"\n📡 API响应统计:")
for succeeded, count in api_stats:
status = "成功" if succeeded else "失败"
emoji = "✅" if succeeded else "❌"
print(f" {emoji} {status}: {count:,}")
print("="*60)
def adjust_settings(self):
"""调整下载设置"""
print(f"\n🔧 当前下载设置:")
print(f" 下载间隔: {self.download_interval_min}-{self.download_interval_max}秒 ({self.download_interval_min/60:.1f}-{self.download_interval_max/60:.1f}分钟)")
print(f" 长休眠间隔: 每{self.long_delay_interval}个文件")
print(f" 长休眠时间: {self.long_delay_min}-{self.long_delay_max}秒 ({self.long_delay_min/60:.1f}-{self.long_delay_max/60:.1f}分钟)")
print(f" 下载目录: {self.download_dir}")
try:
new_interval = int(input(f"长休眠间隔 (当前每{self.long_delay_interval}个文件): ") or self.long_delay_interval)
new_dir = input(f"下载目录 (当前: {self.download_dir}): ").strip() or self.download_dir
self.long_delay_interval = max(new_interval, 1)
if new_dir != self.download_dir:
self.download_dir = new_dir
os.makedirs(new_dir, exist_ok=True)
print(f"📁 下载目录已更新: {os.path.abspath(new_dir)}")
print(f"✅ 设置已更新")
except ValueError:
print("❌ 输入无效,保持原设置")
def close(self):
"""关闭资源"""
if hasattr(self, 'file_db') and self.file_db:
self.file_db.close()
print("🔒 文件数据库连接已关闭")
|
2977094657/ZsxqCrawler
| 6,785
|
accounts_manager.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import json
import time
import threading
from typing import Dict, Any, List, Optional, Tuple
_lock = threading.Lock()
def _get_project_root() -> str:
"""
在当前文件夹向上查找包含 config.toml 的目录,作为项目根目录。
找不到则返回当前文件所在目录。
"""
cur = os.path.abspath(os.path.dirname(__file__))
while True:
if os.path.exists(os.path.join(cur, "config.toml")):
return cur
parent = os.path.dirname(cur)
if parent == cur:
return os.path.abspath(os.path.dirname(__file__))
cur = parent
_ACCOUNTS_FILE = os.path.join(_get_project_root(), "accounts.json")
def _ensure_store() -> None:
"""确保账户存储文件存在"""
if not os.path.exists(_ACCOUNTS_FILE):
with _lock:
# 双重检查
if not os.path.exists(_ACCOUNTS_FILE):
data = {"accounts": [], "group_account_map": {}}
_write_data(data)
def _read_data() -> Dict[str, Any]:
"""读取账户与映射数据"""
_ensure_store()
with _lock:
try:
with open(_ACCOUNTS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
# 文件损坏时重置
data = {"accounts": [], "group_account_map": {}}
_write_data(data)
return data
def _write_data(data: Dict[str, Any]) -> None:
"""原子写入数据"""
tmp_path = _ACCOUNTS_FILE + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
os.replace(tmp_path, _ACCOUNTS_FILE)
def _mask_cookie(cookie: str) -> str:
"""掩码显示 Cookie"""
if not cookie:
return ""
tail = cookie[-8:] if len(cookie) >= 8 else cookie
return f"***{tail}"
def _now_iso() -> str:
"""当前时间 ISO 字符串"""
return time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
def get_accounts(mask_cookie: bool = True) -> List[Dict[str, Any]]:
"""
获取所有账号列表
mask_cookie: 是否对 cookie 进行掩码
"""
data = _read_data()
accounts = data.get("accounts", [])
if mask_cookie:
safe = []
for acc in accounts:
acc_copy = dict(acc)
acc_copy["cookie"] = _mask_cookie(acc_copy.get("cookie", ""))
safe.append(acc_copy)
return safe
return accounts
def get_account_by_id(account_id: str, mask_cookie: bool = False) -> Optional[Dict[str, Any]]:
"""根据ID获取账号"""
data = _read_data()
for acc in data.get("accounts", []):
if acc.get("id") == account_id:
if mask_cookie:
acc_cp = dict(acc)
acc_cp["cookie"] = _mask_cookie(acc_cp.get("cookie", ""))
return acc_cp
return acc
return None
def add_account(cookie: str, name: Optional[str] = None, make_default: bool = False) -> Dict[str, Any]:
"""新增账号"""
if not cookie or not cookie.strip():
raise ValueError("cookie 不能为空")
data = _read_data()
accounts = data.get("accounts", [])
account_id = f"acc_{int(time.time() * 1000)}"
acc = {
"id": account_id,
"name": name or f"账号{len(accounts) + 1}",
"cookie": cookie.strip(),
"created_at": _now_iso(),
"is_default": False,
}
if make_default or len(accounts) == 0:
# 设置为默认,并取消其他默认
for a in accounts:
a["is_default"] = False
acc["is_default"] = True
accounts.append(acc)
data["accounts"] = accounts
_write_data(data)
return acc
def delete_account(account_id: str) -> bool:
"""删除账号,同时清理映射。如果删除默认账号,则将第一个账号设为默认(如存在)"""
data = _read_data()
accounts = data.get("accounts", [])
group_map = data.get("group_account_map", {})
idx = next((i for i, a in enumerate(accounts) if a.get("id") == account_id), None)
if idx is None:
return False
was_default = accounts[idx].get("is_default", False)
accounts.pop(idx)
# 清理映射
group_map = {gid: aid for gid, aid in group_map.items() if aid != account_id}
# 若删除了默认账号,且仍有账号,则设置第一个为默认
if was_default and accounts:
for i, a in enumerate(accounts):
a["is_default"] = (i == 0)
data["accounts"] = accounts
data["group_account_map"] = group_map
_write_data(data)
return True
def set_default_account(account_id: str) -> bool:
"""设置默认账号"""
data = _read_data()
accounts = data.get("accounts", [])
if not any(a.get("id") == account_id for a in accounts):
return False
for a in accounts:
a["is_default"] = (a.get("id") == account_id)
data["accounts"] = accounts
_write_data(data)
return True
def get_default_account(mask_cookie: bool = False) -> Optional[Dict[str, Any]]:
"""获取默认账号"""
data = _read_data()
accounts = data.get("accounts", [])
default = next((a for a in accounts if a.get("is_default")), None)
if not default and accounts:
default = accounts[0]
if not default:
return None
if mask_cookie:
cp = dict(default)
cp["cookie"] = _mask_cookie(cp.get("cookie", ""))
return cp
return default
def assign_group_account(group_id: str, account_id: str) -> Tuple[bool, str]:
"""将群组分配到指定账号"""
if not group_id:
return False, "group_id 不能为空"
data = _read_data()
if not any(a.get("id") == account_id for a in data.get("accounts", [])):
return False, "账号不存在"
group_map = data.get("group_account_map", {})
group_map[str(group_id)] = account_id
data["group_account_map"] = group_map
_write_data(data)
return True, "分配成功"
def get_group_account_mapping() -> Dict[str, str]:
"""获取群组与账号ID映射"""
data = _read_data()
return data.get("group_account_map", {})
def get_account_for_group(group_id: str, mask_cookie: bool = False) -> Optional[Dict[str, Any]]:
"""获取某群组使用的账号(优先映射,其次默认)"""
data = _read_data()
group_map = data.get("group_account_map", {})
acc_id = group_map.get(str(group_id))
account = None
if acc_id:
account = next((a for a in data.get("accounts", []) if a.get("id") == acc_id), None)
if not account:
account = get_default_account(mask_cookie=False)
if not account:
return None
if mask_cookie:
cp = dict(account)
cp["cookie"] = _mask_cookie(cp.get("cookie", ""))
return cp
return account
def get_account_summary_for_group(group_id: str) -> Optional[Dict[str, Any]]:
"""获取群组所属账号的摘要信息"""
acc = get_account_for_group(group_id, mask_cookie=True)
if not acc:
return None
return {
"id": acc.get("id"),
"name": acc.get("name"),
"is_default": acc.get("is_default", False),
"created_at": acc.get("created_at"),
"cookie": acc.get("cookie"), # 已掩码
}
|
2977094657/ZsxqCrawler
| 4,811
|
account_info_db.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import json
import sqlite3
import threading
from datetime import datetime
from typing import Optional, Dict, Any
from db_path_manager import get_db_path_manager
_lock = threading.Lock()
def _ensure_dir(path: str):
d = os.path.dirname(path)
if d and not os.path.exists(d):
os.makedirs(d, exist_ok=True)
class AccountInfoDB:
"""
账号信息数据库:持久化 /v3/users/self 的用户信息
数据库存放路径:DatabasePathManager.get_config_db_path()
表:accounts_self
"""
def __init__(self, db_path: Optional[str] = None):
pm = get_db_path_manager()
self.db_path = db_path or pm.get_config_db_path()
_ensure_dir(self.db_path)
self.conn = sqlite3.connect(self.db_path, check_same_thread=False)
self.conn.execute("PRAGMA journal_mode=WAL;")
self.conn.execute("PRAGMA foreign_keys=ON;")
self.cursor = self.conn.cursor()
self._ensure_schema()
def _ensure_schema(self):
with _lock:
self.cursor.execute(
"""
CREATE TABLE IF NOT EXISTS accounts_self (
account_id TEXT PRIMARY KEY,
uid TEXT,
name TEXT,
avatar_url TEXT,
location TEXT,
user_sid TEXT,
grade TEXT,
raw_json TEXT,
fetched_at TEXT
)
"""
)
self.conn.commit()
def upsert_self_info(
self,
account_id: str,
self_info: Dict[str, Any],
raw_json: Optional[Dict[str, Any]] = None,
):
"""
保存/更新用户信息
self_info 期望字段:uid, name, avatar_url, location, user_sid, grade
"""
if not account_id:
raise ValueError("account_id 不能为空")
now = datetime.now().isoformat(timespec="seconds")
raw_json_str = json.dumps(raw_json or {}, ensure_ascii=False)
with _lock:
self.cursor.execute(
"""
INSERT INTO accounts_self (account_id, uid, name, avatar_url, location, user_sid, grade, raw_json, fetched_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(account_id) DO UPDATE SET
uid=excluded.uid,
name=excluded.name,
avatar_url=excluded.avatar_url,
location=excluded.location,
user_sid=excluded.user_sid,
grade=excluded.grade,
raw_json=excluded.raw_json,
fetched_at=excluded.fetched_at
""",
(
account_id,
self_info.get("uid"),
self_info.get("name"),
self_info.get("avatar_url"),
self_info.get("location"),
self_info.get("user_sid"),
self_info.get("grade"),
raw_json_str,
now,
),
)
self.conn.commit()
def get_self_info(self, account_id: str) -> Optional[Dict[str, Any]]:
if not account_id:
return None
with _lock:
self.cursor.execute(
"""
SELECT account_id, uid, name, avatar_url, location, user_sid, grade, raw_json, fetched_at
FROM accounts_self
WHERE account_id = ?
""",
(account_id,),
)
row = self.cursor.fetchone()
if not row:
return None
return {
"account_id": row[0],
"uid": row[1],
"name": row[2],
"avatar_url": row[3],
"location": row[4],
"user_sid": row[5],
"grade": row[6],
"raw_json": self._safe_load_json(row[7]),
"fetched_at": row[8],
}
def _safe_load_json(self, s: Optional[str]) -> Any:
if not s:
return None
try:
return json.loads(s)
except Exception:
return None
def close(self):
with _lock:
try:
self.cursor.close()
except Exception:
pass
try:
self.conn.close()
except Exception:
pass
_db_singleton: Optional[AccountInfoDB] = None
_db_lock = threading.Lock()
def get_account_info_db() -> AccountInfoDB:
global _db_singleton
if _db_singleton is None:
with _db_lock:
if _db_singleton is None:
_db_singleton = AccountInfoDB()
return _db_singleton
|
2977094657/ZsxqCrawler
| 2,159
|
README.md
|
<div align="center">
<img src="images/_Image.png" alt="知识星球数据采集器" width="200">
<h1>🌟 知识星球数据采集器</h1>
<p>知识星球内容爬取与文件下载工具,支持话题采集、文件批量下载等功能</p>
[](https://www.python.org/downloads/)
[](LICENSE)
[]()
<img src="images/info.png" alt="群组详情页面" height="400">
</div>
## ✨ 项目特性
- 🎯 **智能采集**: 支持全量、增量、智能更新等多种采集模式
- 📁 **文件管理**: 自动下载和管理知识星球中的文件资源,支持直接下载
- 💻 **命令行界面**: 提供强大的交互式命令行工具
- 🌐 **Web界面**: 现代化的React前端界面,操作更直观
## 🖼️ 界面展示
### Web界面
<div align="center">
<img src="images/home.png" alt="首页界面" height="400">
<p><em>首页 - 群组选择和概览</em></p>
</div>
<div align="center">
<img src="images/config.png" alt="配置页面" height="400">
<p><em>配置页面 - 爬取间隔设置</em></p>
</div>
<div align="center">
<img src="images/log.png" alt="日志页面" height="400">
<p><em>日志页面 - 实时任务执行日志</em></p>
</div>
## 🚀 快速开始
### 1. 安装部署
```bash
# 1. 克隆项目
git clone https://github.com/2977094657/ZsxqCrawler.git
cd ZsxqCrawler
# 2. 安装uv包管理器(推荐)
pip install uv
# 3. 安装依赖
uv sync
```
### 2. 获取认证信息
在使用工具前,需要获取知识星球的Cookie和群组ID:
1. **获取Cookie**:
- 使用浏览器登录知识星球
- 按 `F12` 打开开发者工具
- 切换到 `Network` 标签
- 刷新页面,找到任意API请求
- 复制请求头中的 `Cookie` 值
2. **获取群组ID**:
- 访问目标知识星球页面
- URL格式:`https://wx.zsxq.com/group/{群组ID}`
- 从URL中提取群组ID
3. **首次使用**:
- 编辑 `config.toml` 文件,填入您的配置信息
- 或者启动Web界面后按照提示进行配置
### 3. 运行应用
#### 方式一:Web界面(推荐)
```bash
# 1. 启动后端API服务
uv run main.py
# 2. 启动前端服务(新开终端窗口)
cd frontend
npm run dev
```
然后访问:
- 🌐 **Web界面**: http://localhost:3060
- 📖 **API文档**: http://localhost:8000/docs
#### 方式二:命令行工具
```bash
# 运行交互式命令行工具
uv run zsxq_interactive_crawler.py
```
<div align="center">
<img src="images/QQ20250703-170055.png" alt="命令行界面" height="400">
<p><em>命令行界面 - 交互式操作控制台</em></p>
</div>
## 🤝 贡献指南
欢迎提交Issue和Pull Request!
## 📄 许可证
本项目采用 [MIT License](LICENSE) 开源协议。
## ⚠️ 免责声明
本工具仅供学习和研究使用,请遵守知识星球的服务条款和相关法律法规。使用本工具产生的任何后果由使用者自行承担。
---
<div align="center">
<p>如果这个项目对你有帮助,请给个 ⭐ Star 支持一下!</p>
</div>
|
2977094657/ZsxqCrawler
| 61,717
|
zsxq_database.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
from typing import Dict, Any, Optional, List
class ZSXQDatabase:
"""知识星球数据库管理器"""
def __init__(self, db_path: str = "zsxq_interactive.db"):
self.db_path = db_path
self.conn = sqlite3.connect(db_path, check_same_thread=False)
self.cursor = self.conn.cursor()
self._init_database()
def _init_database(self):
"""初始化数据库表结构"""
# 群组表 - 适配现有结构
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS groups (
group_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
type TEXT,
background_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 用户表 - 适配现有结构
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
alias TEXT,
avatar_url TEXT,
location TEXT,
description TEXT,
ai_comment_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 话题表 - 适配现有结构
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS topics (
topic_id INTEGER PRIMARY KEY,
group_id INTEGER NOT NULL,
type TEXT NOT NULL,
title TEXT,
create_time TEXT,
digested BOOLEAN DEFAULT FALSE,
sticky BOOLEAN DEFAULT FALSE,
likes_count INTEGER DEFAULT 0,
tourist_likes_count INTEGER DEFAULT 0,
rewards_count INTEGER DEFAULT 0,
comments_count INTEGER DEFAULT 0,
reading_count INTEGER DEFAULT 0,
readers_count INTEGER DEFAULT 0,
answered BOOLEAN DEFAULT FALSE,
silenced BOOLEAN DEFAULT FALSE,
annotation TEXT,
user_liked BOOLEAN DEFAULT FALSE,
user_subscribed BOOLEAN DEFAULT FALSE,
imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (group_id) REFERENCES groups (group_id)
)
''')
# 话题内容表(talks)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS talks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
owner_user_id INTEGER,
text TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (owner_user_id) REFERENCES users (user_id)
)
''')
# 文章表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS articles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
title TEXT,
article_id TEXT,
article_url TEXT,
inline_article_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id)
)
''')
# 图片表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS images (
image_id INTEGER PRIMARY KEY,
topic_id INTEGER,
comment_id INTEGER,
type TEXT,
thumbnail_url TEXT,
thumbnail_width INTEGER,
thumbnail_height INTEGER,
large_url TEXT,
large_width INTEGER,
large_height INTEGER,
original_url TEXT,
original_width INTEGER,
original_height INTEGER,
original_size INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id)
)
''')
# 点赞表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS likes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
user_id INTEGER,
create_time TEXT,
imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (user_id) REFERENCES users (user_id)
)
''')
# 表情点赞表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS like_emojis (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
emoji_key TEXT,
likes_count INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id)
)
''')
# 用户表情点赞表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS user_liked_emojis (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
emoji_key TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id)
)
''')
# 评论表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS comments (
comment_id INTEGER PRIMARY KEY,
topic_id INTEGER,
owner_user_id INTEGER,
parent_comment_id INTEGER,
repliee_user_id INTEGER,
text TEXT,
create_time TEXT,
likes_count INTEGER DEFAULT 0,
rewards_count INTEGER DEFAULT 0,
replies_count INTEGER DEFAULT 0,
sticky BOOLEAN DEFAULT FALSE,
imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (owner_user_id) REFERENCES users (user_id),
FOREIGN KEY (parent_comment_id) REFERENCES comments (comment_id),
FOREIGN KEY (repliee_user_id) REFERENCES users (user_id)
)
''')
# 问题表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS questions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
owner_user_id INTEGER,
questionee_user_id INTEGER,
text TEXT,
expired BOOLEAN DEFAULT FALSE,
anonymous BOOLEAN DEFAULT FALSE,
owner_questions_count INTEGER,
owner_join_time TEXT,
owner_status TEXT,
owner_location TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (owner_user_id) REFERENCES users (user_id),
FOREIGN KEY (questionee_user_id) REFERENCES users (user_id)
)
''')
# 回答表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS answers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
owner_user_id INTEGER,
text TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (owner_user_id) REFERENCES users (user_id)
)
''')
# 标签表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS tags (
tag_id INTEGER PRIMARY KEY AUTOINCREMENT,
group_id INTEGER NOT NULL,
tag_name TEXT NOT NULL,
hid TEXT,
topic_count INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(group_id, tag_name),
FOREIGN KEY (group_id) REFERENCES groups (group_id)
)
''')
# 话题标签关联表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS topic_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER NOT NULL,
tag_id INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(topic_id, tag_id),
FOREIGN KEY (topic_id) REFERENCES topics (topic_id),
FOREIGN KEY (tag_id) REFERENCES tags (tag_id)
)
''')
# 话题文件表 (talk.files数组)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS topic_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER,
file_id INTEGER,
name TEXT,
hash TEXT,
size INTEGER,
duration INTEGER,
download_count INTEGER,
create_time TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (topic_id) REFERENCES topics (topic_id)
)
''')
self.conn.commit()
def import_topic_data(self, topic_data: Dict[str, Any]) -> bool:
"""导入话题数据到数据库"""
try:
topic_id = topic_data.get('topic_id')
group_info = topic_data.get('group', {})
if not topic_id:
return False
# 导入群组信息
if group_info:
self._upsert_group(group_info)
# 导入话题相关的所有用户信息
self._import_all_users(topic_data)
# 导入话题信息
self._upsert_topic(topic_data)
# 导入话题内容(talk)
if 'talk' in topic_data and topic_data['talk']:
self._upsert_talk(topic_id, topic_data['talk'])
# 导入文章信息(如果话题类型是文章)
self._import_articles(topic_id, topic_data)
# 导入图片信息
self._import_images(topic_id, topic_data)
# 导入点赞信息
self._import_likes(topic_id, topic_data)
# 导入表情点赞信息
self._import_like_emojis(topic_id, topic_data)
# 导入用户表情点赞信息
self._import_user_liked_emojis(topic_id, topic_data)
# 导入评论信息
if 'show_comments' in topic_data:
self._import_comments(topic_id, topic_data['show_comments'])
# 导入问题信息
if 'question' in topic_data and topic_data['question']:
self._upsert_question(topic_id, topic_data['question'])
# 导入回答信息
if 'answer' in topic_data and topic_data['answer']:
self._upsert_answer(topic_id, topic_data['answer'])
# 导入标签信息
self._import_tags(topic_id, topic_data)
# 导入文件信息
if 'talk' in topic_data and topic_data['talk'] and 'files' in topic_data['talk']:
self._import_files(topic_id, topic_data['talk']['files'])
return True
except Exception as e:
print(f"❌ 导入话题数据失败: {e}")
import traceback
traceback.print_exc()
return False
def _upsert_group(self, group_data: Dict[str, Any]):
"""插入或更新群组信息"""
group_id = group_data.get('group_id')
if not group_id:
return
# 获取当前时间作为created_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO groups
(group_id, name, type, background_url, created_at)
VALUES (?, ?, ?, ?, ?)
''', (
group_id,
group_data.get('name', ''),
group_data.get('type', ''),
group_data.get('background_url', ''),
current_time
))
def _upsert_user(self, user_data: Dict[str, Any]):
"""插入或更新用户信息"""
user_id = user_data.get('user_id')
if not user_id:
return
# 获取当前时间作为created_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO users
(user_id, name, alias, avatar_url, location, description, ai_comment_url, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (
user_id,
user_data.get('name', ''),
user_data.get('alias', ''),
user_data.get('avatar_url', ''),
user_data.get('location', ''),
user_data.get('description', ''),
user_data.get('ai_comment_url', ''),
current_time
))
def _upsert_topic(self, topic_data: Dict[str, Any]):
"""插入或更新话题信息"""
topic_id = topic_data.get('topic_id')
if not topic_id:
return
# 获取当前时间作为imported_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO topics
(topic_id, group_id, type, title, create_time, digested, sticky,
likes_count, tourist_likes_count, rewards_count, comments_count,
reading_count, readers_count, answered, silenced, annotation,
user_liked, user_subscribed, imported_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
topic_id,
topic_data.get('group', {}).get('group_id', ''),
topic_data.get('type', ''),
topic_data.get('title', ''),
topic_data.get('create_time', ''),
topic_data.get('digested', False),
topic_data.get('sticky', False),
topic_data.get('likes_count', 0),
topic_data.get('tourist_likes_count', 0),
topic_data.get('rewards_count', 0),
topic_data.get('comments_count', 0),
topic_data.get('reading_count', 0),
topic_data.get('readers_count', 0),
topic_data.get('answered', False),
topic_data.get('silenced', False),
topic_data.get('annotation', ''),
topic_data.get('user_liked', False),
topic_data.get('user_subscribed', False),
current_time
))
def update_topic_stats(self, topic_data: Dict[str, Any]) -> bool:
"""仅更新话题的统计信息,不导入其他相关数据"""
try:
topic_id = topic_data.get('topic_id')
if not topic_id:
return False
# 获取当前时间作为imported_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
# 只更新统计相关字段,不更新内容字段
self.cursor.execute('''
UPDATE topics
SET likes_count = ?, tourist_likes_count = ?, rewards_count = ?,
comments_count = ?, reading_count = ?, readers_count = ?,
digested = ?, sticky = ?, user_liked = ?, user_subscribed = ?,
imported_at = ?
WHERE topic_id = ?
''', (
topic_data.get('likes_count', 0),
topic_data.get('tourist_likes_count', 0),
topic_data.get('rewards_count', 0),
topic_data.get('comments_count', 0),
topic_data.get('reading_count', 0),
topic_data.get('readers_count', 0),
topic_data.get('digested', False),
topic_data.get('sticky', False),
topic_data.get('user_specific', {}).get('liked', False),
topic_data.get('user_specific', {}).get('subscribed', False),
current_time,
topic_id
))
# 检查是否有行被更新
if self.cursor.rowcount > 0:
return True
else:
print(f"警告:话题 {topic_id} 不存在,无法更新")
return False
except Exception as e:
print(f"❌ 更新话题统计信息失败: {e}")
import traceback
traceback.print_exc()
return False
def get_database_stats(self) -> Dict[str, Any]:
"""获取数据库统计信息"""
stats = {}
tables = ['groups', 'users', 'topics', 'talks', 'articles', 'images',
'likes', 'like_emojis', 'user_liked_emojis', 'comments',
'questions', 'answers']
for table in tables:
try:
self.cursor.execute(f'SELECT COUNT(*) FROM {table}')
stats[table] = self.cursor.fetchone()[0]
except Exception as e:
print(f"获取表 {table} 统计信息失败: {e}")
stats[table] = 0
return stats
def get_timestamp_range_info(self) -> Dict[str, Any]:
"""获取话题时间戳范围信息"""
try:
# 获取最新话题时间
self.cursor.execute('''
SELECT create_time FROM topics
WHERE create_time IS NOT NULL AND create_time != ''
ORDER BY create_time DESC LIMIT 1
''')
newest_result = self.cursor.fetchone()
newest_time = newest_result[0] if newest_result else None
# 获取最老话题时间
self.cursor.execute('''
SELECT create_time FROM topics
WHERE create_time IS NOT NULL AND create_time != ''
ORDER BY create_time ASC LIMIT 1
''')
oldest_result = self.cursor.fetchone()
oldest_time = oldest_result[0] if oldest_result else None
# 获取话题总数
self.cursor.execute('SELECT COUNT(*) FROM topics')
total_topics = self.cursor.fetchone()[0]
# 判断是否有数据
has_data = newest_time is not None and oldest_time is not None
return {
'newest_time': newest_time,
'oldest_time': oldest_time,
'newest_timestamp': newest_time,
'oldest_timestamp': oldest_time,
'total_topics': total_topics,
'has_data': has_data
}
except Exception as e:
print(f"获取时间戳范围信息失败: {e}")
return {
'newest_time': None,
'oldest_time': None,
'newest_timestamp': None,
'oldest_timestamp': None,
'total_topics': 0,
'has_data': False
}
def get_oldest_topic_timestamp(self) -> Optional[str]:
"""获取数据库中最老的话题时间戳"""
try:
self.cursor.execute('''
SELECT create_time FROM topics
WHERE create_time IS NOT NULL AND create_time != ''
ORDER BY create_time ASC LIMIT 1
''')
result = self.cursor.fetchone()
return result[0] if result else None
except Exception as e:
print(f"获取最老话题时间戳失败: {e}")
return None
def get_newest_topic_timestamp(self) -> Optional[str]:
"""获取数据库中最新的话题时间戳"""
try:
self.cursor.execute('''
SELECT create_time FROM topics
WHERE create_time IS NOT NULL AND create_time != ''
ORDER BY create_time DESC LIMIT 1
''')
result = self.cursor.fetchone()
return result[0] if result else None
except Exception as e:
print(f"获取最新话题时间戳失败: {e}")
return None
def _import_all_users(self, topic_data: Dict[str, Any]):
"""导入话题相关的所有用户信息"""
# 导入talk中的用户
if 'talk' in topic_data and topic_data['talk'] and 'owner' in topic_data['talk']:
self._upsert_user(topic_data['talk']['owner'])
# 导入question中的用户
if 'question' in topic_data and topic_data['question']:
# 对于非匿名用户,导入提问者信息
if 'owner' in topic_data['question'] and not topic_data['question'].get('anonymous', False):
self._upsert_user(topic_data['question']['owner'])
# 导入被提问者信息(无论是否匿名都有)
if 'questionee' in topic_data['question']:
self._upsert_user(topic_data['question']['questionee'])
# 导入answer中的用户
if 'answer' in topic_data and topic_data['answer'] and 'owner' in topic_data['answer']:
self._upsert_user(topic_data['answer']['owner'])
# 导入latest_likes中的用户
if 'latest_likes' in topic_data:
for like in topic_data['latest_likes']:
if 'owner' in like:
self._upsert_user(like['owner'])
# 导入comments中的用户
if 'show_comments' in topic_data:
for comment in topic_data['show_comments']:
if 'owner' in comment:
self._upsert_user(comment['owner'])
if 'repliee' in comment:
self._upsert_user(comment['repliee'])
def _upsert_talk(self, topic_id: int, talk_data: Dict[str, Any]):
"""插入或更新话题内容"""
if not talk_data:
return
owner_user_id = talk_data.get('owner', {}).get('user_id')
if not owner_user_id:
return
# 获取当前时间作为created_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO talks
(topic_id, owner_user_id, text, created_at)
VALUES (?, ?, ?, ?)
''', (
topic_id,
owner_user_id,
talk_data.get('text', ''),
current_time
))
def _import_images(self, topic_id: int, topic_data: Dict[str, Any]):
"""导入图片信息"""
images_to_import = []
# 从talk中获取图片
if 'talk' in topic_data and topic_data['talk'] and 'images' in topic_data['talk']:
for img in topic_data['talk']['images']:
images_to_import.append((img, None)) # (image_data, comment_id)
# 从comments中获取图片
if 'show_comments' in topic_data:
for comment in topic_data['show_comments']:
if 'images' in comment:
comment_id = comment.get('comment_id')
for img in comment['images']:
images_to_import.append((img, comment_id))
# 导入所有图片
for img_data, comment_id in images_to_import:
self._upsert_image(topic_id, img_data, comment_id)
def _upsert_image(self, topic_id: int, image_data: Dict[str, Any], comment_id: Optional[int] = None):
"""插入或更新图片信息"""
image_id = image_data.get('image_id')
if not image_id:
return
thumbnail = image_data.get('thumbnail', {})
large = image_data.get('large', {})
original = image_data.get('original', {})
# 获取当前时间作为created_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO images
(image_id, topic_id, comment_id, type, thumbnail_url, thumbnail_width, thumbnail_height,
large_url, large_width, large_height, original_url, original_width, original_height, original_size, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
image_id,
topic_id,
comment_id,
image_data.get('type', ''),
thumbnail.get('url', ''),
thumbnail.get('width'),
thumbnail.get('height'),
large.get('url', ''),
large.get('width'),
large.get('height'),
original.get('url', ''),
original.get('width'),
original.get('height'),
original.get('size'),
current_time
))
def _import_likes(self, topic_id: int, topic_data: Dict[str, Any]):
"""导入点赞信息"""
if 'latest_likes' not in topic_data:
return
for like in topic_data['latest_likes']:
owner = like.get('owner', {})
user_id = owner.get('user_id')
if user_id:
# 获取当前时间作为imported_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR IGNORE INTO likes
(topic_id, user_id, create_time, imported_at)
VALUES (?, ?, ?, ?)
''', (
topic_id,
user_id,
like.get('create_time', ''),
current_time
))
if topic_data['latest_likes']:
pass # 数据已导入,无需额外日志
def _import_like_emojis(self, topic_id: int, topic_data: Dict[str, Any]):
"""导入表情点赞信息"""
if 'likes_detail' not in topic_data or 'emojis' not in topic_data['likes_detail']:
return
for emoji in topic_data['likes_detail']['emojis']:
emoji_key = emoji.get('emoji_key')
likes_count = emoji.get('likes_count', 0)
if emoji_key:
# 获取当前时间作为created_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO like_emojis
(topic_id, emoji_key, likes_count, created_at)
VALUES (?, ?, ?, ?)
''', (
topic_id,
emoji_key,
likes_count,
current_time
))
if topic_data['likes_detail']['emojis']:
pass # 数据已导入,无需额外日志
def _import_user_liked_emojis(self, topic_id: int, topic_data: Dict[str, Any]):
"""导入用户表情点赞信息"""
if 'user_specific' not in topic_data or 'liked_emojis' not in topic_data['user_specific']:
return
for emoji_key in topic_data['user_specific']['liked_emojis']:
if emoji_key:
self.cursor.execute('''
INSERT OR IGNORE INTO user_liked_emojis
(topic_id, emoji_key)
VALUES (?, ?)
''', (
topic_id,
emoji_key
))
if topic_data['user_specific']['liked_emojis']:
pass # 数据已导入,无需额外日志
def _import_comments(self, topic_id: int, comments: List[Dict[str, Any]]):
"""导入评论信息"""
for comment in comments:
self._upsert_comment(topic_id, comment)
# 导入评论的图片
if 'images' in comment and comment['images']:
self._import_comment_images(topic_id, comment['comment_id'], comment['images'])
if comments:
pass # 数据已导入,无需额外日志
def import_additional_comments(self, topic_id: int, comments: List[Dict[str, Any]]):
"""导入额外获取的评论信息(来自评论API)"""
if not comments:
return
print(f"📝 导入话题 {topic_id} 的 {len(comments)} 条额外评论...")
for comment in comments:
# 导入评论作者
if 'owner' in comment and comment['owner']:
self._upsert_user(comment['owner'])
# 导入回复人(如果存在)
if 'repliee' in comment and comment['repliee']:
self._upsert_user(comment['repliee'])
# 导入评论
self._upsert_comment(topic_id, comment)
# 导入评论的图片
if 'images' in comment and comment['images']:
self._import_comment_images(topic_id, comment['comment_id'], comment['images'])
print(f"✅ 完成导入 {len(comments)} 条评论")
def _upsert_comment(self, topic_id: int, comment_data: Dict[str, Any]):
"""插入或更新评论信息"""
comment_id = comment_data.get('comment_id')
if not comment_id:
return
owner_user_id = comment_data.get('owner', {}).get('user_id')
repliee_user_id = comment_data.get('repliee', {}).get('user_id')
# 获取当前时间作为imported_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO comments
(comment_id, topic_id, owner_user_id, parent_comment_id, repliee_user_id,
text, create_time, likes_count, rewards_count, replies_count, sticky, imported_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
comment_id,
topic_id,
owner_user_id,
comment_data.get('parent_comment_id'),
repliee_user_id,
comment_data.get('text', ''),
comment_data.get('create_time', ''),
comment_data.get('likes_count', 0),
comment_data.get('rewards_count', 0),
comment_data.get('replies_count', 0),
comment_data.get('sticky', False),
current_time
))
def _import_comment_images(self, topic_id: int, comment_id: int, images: List[Dict[str, Any]]):
"""导入评论的图片信息"""
for image in images:
if not image.get('image_id'):
continue
# 获取当前时间作为created_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO images
(image_id, topic_id, comment_id, type, thumbnail_url, thumbnail_width, thumbnail_height,
large_url, large_width, large_height, original_url, original_width, original_height,
original_size, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
image.get('image_id'),
topic_id,
comment_id,
image.get('type', ''),
image.get('thumbnail', {}).get('url', ''),
image.get('thumbnail', {}).get('width', 0),
image.get('thumbnail', {}).get('height', 0),
image.get('large', {}).get('url', ''),
image.get('large', {}).get('width', 0),
image.get('large', {}).get('height', 0),
image.get('original', {}).get('url', ''),
image.get('original', {}).get('width', 0),
image.get('original', {}).get('height', 0),
image.get('original', {}).get('size', 0),
current_time
))
def _upsert_question(self, topic_id: int, question_data: Dict[str, Any]):
"""插入或更新问题信息"""
owner_user_id = question_data.get('owner', {}).get('user_id')
questionee_user_id = question_data.get('questionee', {}).get('user_id')
is_anonymous = question_data.get('anonymous', False)
# 对于匿名用户,owner_user_id 可能为 None,但仍需要存储问题信息
# 只有在既没有 owner_user_id 又没有问题文本时才跳过
if not owner_user_id and not question_data.get('text'):
return
owner_detail = question_data.get('owner_detail', {})
# 获取当前时间作为created_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO questions
(topic_id, owner_user_id, questionee_user_id, text, expired, anonymous,
owner_questions_count, owner_join_time, owner_status, owner_location, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
topic_id,
owner_user_id, # 对于匿名用户可能为 None
questionee_user_id,
question_data.get('text', ''),
question_data.get('expired', False),
is_anonymous,
owner_detail.get('questions_count'),
owner_detail.get('join_time', owner_detail.get('estimated_join_time', '')), # 支持 estimated_join_time
owner_detail.get('status', ''),
question_data.get('owner_location', ''),
current_time
))
def _upsert_answer(self, topic_id: int, answer_data: Dict[str, Any]):
"""插入或更新回答信息"""
owner_user_id = answer_data.get('owner', {}).get('user_id')
if not owner_user_id:
return
# 获取当前时间作为created_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO answers
(topic_id, owner_user_id, text, created_at)
VALUES (?, ?, ?, ?)
''', (
topic_id,
owner_user_id,
answer_data.get('text', ''),
current_time
))
def _import_articles(self, topic_id: int, topic_data: Dict[str, Any]):
"""导入文章信息"""
# 检查talk类型话题中的article字段
if 'talk' in topic_data and topic_data['talk'] and 'article' in topic_data['talk']:
article_data = topic_data['talk']['article']
if article_data:
self._upsert_article(topic_id, article_data)
return
# 检查顶层的article字段(如果存在)
if 'article' in topic_data and topic_data['article']:
article_data = topic_data['article']
self._upsert_article(topic_id, article_data)
return
# 如果话题类型是article但没有article字段,从title等信息构建
topic_type = topic_data.get('type', '')
if topic_type == 'article' and topic_data.get('title'):
article_data = {
'title': topic_data.get('title', ''),
'article_id': str(topic_id), # 使用topic_id作为article_id
'article_url': '', # 暂时为空
'inline_article_url': '' # 暂时为空
}
self._upsert_article(topic_id, article_data)
def _upsert_article(self, topic_id: int, article_data: Dict[str, Any]):
"""插入或更新文章信息"""
title = article_data.get('title', '')
article_id = article_data.get('article_id', '')
if not title and not article_id:
return
# 获取话题的创建时间作为文章创建时间
self.cursor.execute('''
SELECT create_time FROM topics WHERE topic_id = ?
''', (topic_id,))
result = self.cursor.fetchone()
created_at = result[0] if result else ''
self.cursor.execute('''
INSERT OR REPLACE INTO articles
(topic_id, title, article_id, article_url, inline_article_url, created_at)
VALUES (?, ?, ?, ?, ?, ?)
''', (
topic_id,
title,
article_id,
article_data.get('article_url', ''),
article_data.get('inline_article_url', ''),
created_at
))
def _import_files(self, topic_id: int, files_data: List[Dict[str, Any]]):
"""导入话题文件信息"""
if not files_data:
return
for file_data in files_data:
if not file_data.get('file_id'):
continue
# 获取当前时间作为created_at(使用东八区时间格式)
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR REPLACE INTO topic_files
(topic_id, file_id, name, hash, size, duration, download_count, create_time, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
topic_id,
file_data.get('file_id'),
file_data.get('name', ''),
file_data.get('hash', ''),
file_data.get('size', 0),
file_data.get('duration', 0),
file_data.get('download_count', 0),
file_data.get('create_time', ''),
current_time
))
def get_topic_detail(self, topic_id: int):
"""获取完整的话题详情"""
try:
# 1. 获取基本话题信息和群组信息
self.cursor.execute('''
SELECT
t.topic_id, t.type, t.title, t.create_time, t.digested, t.sticky,
t.likes_count, t.tourist_likes_count, t.rewards_count, t.comments_count,
t.reading_count, t.readers_count, t.answered, t.silenced, t.annotation,
t.user_liked, t.user_subscribed,
g.group_id, g.name as group_name, g.type as group_type, g.background_url
FROM topics t
LEFT JOIN groups g ON t.group_id = g.group_id
WHERE t.topic_id = ?
''', (topic_id,))
topic_row = self.cursor.fetchone()
if not topic_row:
return None
# 构建基本话题信息
topic_detail = {
"topic_id": topic_row[0],
"type": topic_row[1],
"title": topic_row[2],
"create_time": topic_row[3],
"digested": bool(topic_row[4]),
"sticky": bool(topic_row[5]),
"likes_count": topic_row[6],
"tourist_likes_count": topic_row[7],
"rewards_count": topic_row[8],
"comments_count": topic_row[9],
"reading_count": topic_row[10],
"readers_count": topic_row[11],
"answered": bool(topic_row[12]),
"silenced": bool(topic_row[13]),
"annotation": topic_row[14],
"group": {
"group_id": topic_row[17],
"name": topic_row[18],
"type": topic_row[19],
"background_url": topic_row[20]
},
"user_specific": {
"liked": bool(topic_row[15]),
"liked_emojis": [],
"subscribed": bool(topic_row[16])
}
}
# 2. 获取话题内容(talk)
self.cursor.execute('''
SELECT
t.text,
u.user_id, u.name, u.alias, u.avatar_url, u.location, u.description
FROM talks t
LEFT JOIN users u ON t.owner_user_id = u.user_id
WHERE t.topic_id = ?
LIMIT 1
''', (topic_id,))
talk_row = self.cursor.fetchone()
if talk_row:
talk_data = {
"text": talk_row[0],
"owner": {
"user_id": talk_row[1],
"name": talk_row[2],
"alias": talk_row[3],
"avatar_url": talk_row[4],
"location": talk_row[5],
"description": talk_row[6]
}
}
# 获取话题图片
self.cursor.execute('''
SELECT
image_id, type, thumbnail_url, thumbnail_width, thumbnail_height,
large_url, large_width, large_height,
original_url, original_width, original_height, original_size
FROM images
WHERE topic_id = ? AND comment_id IS NULL
ORDER BY image_id
''', (topic_id,))
images = []
for img_row in self.cursor.fetchall():
images.append({
"image_id": img_row[0],
"type": img_row[1],
"thumbnail": {
"url": img_row[2],
"width": img_row[3],
"height": img_row[4]
},
"large": {
"url": img_row[5],
"width": img_row[6],
"height": img_row[7]
},
"original": {
"url": img_row[8],
"width": img_row[9],
"height": img_row[10],
"size": img_row[11]
}
})
if images:
talk_data["images"] = images
# 获取话题文件
self.cursor.execute('''
SELECT
file_id, name, hash, size, duration, download_count, create_time
FROM topic_files
WHERE topic_id = ?
ORDER BY file_id
''', (topic_id,))
files = []
for file_row in self.cursor.fetchall():
files.append({
"file_id": file_row[0],
"name": file_row[1],
"hash": file_row[2],
"size": file_row[3],
"duration": file_row[4],
"download_count": file_row[5],
"create_time": file_row[6]
})
if files:
talk_data["files"] = files
# 读取文章信息(如有)
self.cursor.execute('''
SELECT title, article_id, article_url, inline_article_url
FROM articles
WHERE topic_id = ?
LIMIT 1
''', (topic_id,))
article_row = self.cursor.fetchone()
if article_row:
talk_data["article"] = {
"title": article_row[0],
"article_id": article_row[1],
"article_url": article_row[2],
"inline_article_url": article_row[3]
}
topic_detail["talk"] = talk_data
# 3. 获取最新点赞
self.cursor.execute('''
SELECT
l.create_time,
u.user_id, u.name, u.avatar_url
FROM likes l
LEFT JOIN users u ON l.user_id = u.user_id
WHERE l.topic_id = ?
ORDER BY l.create_time DESC
LIMIT 5
''', (topic_id,))
latest_likes = []
for like_row in self.cursor.fetchall():
latest_likes.append({
"create_time": like_row[0],
"owner": {
"user_id": like_row[1],
"name": like_row[2],
"avatar_url": like_row[3]
}
})
topic_detail["latest_likes"] = latest_likes
# 4. 获取评论 - 不再限制为10条,返回所有评论
self.cursor.execute('''
SELECT
c.comment_id, c.text, c.create_time, c.likes_count, c.rewards_count, c.sticky,
c.parent_comment_id, c.replies_count,
u.user_id, u.name, u.alias, u.avatar_url, u.location, u.description,
r.user_id as repliee_user_id, r.name as repliee_name, r.avatar_url as repliee_avatar_url
FROM comments c
LEFT JOIN users u ON c.owner_user_id = u.user_id
LEFT JOIN users r ON c.repliee_user_id = r.user_id
WHERE c.topic_id = ?
ORDER BY c.create_time ASC
''', (topic_id,))
show_comments = []
for comment_row in self.cursor.fetchall():
comment_id = comment_row[0]
comment_data = {
"comment_id": comment_id,
"text": comment_row[1],
"create_time": comment_row[2],
"likes_count": comment_row[3],
"rewards_count": comment_row[4],
"sticky": bool(comment_row[5]),
"parent_comment_id": comment_row[6],
"replies_count": comment_row[7],
"owner": {
"user_id": comment_row[8],
"name": comment_row[9],
"alias": comment_row[10],
"avatar_url": comment_row[11],
"location": comment_row[12],
"description": comment_row[13]
}
}
# 添加回复人信息(如果存在)
if comment_row[14]: # repliee_user_id
comment_data["repliee"] = {
"user_id": comment_row[14],
"name": comment_row[15],
"avatar_url": comment_row[16]
}
# 获取评论的图片
self.cursor.execute('''
SELECT
image_id, type, thumbnail_url, thumbnail_width, thumbnail_height,
large_url, large_width, large_height,
original_url, original_width, original_height, original_size
FROM images
WHERE comment_id = ?
ORDER BY image_id
''', (comment_id,))
images = []
for img_row in self.cursor.fetchall():
images.append({
"image_id": img_row[0],
"type": img_row[1],
"thumbnail": {
"url": img_row[2],
"width": img_row[3],
"height": img_row[4]
},
"large": {
"url": img_row[5],
"width": img_row[6],
"height": img_row[7]
},
"original": {
"url": img_row[8],
"width": img_row[9],
"height": img_row[10],
"size": img_row[11]
}
})
if images:
comment_data["images"] = images
show_comments.append(comment_data)
topic_detail["show_comments"] = show_comments
# 5. 获取点赞详情(表情)
self.cursor.execute('''
SELECT emoji_key, likes_count
FROM like_emojis
WHERE topic_id = ?
''', (topic_id,))
emojis = []
for emoji_row in self.cursor.fetchall():
emojis.append({
"emoji_key": emoji_row[0],
"likes_count": emoji_row[1]
})
topic_detail["likes_detail"] = {
"emojis": emojis
}
# 6. 获取问答数据(如果是问答类型话题)
if topic_detail["type"] == "q&a":
# 获取问题信息
self.cursor.execute('''
SELECT
q.text, q.expired, q.anonymous, q.owner_questions_count,
q.owner_join_time, q.owner_status, q.owner_location,
owner.user_id as owner_user_id, owner.name as owner_name,
owner.alias as owner_alias, owner.avatar_url as owner_avatar_url,
owner.location as owner_location_detail, owner.description as owner_description,
questionee.user_id as questionee_user_id, questionee.name as questionee_name,
questionee.alias as questionee_alias, questionee.avatar_url as questionee_avatar_url,
questionee.location as questionee_location, questionee.description as questionee_description
FROM questions q
LEFT JOIN users owner ON q.owner_user_id = owner.user_id
LEFT JOIN users questionee ON q.questionee_user_id = questionee.user_id
WHERE q.topic_id = ?
LIMIT 1
''', (topic_id,))
question_row = self.cursor.fetchone()
if question_row:
question_data = {
"text": question_row[0],
"expired": bool(question_row[1]),
"anonymous": bool(question_row[2]),
"owner_detail": {
"questions_count": question_row[3],
"estimated_join_time": question_row[4],
"status": question_row[5]
},
"owner_location": question_row[6]
}
# 添加被提问者信息
if question_row[12]: # questionee_user_id
question_data["questionee"] = {
"user_id": question_row[12],
"name": question_row[13],
"alias": question_row[14],
"avatar_url": question_row[15],
"location": question_row[16],
"description": question_row[17]
}
# 如果不是匿名且有提问者信息,添加提问者信息
if not question_data["anonymous"] and question_row[7]: # owner_user_id
question_data["owner"] = {
"user_id": question_row[7],
"name": question_row[8],
"alias": question_row[9],
"avatar_url": question_row[10],
"location": question_row[11],
"description": question_row[11]
}
topic_detail["question"] = question_data
# 获取回答信息
self.cursor.execute('''
SELECT
a.text,
u.user_id, u.name, u.alias, u.avatar_url, u.location, u.description
FROM answers a
LEFT JOIN users u ON a.owner_user_id = u.user_id
WHERE a.topic_id = ?
LIMIT 1
''', (topic_id,))
answer_row = self.cursor.fetchone()
if answer_row:
answer_data = {
"text": answer_row[0],
"owner": {
"user_id": answer_row[1],
"name": answer_row[2],
"alias": answer_row[3],
"avatar_url": answer_row[4],
"location": answer_row[5],
"description": answer_row[6]
}
}
topic_detail["answer"] = answer_data
return topic_detail
except Exception as e:
print(f"获取话题详情失败: {e}")
return None
def _import_tags(self, topic_id: int, topic_data: Dict[str, Any]):
"""从话题数据中提取并导入标签信息"""
import re
group_id = topic_data.get('group', {}).get('group_id')
if not group_id:
return
# 收集所有可能包含标签的文本内容
text_contents = []
# 从talk内容中提取
if 'talk' in topic_data and topic_data['talk'] and 'text' in topic_data['talk']:
text_contents.append(topic_data['talk']['text'])
# 从question内容中提取
if 'question' in topic_data and topic_data['question'] and 'text' in topic_data['question']:
text_contents.append(topic_data['question']['text'])
# 从answer内容中提取
if 'answer' in topic_data and topic_data['answer'] and 'text' in topic_data['answer']:
text_contents.append(topic_data['answer']['text'])
# 从评论中提取
if 'show_comments' in topic_data:
for comment in topic_data['show_comments']:
if 'text' in comment:
text_contents.append(comment['text'])
# 提取所有标签
all_tags = set()
for text in text_contents:
if text:
# 使用正则表达式提取标签 <e type="hashtag" hid="..." title="..." />
tag_pattern = r'<e\s+type="hashtag"\s+hid="([^"]+)"\s+title="([^"]+)"\s*/>'
matches = re.findall(tag_pattern, text)
for hid, encoded_title in matches:
try:
# 解码标签名称
import urllib.parse
tag_name = urllib.parse.unquote(encoded_title)
# 移除可能的#符号
tag_name = tag_name.strip('#')
if tag_name:
all_tags.add((tag_name, hid))
except Exception as e:
print(f"解码标签失败: {e}")
# 为每个标签创建或更新数据库记录
for tag_name, hid in all_tags:
tag_id = self._upsert_tag(group_id, tag_name, hid)
if tag_id:
self._link_topic_tag(topic_id, tag_id)
def _upsert_tag(self, group_id: int, tag_name: str, hid: str = None) -> Optional[int]:
"""插入或更新标签信息"""
try:
# 检查标签是否已存在
self.cursor.execute('''
SELECT tag_id FROM tags WHERE group_id = ? AND tag_name = ?
''', (group_id, tag_name))
result = self.cursor.fetchone()
if result:
tag_id = result[0]
# 更新hid(如果提供了新的hid)
if hid:
self.cursor.execute('''
UPDATE tags SET hid = ? WHERE tag_id = ?
''', (hid, tag_id))
return tag_id
else:
# 插入新标签
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT INTO tags (group_id, tag_name, hid, created_at)
VALUES (?, ?, ?, ?)
''', (group_id, tag_name, hid, current_time))
return self.cursor.lastrowid
except Exception as e:
print(f"插入标签失败: {e}")
return None
def _link_topic_tag(self, topic_id: int, tag_id: int):
"""关联话题和标签"""
try:
from datetime import datetime, timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
self.cursor.execute('''
INSERT OR IGNORE INTO topic_tags (topic_id, tag_id, created_at)
VALUES (?, ?, ?)
''', (topic_id, tag_id, current_time))
# 更新标签的话题计数
self.cursor.execute('''
UPDATE tags SET topic_count = (
SELECT COUNT(*) FROM topic_tags WHERE tag_id = ?
) WHERE tag_id = ?
''', (tag_id, tag_id))
except Exception as e:
print(f"关联话题标签失败: {e}")
def get_tags_by_group(self, group_id: int) -> List[Dict[str, Any]]:
"""获取指定群组的所有标签"""
try:
self.cursor.execute('''
SELECT tag_id, tag_name, hid, topic_count, created_at
FROM tags
WHERE group_id = ?
ORDER BY topic_count DESC, tag_name ASC
''', (group_id,))
tags = []
for row in self.cursor.fetchall():
tags.append({
'tag_id': row[0],
'tag_name': row[1],
'hid': row[2],
'topic_count': row[3],
'created_at': row[4]
})
return tags
except Exception as e:
print(f"获取标签列表失败: {e}")
return []
def get_topics_by_tag(self, tag_id: int, page: int = 1, per_page: int = 20) -> Dict[str, Any]:
"""根据标签获取话题列表"""
try:
offset = (page - 1) * per_page
# 获取话题列表 - 包含所有详细信息,与get_group_topics保持一致
self.cursor.execute('''
SELECT
t.topic_id, t.title, t.create_time, t.likes_count, t.comments_count,
t.reading_count, t.type, t.digested, t.sticky,
q.text as question_text,
a.text as answer_text,
tk.text as talk_text,
u.user_id, u.name, u.avatar_url
FROM topics t
INNER JOIN topic_tags tt ON t.topic_id = tt.topic_id
LEFT JOIN questions q ON t.topic_id = q.topic_id
LEFT JOIN answers a ON t.topic_id = a.topic_id
LEFT JOIN talks tk ON t.topic_id = tk.topic_id
LEFT JOIN users u ON tk.owner_user_id = u.user_id
WHERE tt.tag_id = ?
ORDER BY t.create_time DESC
LIMIT ? OFFSET ?
''', (tag_id, per_page, offset))
topics = []
for topic in self.cursor.fetchall():
topic_data = {
"topic_id": topic[0],
"title": topic[1],
"create_time": topic[2],
"likes_count": topic[3],
"comments_count": topic[4],
"reading_count": topic[5],
"type": topic[6],
"digested": bool(topic[7]) if topic[7] is not None else False,
"sticky": bool(topic[8]) if topic[8] is not None else False
}
# 添加内容文本
if topic[6] == 'q&a':
# 问答类型话题
topic_data['question_text'] = topic[9] if topic[9] else ''
topic_data['answer_text'] = topic[10] if topic[10] else ''
else:
# 其他类型话题(talk、article等)
topic_data['talk_text'] = topic[11] if topic[11] else ''
if topic[12]: # 有作者信息
topic_data['author'] = {
'user_id': topic[12],
'name': topic[13],
'avatar_url': topic[14]
}
topics.append(topic_data)
# 获取总数
self.cursor.execute('''
SELECT COUNT(*)
FROM topic_tags
WHERE tag_id = ?
''', (tag_id,))
total = self.cursor.fetchone()[0]
return {
'topics': topics,
'pagination': {
'page': page,
'per_page': per_page,
'total': total,
'pages': (total + per_page - 1) // per_page
}
}
except Exception as e:
print(f"根据标签获取话题失败: {e}")
return {'topics': [], 'pagination': {'page': page, 'per_page': per_page, 'total': 0, 'pages': 0}}
def close(self):
"""关闭数据库连接"""
if hasattr(self, 'conn') and self.conn:
self.conn.close()
def __del__(self):
"""析构函数,确保数据库连接被关闭"""
self.close()
|
2977094657/ZsxqCrawler
| 69,545
|
zsxq_interactive_crawler.py
|
#!/usr/bin/env python3
"""
知识星球交互式数据采集器
支持多种爬取模式,增强反检测机制
"""
import requests
import time
import random
import json
from typing import Dict, Any, Optional, List
from zsxq_database import ZSXQDatabase
from zsxq_file_downloader import ZSXQFileDownloader
from db_path_manager import get_db_path_manager
import os
try:
import tomllib
except ImportError:
try:
import tomli as tomllib
except ImportError:
print("⚠️ 需要安装tomli库来解析TOML配置文件")
print("💡 请运行: pip install tomli")
tomllib = None
class ZSXQInteractiveCrawler:
"""知识星球交互式数据采集器"""
def __init__(self, cookie: str, group_id: str, db_path: str = None, log_callback=None):
self.cookie = self.clean_cookie(cookie)
self.group_id = group_id
self.log_callback = log_callback # 日志回调函数
self.stop_flag = False # 停止标志
self.stop_check_func = None # 停止检查函数
# 使用路径管理器获取数据库路径
path_manager = get_db_path_manager()
if db_path is None:
db_path = path_manager.get_topics_db_path(group_id)
self.db_path = db_path # 保存数据库路径
self.db = ZSXQDatabase(db_path)
self.session = requests.Session()
# 文件下载器(懒加载)
self.file_downloader = None
# 基础API配置
self.base_url = "https://api.zsxq.com"
self.api_endpoint = f"/v2/groups/{group_id}/topics"
# 反检测配置
self.request_count = 0
self.page_count = 0 # 成功处理的页面数
self.last_request_time = 0
self.min_delay = 2.0 # 最小延迟
self.max_delay = 5.0 # 最大延迟
self.long_delay_interval = 15 # 每15个页面进行长延迟
self.debug_mode = False # 调试模式
self.timestamp_offset_ms = 1 # 时间戳减去的毫秒数
# 可配置的间隔参数(用于API调用时覆盖默认值)
self.use_custom_intervals = False
self.custom_min_delay = None
self.custom_max_delay = None
self.custom_long_delay_min = None
self.custom_long_delay_max = None
self.custom_pages_per_batch = None
self.log(f"🚀 知识星球交互式采集器初始化完成")
self.log(f"📊 目标群组: {group_id}")
self.log(f"💾 数据库: {db_path}")
# 显示当前数据库状态
self.show_database_status()
def set_custom_intervals(self, crawl_interval_min=None, crawl_interval_max=None,
long_sleep_interval_min=None, long_sleep_interval_max=None,
pages_per_batch=None):
"""设置自定义间隔参数"""
if any([crawl_interval_min, crawl_interval_max, long_sleep_interval_min,
long_sleep_interval_max, pages_per_batch]):
self.use_custom_intervals = True
self.custom_min_delay = crawl_interval_min
self.custom_max_delay = crawl_interval_max
self.custom_long_delay_min = long_sleep_interval_min
self.custom_long_delay_max = long_sleep_interval_max
self.custom_pages_per_batch = pages_per_batch
self.log(f"🔧 使用自定义间隔设置:")
if crawl_interval_min and crawl_interval_max:
self.log(f" 页面间隔: {crawl_interval_min}-{crawl_interval_max}秒")
if long_sleep_interval_min and long_sleep_interval_max:
self.log(f" 长休眠: {long_sleep_interval_min}-{long_sleep_interval_max}秒")
if pages_per_batch:
self.log(f" 批次大小: {pages_per_batch}页")
else:
self.use_custom_intervals = False
self.log(f"🔧 使用默认间隔设置")
def log(self, message: str):
"""统一的日志输出方法"""
print(message) # 仍然输出到控制台
if self.log_callback:
self.log_callback(message) # 同时推送到前端
def set_stop_flag(self):
"""设置停止标志"""
self.stop_flag = True
self.log("🛑 收到停止信号,任务将在下一个检查点停止")
def is_stopped(self):
"""检查是否被停止"""
# 首先检查本地停止标志
if self.stop_flag:
return True
# 然后检查外部停止检查函数
if self.stop_check_func and self.stop_check_func():
self.stop_flag = True # 同步本地标志
return True
return False
def _interruptible_sleep(self, duration: float):
"""可中断的睡眠,每0.1秒检查一次停止标志"""
start_time = time.time()
while time.time() - start_time < duration:
if self.is_stopped():
return
time.sleep(0.1) # 短暂睡眠,允许快速响应停止信号
def clean_cookie(self, cookie: str) -> str:
"""清理Cookie字符串,去除不合法字符
Args:
cookie (str): 原始Cookie字符串
Returns:
str: 清理后的Cookie字符串
"""
try:
# 如果是bytes类型,先解码
if isinstance(cookie, bytes):
cookie = cookie.decode('utf-8')
# 去除多余的空格和换行符
cookie = cookie.strip()
# 如果有多行,只取第一行
if '\n' in cookie:
cookie = cookie.split('\n')[0]
# 去除末尾的反斜杠
cookie = cookie.rstrip('\\')
# 去除可能的前缀b和引号
if cookie.startswith("b'") and cookie.endswith("'"):
cookie = cookie[2:-1]
elif cookie.startswith('b"') and cookie.endswith('"'):
cookie = cookie[2:-1]
elif cookie.startswith("'") and cookie.endswith("'"):
cookie = cookie[1:-1]
elif cookie.startswith('"') and cookie.endswith('"'):
cookie = cookie[1:-1]
# 处理转义字符
cookie = cookie.replace('\\n', '')
cookie = cookie.replace('\\"', '"')
cookie = cookie.replace("\\'", "'")
# 确保分号后有空格
cookie = '; '.join(part.strip() for part in cookie.split(';'))
return cookie
except Exception as e:
print(f"Cookie清理失败: {e}")
return cookie # 返回原始值
def get_file_downloader(self):
"""获取文件下载器(懒加载)"""
if self.file_downloader is None:
# 使用路径管理器获取文件数据库路径
path_manager = get_db_path_manager()
files_db_path = path_manager.get_files_db_path(self.group_id)
self.file_downloader = ZSXQFileDownloader(self.cookie, self.group_id, files_db_path)
return self.file_downloader
def show_database_status(self):
"""显示数据库当前状态"""
stats = self.db.get_database_stats()
total_topics = stats.get('topics', 0)
total_users = stats.get('users', 0)
total_comments = stats.get('comments', 0)
print(f"\n📊 当前数据库状态:")
print(f" 话题: {total_topics}, 用户: {total_users}, 评论: {total_comments}")
# 显示时间戳范围信息
if total_topics > 0:
timestamp_info = self.db.get_timestamp_range_info()
if timestamp_info['has_data']:
print(f" 时间范围: {timestamp_info['oldest_timestamp']} ~ {timestamp_info['newest_timestamp']}")
else:
print(f" ⚠️ 时间戳数据不完整")
def get_stealth_headers(self) -> Dict[str, str]:
"""获取隐蔽性更强的请求头"""
# 更多样化的User-Agent池
user_agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
]
# 基础头部
headers = {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7",
"Cache-Control": "no-cache",
"Cookie": self.cookie,
"Origin": "https://wx.zsxq.com",
"Pragma": "no-cache",
"Priority": "u=1, i",
"Referer": "https://wx.zsxq.com/",
"Sec-Ch-Ua": '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
"Sec-Ch-Ua-Mobile": "?0",
"Sec-Ch-Ua-Platform": '"Windows"',
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-site",
"User-Agent": random.choice(user_agents),
"X-Aduid": "a3be07cd6-dd67-3912-0093-862d844e7fe",
"X-Request-Id": f"dcc5cb6ab-1bc3-8273-cc26-{random.randint(100000000000, 999999999999)}",
"X-Signature": "733fd672ddf6d4e367730d9622cdd1e28a4b6203",
"X-Timestamp": str(int(time.time())),
"X-Version": "2.77.0"
}
# 随机添加可选头部
optional_headers = {
"X-Requested-With": "XMLHttpRequest",
"Sec-GPC": "1",
"Upgrade-Insecure-Requests": "1"
}
for key, value in optional_headers.items():
if random.random() > 0.4: # 60%概率添加
headers[key] = value
return headers
def smart_delay(self, is_historical: bool = False):
"""智能延迟机制 - 模拟人类行为(仅基础延迟)"""
self.request_count += 1
# 基础延迟时间
if self.use_custom_intervals and self.custom_min_delay and self.custom_max_delay:
# 使用自定义间隔
min_delay = self.custom_min_delay
max_delay = self.custom_max_delay
if is_historical:
delay = random.uniform(min_delay, max_delay + 1.0) # 历史爬取稍长
else:
delay = random.uniform(min_delay, max_delay)
self.log(f"⏱️ 页面间隔: {delay:.2f}秒 [自定义范围: {min_delay}-{max_delay}秒]")
else:
# 使用默认间隔
if is_historical:
delay = random.uniform(self.min_delay + 1.0, self.max_delay + 2.0) # 历史爬取稍长
else:
delay = random.uniform(self.min_delay, self.max_delay)
if self.debug_mode:
self.log(f" ⏱️ 延迟: {delay:.2f}秒 (请求#{self.request_count})")
# 可中断的延迟
self._interruptible_sleep(delay)
self.last_request_time = time.time()
def check_page_long_delay(self):
"""检查页面级长休眠:根据配置进行长休眠"""
self.page_count += 1
# 确定长休眠间隔
if self.use_custom_intervals and self.custom_pages_per_batch:
interval = self.custom_pages_per_batch
else:
interval = self.long_delay_interval
if self.page_count % interval == 0:
import datetime
# 确定长休眠时间
if self.use_custom_intervals and self.custom_long_delay_min and self.custom_long_delay_max:
long_delay = random.uniform(self.custom_long_delay_min, self.custom_long_delay_max)
self.log(f"🛌 长休眠开始: {long_delay:.1f}秒 ({long_delay/60:.1f}分钟) [自定义范围: {self.custom_long_delay_min/60:.1f}-{self.custom_long_delay_max/60:.1f}分钟]")
else:
long_delay = random.uniform(180, 300) # 3-5分钟长休眠
self.log(f"🛌 长休眠开始: {long_delay:.1f}秒 ({long_delay/60:.1f}分钟) [默认范围: 3-5分钟]")
start_time = datetime.datetime.now()
end_time = start_time + datetime.timedelta(seconds=long_delay)
self.log(f" 已完成 {self.page_count} 个页面,进入长休眠模式...")
self.log(f" ⏰ 开始时间: {start_time.strftime('%H:%M:%S')}")
self.log(f" 🕐 预计恢复: {end_time.strftime('%H:%M:%S')}")
# 可中断的长延迟
self._interruptible_sleep(long_delay)
actual_end_time = datetime.datetime.now()
self.log(f"😴 长休眠结束,继续爬取...")
self.log(f" 🕐 实际结束: {actual_end_time.strftime('%H:%M:%S')}")
# 调试信息
if self.debug_mode:
actual_duration = (actual_end_time - start_time).total_seconds()
print(f" 💤 长休眠完成: 预计{long_delay:.1f}秒,实际{actual_duration:.1f}秒 (页面#{self.page_count})")
def fetch_comments_safe(self, topic_id: int, begin_time: str = None, count: int = 30, max_retries: int = 10) -> Optional[Dict[str, Any]]:
"""安全获取话题评论,包含重试机制处理反爬"""
for retry in range(max_retries):
try:
# 构建评论API URL
url = f"https://api.zsxq.com/v2/topics/{topic_id}/comments"
params = {
'sort': 'asc',
'count': count,
'with_sticky': 'true'
}
if begin_time:
params['begin_time'] = begin_time
# 使用与主要API相同的隐蔽性请求头,包含完整的认证信息
headers = self.get_stealth_headers()
# 调试模式输出详细信息
if self.debug_mode and retry == 0: # 只在第一次尝试时输出
from urllib.parse import urlencode
full_url = f"{url}?{urlencode(params)}"
print(f"🔍 评论API调试信息:")
print(f" 🔗 完整URL: {full_url}")
print(f" 📊 参数: {params}")
print(f" 🔧 关键认证头:")
print(f" X-Signature: {headers.get('X-Signature', 'N/A')}")
print(f" X-Timestamp: {headers.get('X-Timestamp', 'N/A')}")
print(f" X-Request-Id: {headers.get('X-Request-Id', 'N/A')}")
print(f" X-Aduid: {headers.get('X-Aduid', 'N/A')}")
# 发送请求
response = self.session.get(url, params=params, headers=headers, timeout=30)
if response.status_code == 200:
data = response.json()
if data.get('succeeded'):
if retry > 0:
self.log(f"✅ 评论API重试成功 (第{retry+1}次尝试)")
return data
else:
error_code = data.get('code')
error_msg = data.get('error', '未知错误')
# 检查是否是反爬错误码1059
if error_code == 1059:
if retry < max_retries - 1:
# 智能等待时间策略:前几次短等待,后面逐渐增加
if retry < 3:
wait_time = 2 # 前3次等待2秒
elif retry < 6:
wait_time = 5 # 第4-6次等待5秒
else:
wait_time = 10 # 第7-10次等待10秒
self.log(f"⚠️ 遇到反爬机制 (错误码1059),等待{wait_time}秒后重试 (第{retry+1}/{max_retries}次)")
time.sleep(wait_time)
continue
else:
self.log(f"❌ 评论API重试{max_retries}次后仍失败: 错误码{error_code} - {error_msg}")
return None
else:
self.log(f"❌ 评论API返回失败: 错误码{error_code} - {error_msg}")
return None
else:
# 详细的错误日志
self.log(f"❌ 评论API请求失败: {response.status_code}")
self.log(f"🔗 请求URL: {response.url}")
self.log(f"📋 响应内容: {response.text[:500]}...")
return None
except Exception as e:
if retry < max_retries - 1:
# 使用与1059错误相同的等待策略
if retry < 3:
wait_time = 2
elif retry < 6:
wait_time = 5
else:
wait_time = 10
self.log(f"❌ 获取评论异常: {str(e)},等待{wait_time}秒后重试 (第{retry+1}/{max_retries}次)")
time.sleep(wait_time)
continue
else:
self.log(f"❌ 获取评论异常,重试{max_retries}次后仍失败: {str(e)}")
return None
return None
def fetch_all_comments(self, topic_id: int, comments_count: int) -> List[Dict[str, Any]]:
"""获取话题的所有评论(如果评论数量大于8)"""
if comments_count <= 8:
return [] # 不需要额外获取
self.log(f"📝 话题 {topic_id} 有 {comments_count} 条评论,开始获取完整评论列表...")
all_comments = []
begin_time = None
page = 1
while True:
# 检查停止标志
if self.is_stopped():
self.log("🛑 评论获取已停止")
break
self.log(f" 📄 获取第 {page} 页评论...")
# 获取当前页评论
data = self.fetch_comments_safe(topic_id, begin_time, count=30)
if not data:
self.log(f" ❌ 第 {page} 页获取失败,可能是权限问题,跳过此话题")
break
comments = data.get('resp_data', {}).get('comments', [])
if not comments:
self.log(f" 📭 第 {page} 页无评论,停止获取")
break
self.log(f" ✅ 第 {page} 页获取到 {len(comments)} 条评论")
# 处理评论数据,包括回复评论
for comment in comments:
all_comments.append(comment)
# 处理回复评论
if 'replied_comments' in comment and comment['replied_comments']:
for reply in comment['replied_comments']:
all_comments.append(reply)
# 如果返回的评论数量少于30,说明已经是最后一页
if len(comments) < 30:
self.log(f" 🏁 已获取完所有评论,共 {len(all_comments)} 条")
break
# 准备下一页的 begin_time(最后一条评论的时间 + 1毫秒)
last_comment = comments[-1]
last_time = last_comment.get('create_time')
if last_time:
begin_time = self._increment_time(last_time)
self.log(f" ⏭️ 下一页起始时间: {begin_time}")
else:
self.log(" ❌ 无法获取最后评论时间,停止获取")
break
page += 1
# 添加延迟避免请求过快
time.sleep(1)
return all_comments
def _increment_time(self, time_str: str) -> str:
"""将时间字符串增加1毫秒"""
try:
from datetime import datetime, timedelta
import re
# 解析时间字符串,例如: "2025-07-03T12:54:05.849+0800"
# 提取毫秒部分
match = re.match(r'(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\.(\d{3})(\+\d{4})', time_str)
if match:
base_time = match.group(1)
milliseconds = int(match.group(2))
timezone = match.group(3)
# 增加1毫秒
milliseconds += 1
if milliseconds >= 1000:
# 需要进位到秒
dt = datetime.strptime(base_time, '%Y-%m-%dT%H:%M:%S')
dt += timedelta(seconds=1)
base_time = dt.strftime('%Y-%m-%dT%H:%M:%S')
milliseconds = 0
return f"{base_time}.{milliseconds:03d}{timezone}"
else:
# 如果格式不匹配,直接返回原时间
return time_str
except Exception as e:
self.log(f"❌ 时间增量失败: {e}")
return time_str
def fetch_topics_safe(self, scope: str = "all", count: int = 20,
end_time: Optional[str] = None, is_historical: bool = False) -> Optional[Dict[str, Any]]:
"""安全的话题获取方法"""
# 智能延迟
self.smart_delay(is_historical)
url = f"{self.base_url}{self.api_endpoint}"
headers = self.get_stealth_headers()
# 构建参数
params = {
"scope": scope,
"count": str(count)
}
if end_time:
params["end_time"] = end_time
# 不添加额外参数,保持与官网请求一致
# random_params = {
# "_t": str(int(time.time() * 1000)),
# "v": "1.0",
# "_r": str(random.randint(1000, 9999))
# }
#
# for key, value in random_params.items():
# if random.random() > 0.3: # 70%概率添加
# params[key] = value
# 构造完整URL用于显示
from urllib.parse import urlencode
full_url = f"{url}?{urlencode(params)}"
self.log(f"🌐 安全请求 #{self.request_count}")
self.log(f" 🎯 参数: scope={scope}, count={count}")
if end_time:
self.log(f" 📅 时间: {end_time}")
self.log(f" 🔗 完整链接: {full_url}")
# 调试模式输出详细信息
if self.debug_mode:
print(f" 🔍 调试模式:")
print(f" 📍 基础URL: {url}")
print(f" 📊 所有参数: {params}")
print(f" 🔧 请求头: {json.dumps(headers, ensure_ascii=False, indent=4)}")
print(f" 🍪 Cookie长度: {len(self.cookie)}字符")
print(f" ⏰ 当前时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
# 在发起请求前检查停止标志
if self.is_stopped():
# 停止时不再打印日志,直接返回
return None
try:
response = self.session.get(
url,
headers=headers,
params=params,
timeout=10, # 降低超时时间以便快速响应停止信号
allow_redirects=True
)
self.log(f" 📊 状态: {response.status_code}, 大小: {len(response.content)}B")
# 请求完成后立即检查停止标志
if self.is_stopped():
return None
if response.status_code == 200:
try:
# 在处理响应前检查停止标志
if self.is_stopped():
self.log("🛑 响应处理前检测到停止信号")
return None
data = response.json()
if data.get('succeeded'):
topics = data.get('resp_data', {}).get('topics', [])
self.log(f" ✅ 获取成功: {len(topics)}个话题")
return data
else:
error_code = data.get('code')
error_message = data.get('error', data.get('message', '未知错误'))
# 检查是否是会员过期错误
if error_code == 14210:
print(f" ❌ 会员已过期: {error_message}")
print(f" 📋 完整响应: {json.dumps(data, ensure_ascii=False, indent=2)}")
# 设置过期标志,让调用方知道这是过期错误
return {"expired": True, "code": error_code, "message": error_message}
else:
print(f" ❌ API失败: {error_message}")
print(f" 📋 完整响应: {json.dumps(data, ensure_ascii=False, indent=2)}")
return None
except json.JSONDecodeError as e:
print(f" ❌ JSON解析失败: {e}")
print(f" 📄 响应内容: {response.text[:500]}...")
print(f" 📋 响应头: {dict(response.headers)}")
return None
else:
print(f" ❌ HTTP错误: {response.status_code}")
print(f" 📄 响应内容: {response.text}")
print(f" 📋 响应头: {dict(response.headers)}")
if response.status_code == 429:
print(" 🚨 触发频率限制,建议增加延迟时间")
elif response.status_code == 403:
print(" 🚨 访问被拒绝,可能需要更新Cookie或反检测策略")
elif response.status_code == 401:
print(" 🚨 认证失败,请检查Cookie是否过期")
return None
except requests.exceptions.Timeout as e:
print(f" ❌ 请求超时: {e}")
print(f" 🔧 建议: 增加超时时间或检查网络连接")
return None
except requests.exceptions.ConnectionError as e:
print(f" ❌ 连接错误: {e}")
print(f" 🔧 建议: 检查网络连接或DNS设置")
return None
except requests.exceptions.HTTPError as e:
print(f" ❌ HTTP协议错误: {e}")
return None
except requests.exceptions.RequestException as e:
print(f" ❌ 请求异常: {e}")
print(f" 🔧 异常类型: {type(e).__name__}")
return None
def store_batch_data(self, data: Dict[str, Any]) -> Dict[str, int]:
"""批量存储数据到数据库"""
# 在数据存储前检查停止标志
if self.is_stopped():
self.log("🛑 数据存储前检测到停止信号")
return {'new_topics': 0, 'updated_topics': 0, 'errors': 0}
if not data or not data.get('succeeded'):
return {'new_topics': 0, 'updated_topics': 0, 'errors': 0}
topics = data.get('resp_data', {}).get('topics', [])
if not topics:
return {'new_topics': 0, 'updated_topics': 0, 'errors': 0}
stats = {'new_topics': 0, 'updated_topics': 0, 'errors': 0}
for topic_data in topics:
# 在处理每个话题前检查停止标志
if self.is_stopped():
self.log("🛑 话题处理过程中检测到停止信号")
break
try:
topic_id = topic_data.get('topic_id')
# 检查是否已存在
self.db.cursor.execute('SELECT topic_id FROM topics WHERE topic_id = ?', (topic_id,))
exists = self.db.cursor.fetchone()
# 导入数据
self.db.import_topic_data(topic_data)
# 检查是否需要获取更多评论
comments_count = topic_data.get('comments_count', 0)
if comments_count > 8:
self.log(f"📝 话题 {topic_id} 有 {comments_count} 条评论,尝试获取完整评论列表...")
try:
additional_comments = self.fetch_all_comments(topic_id, comments_count)
if additional_comments:
self.db.import_additional_comments(topic_id, additional_comments)
self.log(f"✅ 成功获取并导入 {len(additional_comments)} 条额外评论")
else:
self.log(f"ℹ️ 话题 {topic_id} 无法获取更多评论,可能是权限限制")
except Exception as e:
self.log(f"⚠️ 话题 {topic_id} 获取评论时出错: {e}")
# 不影响话题本身的导入
if exists:
stats['updated_topics'] += 1
else:
stats['new_topics'] += 1
except Exception as e:
stats['errors'] += 1
print(f" ⚠️ 话题导入失败: {e}")
# 提交事务
self.db.conn.commit()
return stats
def crawl_latest(self, count: int = 20) -> Dict[str, int]:
"""爬取最新话题"""
print(f"\n🆕 爬取最新 {count} 个话题...")
data = self.fetch_topics_safe(scope="all", count=count)
if data:
stats = self.store_batch_data(data)
self.log(f"💾 存储结果: 新增{stats['new_topics']}, 更新{stats['updated_topics']}")
return stats
else:
print("❌ 获取失败")
return {'new_topics': 0, 'updated_topics': 0, 'errors': 1}
def crawl_historical(self, pages: int = 10, per_page: int = 20) -> Dict[str, int]:
"""爬取历史数据"""
print(f"\n📚 爬取历史数据: {pages}页 x {per_page}条/页")
total_stats = {'new_topics': 0, 'updated_topics': 0, 'errors': 0, 'pages': 0}
end_time = None
completed_pages = 0
max_retries_per_page = 10 # 每页最大重试次数
while completed_pages < pages:
# 检查停止标志
if self.is_stopped():
self.log("🛑 任务已停止")
break
current_page = completed_pages + 1
self.log(f"\n📄 页面 {current_page}/{pages}")
retry_count = 0
# 重试当前页直到成功或达到最大重试次数
while retry_count < max_retries_per_page:
# 在重试循环中也检查停止标志
if self.is_stopped():
return total_stats
if retry_count > 0:
self.log(f" 🔄 第{retry_count}次重试")
# 获取数据
if current_page == 1:
data = self.fetch_topics_safe(scope="all", count=per_page, is_historical=True)
else:
data = self.fetch_topics_safe(scope="all", count=per_page,
end_time=end_time, is_historical=True)
if data:
# 成功获取数据
topics = data.get('resp_data', {}).get('topics', [])
if not topics:
print(f" 📭 无更多数据,停止爬取")
return total_stats
# 存储数据
page_stats = self.store_batch_data(data)
self.log(f" 💾 页面存储: 新增{page_stats['new_topics']}, 更新{page_stats['updated_topics']}")
# 累计统计
total_stats['new_topics'] += page_stats['new_topics']
total_stats['updated_topics'] += page_stats['updated_topics']
total_stats['errors'] += page_stats['errors']
total_stats['pages'] += 1
completed_pages += 1
# 调试:显示所有话题的时间戳(只在调试模式下)
if self.debug_mode:
self.log(f" 🔍 调试信息:")
self.log(f" 📊 本页获取到 {len(topics)} 个话题")
for i, topic in enumerate(topics):
topic_time = topic.get('create_time', 'N/A')
topic_title = topic.get('title', '无标题')[:30]
self.log(f" {i+1:2d}. {topic_time} - {topic_title}")
# 准备下一页的时间戳
if topics:
original_time = topics[-1].get('create_time')
try:
from datetime import datetime, timedelta
dt = datetime.fromisoformat(original_time.replace('+0800', '+08:00'))
dt = dt - timedelta(milliseconds=self.timestamp_offset_ms)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
print(f" 📅 原始时间戳: {original_time}")
print(f" ⏭️ 下一页时间戳: {end_time} (减去{self.timestamp_offset_ms}毫秒)")
except Exception as e:
end_time = original_time
print(f" ⚠️ 时间戳调整失败: {e}")
print(f" ⏭️ 下一页时间戳: {end_time} (未调整)")
# 检查是否已爬完
if len(topics) < per_page:
print(f" 📭 已爬取完毕 (返回{len(topics)}条)")
return total_stats
# 成功,跳出重试循环
self.check_page_long_delay() # 页面成功处理后进行长休眠检查
break
else:
# 失败,增加重试计数和错误计数
retry_count += 1
total_stats['errors'] += 1
print(f" ❌ 页面 {current_page} 获取失败 (重试{retry_count}/{max_retries_per_page})")
# 调整时间戳用于重试
if end_time:
try:
from datetime import datetime, timedelta
dt = datetime.fromisoformat(end_time.replace('+0800', '+08:00'))
dt = dt - timedelta(milliseconds=self.timestamp_offset_ms)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
print(f" 🔄 调整时间戳: {end_time} (再次减去{self.timestamp_offset_ms}毫秒)")
except Exception as e:
print(f" ⚠️ 时间戳调整失败: {e}")
# 如果重试次数用完仍然失败
if retry_count >= max_retries_per_page:
print(f" 🚫 页面 {current_page} 达到最大重试次数,跳过此页")
# 如果有时间戳,尝试大幅度调整跳过问题区域
if end_time:
try:
from datetime import datetime, timedelta
dt = datetime.fromisoformat(end_time.replace('+0800', '+08:00'))
# 大幅度跳过,减去1小时
dt = dt - timedelta(hours=1)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
print(f" ⏰ 大幅度跳过时间段: {end_time} (减去1小时)")
except Exception as e:
print(f" ⚠️ 大幅度时间戳调整失败: {e}")
completed_pages += 1 # 跳过这一页
print(f"\n🏁 历史爬取完成:")
print(f" 📄 成功页数: {total_stats['pages']}")
print(f" ✅ 新增话题: {total_stats['new_topics']}")
print(f" 🔄 更新话题: {total_stats['updated_topics']}")
if total_stats['errors'] > 0:
print(f" ❌ 总错误数: {total_stats['errors']}")
return total_stats
def crawl_all_historical(self, per_page: int = 20, auto_confirm: bool = False) -> Dict[str, int]:
"""获取所有历史数据:无限爬取直到没有数据(使用增量爬取逻辑)"""
self.log(f"\n🌊 获取所有历史数据模式 (每页{per_page}条)")
self.log(f"⚠️ 警告:此模式将持续爬取直到没有数据,可能需要很长时间")
# 检查数据库状态,如果有数据则使用增量爬取逻辑
timestamp_info = self.db.get_timestamp_range_info()
start_end_time = None
if timestamp_info['has_data']:
oldest_timestamp = timestamp_info['oldest_timestamp']
total_existing = timestamp_info['total_topics']
self.log(f"📊 数据库现状:")
self.log(f" 现有话题数: {total_existing}")
self.log(f" 最老时间戳: {oldest_timestamp}")
self.log(f" 最新时间戳: {timestamp_info['newest_timestamp']}")
self.log(f"🎯 将从最老时间戳开始继续向历史爬取(增量模式)...")
# 准备增量爬取的起始时间戳
try:
from datetime import datetime, timedelta
dt = datetime.fromisoformat(oldest_timestamp.replace('+0800', '+08:00'))
dt = dt - timedelta(milliseconds=self.timestamp_offset_ms)
start_end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
print(f"🚀 增量爬取起始时间戳: {start_end_time}")
except Exception as e:
print(f"⚠️ 时间戳处理失败,使用原时间戳: {e}")
start_end_time = oldest_timestamp
else:
self.log(f"📊 数据库为空,将从最新数据开始爬取")
# 用户确认(Web API调用时自动确认)
if not auto_confirm:
confirm = input("确认开始无限爬取?(y/N): ").lower().strip()
if confirm != 'y':
self.log("❌ 用户取消操作")
return {'new_topics': 0, 'updated_topics': 0, 'errors': 0, 'pages': 0}
self.log(f"🚀 开始无限历史爬取...")
total_stats = {'new_topics': 0, 'updated_topics': 0, 'errors': 0, 'pages': 0}
end_time = start_end_time # 使用增量爬取的起始时间戳
current_page = 0
max_retries_per_page = 10
consecutive_empty_pages = 0 # 连续空页面计数
max_consecutive_empty = 3 # 最大连续空页面数
while True:
# 检查停止标志
if self.is_stopped():
self.log("🛑 任务已停止")
break
current_page += 1
self.log(f"\n📄 页面 {current_page}")
retry_count = 0
page_success = False
# 重试当前页直到成功或达到最大重试次数
while retry_count < max_retries_per_page:
# 在重试循环中也检查停止标志
if self.is_stopped():
return total_stats
if retry_count > 0:
self.log(f" 🔄 第{retry_count}次重试")
# 获取数据 - 根据是否有起始时间戳决定请求方式
if current_page == 1 and start_end_time is None:
# 数据库为空,从最新开始
data = self.fetch_topics_safe(scope="all", count=per_page, is_historical=True)
else:
# 有数据或后续页面,使用 end_time 参数
data = self.fetch_topics_safe(scope="all", count=per_page,
end_time=end_time, is_historical=True)
# 检查是否是会员过期错误
if data and data.get('expired'):
print(f" ❌ 会员已过期,停止爬取")
return data # 直接返回过期信息
if data:
# 成功获取数据
topics = data.get('resp_data', {}).get('topics', [])
if not topics:
consecutive_empty_pages += 1
print(f" 📭 第{consecutive_empty_pages}个空页面")
if consecutive_empty_pages >= max_consecutive_empty:
print(f" 🏁 连续{max_consecutive_empty}个空页面,所有历史数据爬取完成")
print(f"\n🎉 无限爬取完成总结:")
print(f" 📄 总页数: {total_stats['pages']}")
print(f" ✅ 新增话题: {total_stats['new_topics']}")
print(f" 🔄 更新话题: {total_stats['updated_topics']}")
if total_stats['errors'] > 0:
print(f" ❌ 总错误数: {total_stats['errors']}")
# 显示最终数据库状态
final_db_stats = self.db.get_timestamp_range_info()
if final_db_stats['has_data']:
print(f"\n📊 最终数据库状态:")
print(f" 话题总数: {final_db_stats['total_topics']}")
if timestamp_info['has_data']:
print(f" 新增话题: {final_db_stats['total_topics'] - timestamp_info['total_topics']}")
print(f" 时间范围: {final_db_stats['oldest_timestamp']} ~ {final_db_stats['newest_timestamp']}")
return total_stats
# 空页面也算成功,避免无限重试
page_success = True
break
else:
consecutive_empty_pages = 0 # 重置连续空页面计数
# 检查是否有新数据(避免重复爬取已有数据)
new_topics_count = 0
for topic in topics:
topic_id = topic.get('topic_id')
self.db.cursor.execute('SELECT topic_id FROM topics WHERE topic_id = ?', (topic_id,))
if not self.db.cursor.fetchone():
new_topics_count += 1
# 存储数据
page_stats = self.store_batch_data(data)
print(f" 💾 页面存储: 新增{page_stats['new_topics']}, 更新{page_stats['updated_topics']}")
# 累计统计
total_stats['new_topics'] += page_stats['new_topics']
total_stats['updated_topics'] += page_stats['updated_topics']
total_stats['errors'] += page_stats['errors']
total_stats['pages'] += 1
# 显示进度信息
print(f" 📊 获取到 {len(topics)} 个话题,其中 {new_topics_count} 个为新话题")
print(f" 📈 累计: 新增{total_stats['new_topics']}, 更新{total_stats['updated_topics']}, 页数{total_stats['pages']}")
# 调试:显示时间戳信息(简化版)
if topics:
first_time = topics[0].get('create_time', 'N/A')
last_time = topics[-1].get('create_time', 'N/A')
print(f" ⏰ 时间范围: {first_time} ~ {last_time}")
# 准备下一页的时间戳
if topics:
original_time = topics[-1].get('create_time')
try:
from datetime import datetime, timedelta
dt = datetime.fromisoformat(original_time.replace('+0800', '+08:00'))
dt = dt - timedelta(milliseconds=self.timestamp_offset_ms)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
except Exception as e:
end_time = original_time
print(f" ⚠️ 时间戳调整失败: {e}")
# 检查是否返回数据量小于预期(可能接近底部)
if len(topics) < per_page:
print(f" ⚠️ 返回数据量({len(topics)})小于预期({per_page}),可能接近历史底部")
# 如果没有新话题且数据量不足,可能已达历史底部
if new_topics_count == 0 and len(topics) < per_page:
print(f" 📭 无新话题且数据量不足,可能已达历史底部")
return total_stats
# 成功,跳出重试循环
page_success = True
break
else:
# 失败,增加重试计数和错误计数
retry_count += 1
total_stats['errors'] += 1
print(f" ❌ 页面 {current_page} 获取失败 (重试{retry_count}/{max_retries_per_page})")
# 调整时间戳用于重试
if end_time:
try:
from datetime import datetime, timedelta
dt = datetime.fromisoformat(end_time.replace('+0800', '+08:00'))
dt = dt - timedelta(milliseconds=self.timestamp_offset_ms)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
except Exception as e:
print(f" ⚠️ 时间戳调整失败: {e}")
# 如果重试次数用完仍然失败
if not page_success:
print(f" 🚫 页面 {current_page} 达到最大重试次数")
# 大幅度跳过问题区域
if end_time:
try:
from datetime import datetime, timedelta
dt = datetime.fromisoformat(end_time.replace('+0800', '+08:00'))
dt = dt - timedelta(hours=1)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
print(f" ⏰ 大幅度跳过时间段: {end_time} (减去1小时)")
except Exception as e:
print(f" ⚠️ 大幅度时间戳调整失败: {e}")
completed_pages += 1 # 跳过这一页
else:
# 页面成功处理后进行长休眠检查(基于页面数而非请求数)
self.check_page_long_delay()
# 每50页显示一次总体进度
if current_page % 50 == 0:
print(f"\n🎯 进度报告 (第{current_page}页):")
print(f" 📊 累计新增: {total_stats['new_topics']}")
print(f" 📊 累计更新: {total_stats['updated_topics']}")
print(f" 📊 成功页数: {total_stats['pages']}")
print(f" 📊 错误次数: {total_stats['errors']}")
# 显示当前数据库状态
current_db_stats = self.db.get_timestamp_range_info()
if current_db_stats['has_data']:
print(f" 📊 数据库状态: {current_db_stats['total_topics']}个话题")
print(f" 📊 时间范围: {current_db_stats['oldest_timestamp']} ~ {current_db_stats['newest_timestamp']}")
# 这里理论上不会到达,因为在循环内会return
return total_stats
def crawl_incremental(self, pages: int = 10, per_page: int = 20) -> Dict[str, int]:
"""增量爬取:基于数据库最老时间戳继续向历史爬取"""
print(f"\n📈 增量爬取模式: {pages}页 x {per_page}条/页")
# 获取数据库时间戳范围信息
timestamp_info = self.db.get_timestamp_range_info()
if not timestamp_info['has_data']:
print("❌ 数据库中没有话题数据,请先进行历史爬取")
return {'new_topics': 0, 'updated_topics': 0, 'errors': 1}
oldest_timestamp = timestamp_info['oldest_timestamp']
total_existing = timestamp_info['total_topics']
print(f"📊 数据库状态:")
print(f" 现有话题数: {total_existing}")
print(f" 最老时间戳: {oldest_timestamp}")
print(f" 最新时间戳: {timestamp_info['newest_timestamp']}")
print(f"🎯 将从最老时间戳开始继续向历史爬取...")
# 准备增量爬取的起始时间戳(在最老时间戳基础上减去偏移量)
try:
from datetime import datetime, timedelta
dt = datetime.fromisoformat(oldest_timestamp.replace('+0800', '+08:00'))
dt = dt - timedelta(milliseconds=self.timestamp_offset_ms)
start_end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
print(f"🚀 增量爬取起始时间戳: {start_end_time}")
except Exception as e:
print(f"⚠️ 时间戳处理失败,使用原时间戳: {e}")
start_end_time = oldest_timestamp
# 执行增量爬取
total_stats = {'new_topics': 0, 'updated_topics': 0, 'errors': 0, 'pages': 0}
end_time = start_end_time
completed_pages = 0
max_retries_per_page = 10
while completed_pages < pages:
current_page = completed_pages + 1
self.log(f"\n📄 增量页面 {current_page}/{pages}")
retry_count = 0
# 重试当前页直到成功或达到最大重试次数
while retry_count < max_retries_per_page:
if retry_count > 0:
print(f" 🔄 第{retry_count}次重试")
# 获取数据 - 总是使用 end_time 参数
data = self.fetch_topics_safe(scope="all", count=per_page,
end_time=end_time, is_historical=True)
# 检查是否是会员过期错误
if data and data.get('expired'):
print(f" ❌ 会员已过期,停止爬取")
return data # 直接返回过期信息
if data:
# 成功获取数据
topics = data.get('resp_data', {}).get('topics', [])
if not topics:
print(f" 📭 无更多历史数据,增量爬取完成")
return total_stats
# 检查是否有新数据(避免重复爬取已有数据)
new_topics_count = 0
for topic in topics:
topic_id = topic.get('topic_id')
self.db.cursor.execute('SELECT topic_id FROM topics WHERE topic_id = ?', (topic_id,))
if not self.db.cursor.fetchone():
new_topics_count += 1
print(f" 📊 获取到 {len(topics)} 个话题,其中 {new_topics_count} 个为新话题")
# 如果没有新话题且当前页话题数少于预期,可能已到达历史底部
if new_topics_count == 0 and len(topics) < per_page:
print(f" 📭 无新话题且数据量不足,可能已达历史底部")
return total_stats
# 存储数据
page_stats = self.store_batch_data(data)
print(f" 💾 页面存储: 新增{page_stats['new_topics']}, 更新{page_stats['updated_topics']}")
# 累计统计
total_stats['new_topics'] += page_stats['new_topics']
total_stats['updated_topics'] += page_stats['updated_topics']
total_stats['errors'] += page_stats['errors']
total_stats['pages'] += 1
completed_pages += 1
# 调试:显示话题时间戳信息
if self.debug_mode:
print(f" 🔍 调试信息:")
print(f" 📊 本页获取到 {len(topics)} 个话题")
for i, topic in enumerate(topics):
topic_time = topic.get('create_time', 'N/A')
topic_title = topic.get('title', '无标题')[:30]
print(f" {i+1:2d}. {topic_time} - {topic_title}")
# 准备下一页的时间戳
if topics:
original_time = topics[-1].get('create_time')
try:
dt = datetime.fromisoformat(original_time.replace('+0800', '+08:00'))
dt = dt - timedelta(milliseconds=self.timestamp_offset_ms)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
print(f" ⏭️ 下一页时间戳: {end_time}")
except Exception as e:
end_time = original_time
print(f" ⚠️ 时间戳调整失败: {e}")
# 成功,跳出重试循环
self.check_page_long_delay() # 页面成功处理后进行长休眠检查
break
else:
# 失败,增加重试计数和错误计数
retry_count += 1
total_stats['errors'] += 1
# 如果任务已停止,不再打印错误信息和调整时间戳
if self.is_stopped():
return total_stats
print(f" ❌ 页面 {current_page} 获取失败 (重试{retry_count}/{max_retries_per_page})")
# 调整时间戳用于重试
if end_time:
try:
dt = datetime.fromisoformat(end_time.replace('+0800', '+08:00'))
dt = dt - timedelta(milliseconds=self.timestamp_offset_ms)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
print(f" 🔄 调整时间戳: {end_time}")
except Exception as e:
print(f" ⚠️ 时间戳调整失败: {e}")
# 如果重试次数用完仍然失败
if retry_count >= max_retries_per_page:
# 如果任务已停止,不再打印信息
if self.is_stopped():
return total_stats
print(f" 🚫 页面 {current_page} 达到最大重试次数,跳过此页")
# 大幅度跳过问题区域
if end_time:
try:
dt = datetime.fromisoformat(end_time.replace('+0800', '+08:00'))
dt = dt - timedelta(hours=1)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
print(f" ⏰ 大幅度跳过时间段: {end_time} (减去1小时)")
except Exception as e:
print(f" ⚠️ 大幅度时间戳调整失败: {e}")
completed_pages += 1 # 跳过这一页
print(f"\n🏁 增量爬取完成:")
print(f" 📄 成功页数: {total_stats['pages']}")
print(f" ✅ 新增话题: {total_stats['new_topics']}")
print(f" 🔄 更新话题: {total_stats['updated_topics']}")
if total_stats['errors'] > 0:
print(f" ❌ 总错误数: {total_stats['errors']}")
# 显示更新后的数据库状态
updated_info = self.db.get_timestamp_range_info()
print(f"\n📊 更新后数据库状态:")
print(f" 话题总数: {updated_info['total_topics']} (+{updated_info['total_topics'] - total_existing})")
print(f" 时间范围: {updated_info['oldest_timestamp']} ~ {updated_info['newest_timestamp']}")
return total_stats
def crawl_latest_until_complete(self, per_page: int = 20) -> Dict[str, int]:
"""获取最新记录:智能增量更新,爬取到与数据库完全衔接为止"""
print(f"\n🔄 获取最新记录模式 (每页{per_page}条)")
print(f"💡 智能逻辑:检查最新话题,如有新内容则向后爬取直到与数据库完全衔接")
# 检查数据库状态
timestamp_info = self.db.get_timestamp_range_info()
if not timestamp_info['has_data']:
self.log("📊 数据库为空,将从最新开始爬取")
# 空库场景:直接从最新开始增量,直到与已存数据衔接或无更多数据
print(f"📊 数据库状态:")
print(f" 现有话题数: {timestamp_info['total_topics']}")
print(f" 最新时间戳: {timestamp_info['newest_timestamp']}")
total_stats = {'new_topics': 0, 'updated_topics': 0, 'errors': 0, 'pages': 0}
end_time = None # 从最新开始
current_page = 0
max_retries_per_page = 10
while True:
# 检查停止标志
if self.is_stopped():
break
current_page += 1
self.log(f"\n📄 检查页面 {current_page}")
retry_count = 0
page_success = False
# 重试当前页直到成功或达到最大重试次数
while retry_count < max_retries_per_page:
# 在重试循环中也检查停止标志
if self.is_stopped():
return total_stats
if retry_count > 0:
print(f" 🔄 第{retry_count}次重试")
# 获取数据
if current_page == 1:
# 第一页:获取最新话题
data = self.fetch_topics_safe(scope="all", count=per_page, is_historical=False)
else:
# 后续页面:使用 end_time 向历史爬取
data = self.fetch_topics_safe(scope="all", count=per_page,
end_time=end_time, is_historical=True)
if data:
# 成功获取数据
topics = data.get('resp_data', {}).get('topics', [])
if not topics:
print(f" 📭 无更多数据,获取完成")
break
# 检查这一页的话题是否在数据库中全部存在
existing_count = 0
new_topics_list = []
for topic in topics:
topic_id = topic.get('topic_id')
self.db.cursor.execute('SELECT topic_id FROM topics WHERE topic_id = ?', (topic_id,))
if self.db.cursor.fetchone():
existing_count += 1
else:
new_topics_list.append(topic)
print(f" 📊 页面分析: {len(topics)}个话题,{existing_count}个已存在,{len(new_topics_list)}个新话题")
# 判断是否需要停止
if existing_count == len(topics):
# 整页话题全部存在于数据库中
print(f" ✅ 整页话题全部存在于数据库,增量更新完成")
print(f"\n🎉 获取最新记录完成总结:")
print(f" 📄 检查页数: {total_stats['pages']}")
print(f" ✅ 新增话题: {total_stats['new_topics']}")
print(f" 🔄 更新话题: {total_stats['updated_topics']}")
if total_stats['errors'] > 0:
print(f" ❌ 总错误数: {total_stats['errors']}")
# 显示更新后的数据库状态
final_db_stats = self.db.get_timestamp_range_info()
if final_db_stats['has_data']:
print(f"\n📊 数据库最终状态:")
print(f" 话题总数: {final_db_stats['total_topics']} (+{final_db_stats['total_topics'] - timestamp_info['total_topics']})")
print(f" 时间范围: {final_db_stats['oldest_timestamp']} ~ {final_db_stats['newest_timestamp']}")
return total_stats
elif existing_count == 0:
# 整页话题都是新的,全部存储
page_stats = self.store_batch_data(data)
print(f" 💾 整页存储: 新增{page_stats['new_topics']}, 更新{page_stats['updated_topics']}")
else:
# 部分话题是新的,只存储新话题
print(f" 💾 部分存储: 只处理{len(new_topics_list)}个新话题")
new_topics_count = 0
updated_topics_count = 0
for new_topic in new_topics_list:
try:
topic_id = new_topic.get('topic_id')
# 检查是否已存在(双重检查)
self.db.cursor.execute('SELECT topic_id FROM topics WHERE topic_id = ?', (topic_id,))
exists = self.db.cursor.fetchone()
# 导入数据
self.db.import_topic_data(new_topic)
if exists:
updated_topics_count += 1
else:
new_topics_count += 1
except Exception as e:
print(f" ⚠️ 话题导入失败: {e}")
# 提交事务
self.db.conn.commit()
print(f" 💾 新话题存储: 新增{new_topics_count}, 更新{updated_topics_count}")
# 更新统计
total_stats['new_topics'] += new_topics_count
total_stats['updated_topics'] += updated_topics_count
# 累计统计(如果是整页存储)
if existing_count == 0:
total_stats['new_topics'] += page_stats['new_topics']
total_stats['updated_topics'] += page_stats['updated_topics']
total_stats['errors'] += page_stats['errors']
total_stats['pages'] += 1
# 显示当前进度
print(f" 📈 累计: 新增{total_stats['new_topics']}, 更新{total_stats['updated_topics']}, 页数{total_stats['pages']}")
# 显示时间戳信息
if topics:
first_time = topics[0].get('create_time', 'N/A')
last_time = topics[-1].get('create_time', 'N/A')
print(f" ⏰ 时间范围: {first_time} ~ {last_time}")
# 准备下一页的时间戳
if topics:
original_time = topics[-1].get('create_time')
try:
from datetime import datetime, timedelta
dt = datetime.fromisoformat(original_time.replace('+0800', '+08:00'))
dt = dt - timedelta(milliseconds=self.timestamp_offset_ms)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
except Exception as e:
end_time = original_time
print(f" ⚠️ 时间戳调整失败: {e}")
# 成功,跳出重试循环
page_success = True
break
else:
# 失败,增加重试计数和错误计数
retry_count += 1
total_stats['errors'] += 1
# 如果任务已停止,不再打印错误信息和调整时间戳
if self.is_stopped():
return total_stats
print(f" ❌ 页面 {current_page} 获取失败 (重试{retry_count}/{max_retries_per_page})")
# 调整时间戳用于重试
if end_time:
try:
from datetime import datetime, timedelta
dt = datetime.fromisoformat(end_time.replace('+0800', '+08:00'))
dt = dt - timedelta(milliseconds=self.timestamp_offset_ms)
end_time = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + '+0800'
except Exception as e:
print(f" ⚠️ 时间戳调整失败: {e}")
# 如果重试次数用完仍然失败
if not page_success:
# 如果任务已停止,不再打印信息
if self.is_stopped():
break
print(f" 🚫 页面 {current_page} 达到最大重试次数,停止获取")
break
else:
# 页面成功处理后进行长休眠检查(基于页面数而非请求数)
self.check_page_long_delay()
return total_stats
def show_menu(self):
"""显示交互菜单"""
print(f"\n{'='*60}")
print("🕷️ 知识星球交互式数据采集器")
print("="*60)
print("📝 话题采集功能:")
print("1. 获取所有历史数据 (无限爬取) - 适合:全量归档,从最老数据无限挖掘")
print("2. 增量爬取历史 (基于数据库最老时间戳) - 适合:精确补充历史,有目标的回填")
print("3. 获取最新记录 (智能增量更新) - 适合:日常维护,自动检测并只爬新内容")
print("")
print("📥 文件下载功能:")
print("4. 增量收集文件列表 - 适合:从数据库最老时间戳继续收集更早文件")
print("5. 查看文件数据库统计 - 适合:查看收集的文件信息和下载状态")
print("6. 按下载次数下载文件 - 适合:自动收集热门文件并按下载次数排序下载")
print("7. 按时间顺序下载文件 - 适合:自动收集文件列表并按时间顺序下载")
print("8. 文件下载设置 - 适合:调整下载间隔和休眠参数")
print("")
print("⚙️ 系统功能:")
print("9. 查看话题数据库统计 - 适合:监控话题数据状态,了解当前数据范围")
print("10. 调整反检测设置 - 适合:优化爬取速度,应对不同网络环境")
print(f"11. 时间戳设置 (当前: 减去{self.timestamp_offset_ms}毫秒) - 适合:解决时间点冲突,精确控制分页")
print(f"12. 调试模式 (当前: {'开启' if self.debug_mode else '关闭'}) - 适合:排查问题,查看详细请求信息")
print("13. 退出程序")
print("="*60)
def adjust_stealth_settings(self):
"""调整反检测设置"""
print(f"\n🔧 当前反检测设置:")
print(f" 最小延迟: {self.min_delay}秒")
print(f" 最大延迟: {self.max_delay}秒")
print(f" 长延迟间隔: 每{self.long_delay_interval}个页面")
print(f" 长休眠时间: 3-5分钟 (180-300秒)")
print(f"💡 说明: 长休眠基于成功处理的页面数,而非请求数,更加合理稳定")
try:
new_min = float(input(f"新的最小延迟 (当前{self.min_delay}): ") or self.min_delay)
new_max = float(input(f"新的最大延迟 (当前{self.max_delay}): ") or self.max_delay)
new_interval = int(input(f"长延迟间隔 (当前每{self.long_delay_interval}页): ") or self.long_delay_interval)
self.min_delay = max(new_min, 1.0) # 最小1秒
self.max_delay = max(new_max, self.min_delay + 1.0)
self.long_delay_interval = max(new_interval, 5)
print(f"✅ 设置已更新")
print(f"💡 长休眠时间固定为3-5分钟,有助于更好地模拟人类行为")
print(f"🎯 长休眠触发:每成功处理{self.long_delay_interval}个页面进行一次长休眠")
except ValueError:
print("❌ 输入无效,保持原设置")
def adjust_timestamp_settings(self):
"""调整时间戳设置"""
print(f"\n⏰ 当前时间戳设置:")
print(f" 减去毫秒数: {self.timestamp_offset_ms}毫秒")
print(f"\n💡 说明:")
print(f" - 减去1毫秒: 标准设置,与官网一致")
print(f" - 减去2-3毫秒: 可能避开某些问题时间点")
print(f" - 减去5-10毫秒: 更大的容错范围")
try:
new_offset = int(input(f"新的毫秒偏移量 (当前{self.timestamp_offset_ms}): ") or self.timestamp_offset_ms)
if new_offset < 0:
print("❌ 毫秒偏移量不能为负数")
return
self.timestamp_offset_ms = new_offset
print(f"✅ 时间戳设置已更新: 减去{self.timestamp_offset_ms}毫秒")
except ValueError:
print("❌ 输入无效,保持原设置")
def run_interactive(self):
"""运行交互式界面"""
try:
while True:
self.show_menu()
choice = input("\n请选择 (1-13): ").strip()
if choice == "1":
per_page = int(input("每页数量 (默认20): ") or "20")
self.crawl_all_historical(per_page)
elif choice == "2":
pages = int(input("爬取页数 (默认10): ") or "10")
per_page = int(input("每页数量 (默认20): ") or "20")
self.crawl_incremental(pages, per_page)
elif choice == "3":
per_page = int(input("每页数量 (默认20): ") or "20")
self.crawl_latest_until_complete(per_page)
elif choice == "4":
# 增量收集文件列表
downloader = self.get_file_downloader()
downloader.collect_incremental_files()
elif choice == "5":
# 查看文件数据库统计
downloader = self.get_file_downloader()
downloader.show_database_stats()
elif choice == "6":
# 按下载次数下载文件 (集成收集和下载)
downloader = self.get_file_downloader()
# 检查数据库是否已有文件数据
stats = downloader.file_db.get_database_stats()
existing_files = stats.get('files', 0)
if existing_files > 0:
print(f"📊 数据库中已有 {existing_files} 个文件记录")
collect_confirm = input("是否重新收集文件列表? (y/n, 默认n直接下载): ").strip().lower()
if collect_confirm != 'y':
print("⚡ 直接使用现有数据进行下载...")
else:
print("🔄 按下载次数重新收集文件列表...")
downloader.collect_all_files_to_database()
else:
print("🔄 按下载次数收集热门文件列表...")
downloader.collect_all_files_to_database()
# 自动开始下载
print("\n🚀 自动开始下载文件...")
user_input = input("最大下载文件数 (默认无限,输入数字限制): ").strip()
if user_input and user_input.isdigit():
max_files = int(user_input)
else:
max_files = None
downloader.download_files_from_database(max_files=max_files, status_filter='pending')
elif choice == "7":
# 按时间顺序下载文件 (集成收集和下载)
downloader = self.get_file_downloader()
# 检查数据库是否已有文件数据
stats = downloader.file_db.get_database_stats()
existing_files = stats.get('files', 0)
if existing_files > 0:
print(f"📊 数据库中已有 {existing_files} 个文件记录")
collect_confirm = input("是否重新收集文件列表? (y/n, 默认n直接下载): ").strip().lower()
if collect_confirm != 'y':
print("⚡ 直接使用现有数据进行下载...")
else:
print("🔄 按时间排序重新收集文件列表...")
downloader.collect_files_by_time()
else:
print("🔄 按时间排序收集文件列表...")
downloader.collect_files_by_time()
# 自动开始下载
print("\n🚀 自动开始下载文件...")
user_input = input("最大下载文件数 (默认无限,输入数字限制): ").strip()
if user_input and user_input.isdigit():
max_files = int(user_input)
else:
max_files = None
downloader.download_files_from_database(max_files=max_files, status_filter='pending')
elif choice == "8":
# 文件下载设置
downloader = self.get_file_downloader()
downloader.adjust_settings()
elif choice == "9":
# 查看话题数据库统计
self.show_database_status()
stats = self.db.get_database_stats()
print("\n📊 详细统计:")
for table, count in stats.items():
print(f" {table}: {count}")
elif choice == "10":
self.adjust_stealth_settings()
elif choice == "11":
self.adjust_timestamp_settings()
elif choice == "12":
self.debug_mode = not self.debug_mode
status = "开启" if self.debug_mode else "关闭"
print(f"🔍 调试模式已{status}")
if self.debug_mode:
print("⚠️ 调试模式会输出详细的请求信息,包括完整的失败响应")
elif choice == "13":
print("👋 退出程序")
break
else:
print("❌ 无效选择")
input("\n按回车键继续...")
except KeyboardInterrupt:
print("\n⏹️ 用户中断")
except Exception as e:
print(f"❌ 程序异常: {e}")
finally:
self.close()
def close(self):
"""关闭资源"""
self.db.close()
print("🔒 数据库连接已关闭")
def load_config():
"""加载TOML配置文件"""
if tomllib is None:
return None
# 尝试多个可能的配置文件路径
config_paths = [
"config.toml", # 当前目录
"../config.toml", # 上级目录(从backend目录运行时)
"../../config.toml" # 上上级目录
]
config_file = None
for path in config_paths:
if os.path.exists(path):
config_file = path
break
if config_file is None:
print("⚠️ 未找到config.toml配置文件,请先创建并配置")
print("💡 可以复制config.toml.example为config.toml并修改")
return None
try:
with open(config_file, 'rb') as f:
config = tomllib.load(f)
print("✅ 已从config.toml加载配置")
return config
except Exception as e:
print(f"❌ 加载配置文件出错: {e}")
return None
def main():
"""主函数"""
# 加载配置信息
config = load_config()
if not config:
return
# 从TOML配置中获取值
auth_config = config.get('auth', {})
db_config = config.get('database', {})
COOKIE = auth_config.get('cookie', 'your_cookie_here')
GROUP_ID = auth_config.get('group_id', 'your_group_id_here')
DB_PATH = db_config.get('path', 'zsxq_interactive.db')
# 检查配置是否已修改
if COOKIE == "your_cookie_here" or GROUP_ID == "your_group_id_here":
print("⚠️ 请先在config.toml中配置您的cookie和group_id")
return
# 创建交互式爬虫
crawler = ZSXQInteractiveCrawler(COOKIE, GROUP_ID, DB_PATH)
# 运行交互界面
crawler.run_interactive()
if __name__ == "__main__":
main()
|
281677160/openwrt-package
| 9,778
|
luci-app-qfirehose/htdocs/luci-static/resources/view/qfirehose.js
|
'use strict';
'require form';
'require fs';
'require ui';
'require view';
'require poll';
'require uci';
// 定义视图,继承自 view.Map
return view.extend({
// 加载配置和系统状态
load: function() {
// 返回一个Promise,用于加载USB串口设备列表
return Promise.all([
L.resolveDefault(fs.exec('/usr/bin/qfirehose'), {}),
L.resolveDefault(fs.list('/dev'), []),
L.resolveDefault(fs.list('/sys/bus/usb/devices'), []),
uci.load('qfirehose')
]);
},
// 处理用户操作(如点击烧写按钮)
handleAction: function(name, ev) {
if (name != 'flash') return;
// 创建一个包含倒计时的继续按钮
var continueBtn = E('button', {
'class': 'btn btn-primary',
'disabled': true
}, _('Continue') + ' (10)');
// 显示警告对话框
var modal = ui.showModal(_('Warning'), [
E('div', { class: 'alert-message warning' }, [
E('p', {}, _('Warning.')),
E('ul', {}, [
E('li', {}, _('Please ensure before proceeding:')),
E('ul', {}, [
E('li', {}, _('The firmware you selected is from official channels and compatible with your MODEM.')),
E('li', {}, _('The firmware version to be flashed should be higher than the version currently in use.'))
]),
E('li', {}, _('Use of software is completely on your own risk.')),
E('ul', {}, [
E('li', {}, _('Flashing wrong firmware or failed flash can brick your modem permanently.')),
E('li', {}, _('Avoid flashing, if device works without issues and updated firmware does not contain new necessary changes.')),
E('li', {}, _('Do not flash, if you are not willing to take this risk or do not know what you are doing.'))
]),
E('li', {}, _('After succesful flashing, you should use terminal to issue factory reset for modem settings with AT&F command.')),
E('li', {}, _('mPCIe users (mostly): If modem has completely disappeared after succesful flashing, reason might be that some firmware updates set default mode to USB3 which is unsupported by some mPCIe slots, in this case, you should connect it to USB port using mPCIe -> USB adapter, even most of cheap chinese modules can reveal device. After this you should issue a command to use USB2, which may vary between models, but on most Quectel modems is: AT+QUSBCFG="SS",0'))
])
]),
E('div', { class: 'right' }, [
E('button', {
'class': 'btn',
'click': ui.hideModal
}, _('Cancel')),
' ',
continueBtn
])
]);
// 开始10秒倒计时
var countdown = 10;
var self = this; // 保存this引用
var timer = setInterval(function() {
countdown--;
if (countdown > 0) {
continueBtn.textContent = _('Continue') + ' (' + countdown + ')';
} else {
clearInterval(timer);
continueBtn.textContent = _('Continue');
continueBtn.disabled = false;
continueBtn.onclick = function() {
ui.hideModal();
self.handleFlash(); // 使用保存的this引用
};
}
}, 1000);
modal;
},
// 烧写固件
handleFlash: function(ev) {
var form = this.map.lookupOption('firmware', 'config')[0].formvalue('config');
var eraseAll = this.map.lookupOption('erase_all', 'config')[0].formvalue('config');
var logDiv = document.getElementById('widget.cbid.qfirehose.config._log');
// 清空日志显示
if (logDiv) {
logDiv.textContent = '';
logDiv.textContent = '开始烧写固件...\n';
}
// 启动日志轮询
this.startLogPolling();
return fs.exec('/usr/sbin/qfirehose-start', [
'-f', '/tmp/qfirehoseupload/' + form.split('/').pop().replace(/\.zip$/i, ''),
eraseAll === '1' ? '-e' : ''
].filter(Boolean));
},
// 启动日志轮询
startLogPolling: function() {
if (!this.logPollHandle) {
var pollFunction = L.bind(function() {
var logDiv = document.getElementById('widget.cbid.qfirehose.config._log');
if (!logDiv) {
console.log('日志框不存在');
return;
}
fs.exec('cat', ['/tmp/qfirehose_log/current.log']).then(L.bind(function(res) {
if (res && res.stdout) {
console.log('获取到日志内容,长度:', res.stdout.length);
logDiv.textContent = res.stdout;
logDiv.scrollTop = logDiv.scrollHeight;
// 检查是否完成烧写
if (res.stdout.includes('Upgrade module successfully')) {
console.log('烧写过程结束,停止轮询');
this.stopLogPolling();
// 停止所有轮询
poll.stop();
// 显示完成消息
ui.addNotification(null, E('p', _('Firmware upgrade completed successfully.')));
}
} else {
console.log('没有日志内容');
}
}, this)).catch(function(err) {
console.log('读取日志出错:', err);
});
}, this);
// 存储轮询函数的引用
this.pollFunction = pollFunction;
// 启动轮询并存储句柄
this.logPollHandle = poll.add(pollFunction, 1);
}
},
// 停止日志轮询
stopLogPolling: function() {
if (this.logPollHandle && this.pollFunction) {
poll.remove(this.pollFunction);
this.logPollHandle = null;
this.pollFunction = null;
}
},
// 渲染界面
render: function(data) {
// 添加自定义样式
var styleEl = document.createElement('style');
styleEl.textContent = `
.cbi-value {
display: block;
margin-bottom: 5px;
}
.cbi-value-title {
width: 200px;
}
.cbi-value-field {
margin-left: 210px;
}
.cbi-value-field input[type="text"],
.cbi-value-field select {
width: 600px !important;
max-width: 600px !important;
}
.cbi-value-field textarea {
width: 800px !important;
max-width: 800px !important;
height: 400px !important;
font-family: monospace;
white-space: pre;
overflow: auto;
}
`;
document.head.appendChild(styleEl);
// 创建表单
var m, s, o;
var version = '';
if (data[0].stdout) {
let match = data[0].stdout.match(/Version: ([^\n]+)/);
if (match) version = match[1];
}
var ttyUSBDevices = data[1].filter(dev => dev.name.match(/^ttyUSB/)).map(dev => dev.name);
var usbDevices = data[2].filter(dev => dev.name.match(/^./)).map(dev => dev.name);
m = new form.Map('qfirehose');
this.map = m;
s = m.section(form.NamedSection, 'config', 'qfirehose', _('Qfirehose'),
_('Qfirehose is a command-line tool for flashing Qualcomm firmware on OpenWrt.'));
o = s.option(form.Value, 'version', _('Version'));
o.readonly = true;
o.default = version || '';
o.cfgvalue = function() { return version; };
o.write = function() {};
o.remove = function() {};
o.placeholder = _('Unknown');
o = s.option(form.FileUpload, 'firmware', _('Firmware File'),
_('Upgrade package directory path'));
o.root_directory = '/tmp/qfirehoseupload';
o.optional = false;
o = s.option(form.ListValue, 'port', _('Communication Port'),
_('Diagnose port, will auto-detect if not specified'));
o.optional = true;
ttyUSBDevices.forEach(dev => {
o.value('/dev/' + dev, '/dev/' + dev);
});
o = s.option(form.ListValue, 'device', _('USB Device'),
_('When multiple modules exist on the board, use -s specify which module you want to upgrade'));
o.optional = true;
usbDevices.forEach(dev => {
o.value('/sys/bus/usb/devices/' + dev, '/sys/bus/usb/devices/' + dev);
});
o.default = '';
// 隐藏设备类型选项
if (false) {
o = s.option(form.ListValue, 'device_type', _('Device Type'),
_('Device Type, default nand, support emmc/ufs'));
o.value('nand', 'nand');
o.value('emmc', 'emmc');
o.value('ufs', 'ufs');
o.default = 'nand';
}
o = s.option(form.Flag, 'skip_md5', _('Skip MD5 Check'),
_('Skip MD5 checksum verification'));
o.default = '0';
o = s.option(form.Flag, 'erase_all', _('Erase All Before Download'),
_('Will erase all data including calibration data, please be careful'));
o.default = '0';
o = s.option(form.Button, '_flash', _('Flash Firmware'));
o.inputstyle = 'apply';
o.onclick = ui.createHandlerFn(this, this.handleAction, 'flash');
o = s.option(form.TextValue, '_log', _('Log'));
o.readonly = true;
o.rows = 35;
o.wrap = 'off';
o.default = '';
o.value = '';
return m.render();
}
});
|
2977094657/ZsxqCrawler
| 6,227
|
db_path_manager.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from typing import Dict, Any
class DatabasePathManager:
"""数据库路径管理器 - 统一管理所有数据库文件的存储位置"""
def __init__(self, base_dir: str = "output/databases"):
# 确保使用项目根目录的绝对路径
if not os.path.isabs(base_dir):
# 查找项目根目录(包含config.toml的目录)
current_dir = os.path.abspath(os.getcwd())
project_root = current_dir
# 向上查找包含config.toml的目录
while project_root != os.path.dirname(project_root):
if os.path.exists(os.path.join(project_root, "config.toml")):
break
project_root = os.path.dirname(project_root)
self.base_dir = os.path.join(project_root, base_dir)
else:
self.base_dir = base_dir
self._ensure_base_dir()
def _ensure_base_dir(self):
"""确保基础目录存在"""
if not os.path.exists(self.base_dir):
os.makedirs(self.base_dir, exist_ok=True)
print(f"📁 创建数据库目录: {self.base_dir}")
def get_group_dir(self, group_id: str) -> str:
"""获取指定群组的数据库目录"""
group_dir = os.path.join(self.base_dir, str(group_id))
if not os.path.exists(group_dir):
os.makedirs(group_dir, exist_ok=True)
print(f"📁 创建群组目录: {group_dir}")
return group_dir
def get_group_data_dir(self, group_id: str):
"""获取指定群组的数据目录(返回Path对象)"""
from pathlib import Path
return Path(self.get_group_dir(group_id))
def get_topics_db_path(self, group_id: str) -> str:
"""获取话题数据库路径"""
group_dir = self.get_group_dir(group_id)
return os.path.join(group_dir, f"zsxq_topics_{group_id}.db")
def get_files_db_path(self, group_id: str) -> str:
"""获取文件数据库路径"""
group_dir = self.get_group_dir(group_id)
return os.path.join(group_dir, f"zsxq_files_{group_id}.db")
def get_config_db_path(self) -> str:
"""获取配置数据库路径(全局配置,不按群组分)"""
return os.path.join(self.base_dir, "zsxq_config.db")
def get_main_db_path(self, group_id: str) -> str:
"""获取主数据库路径(兼容旧版本)"""
return self.get_topics_db_path(group_id)
def list_group_databases(self, group_id: str) -> Dict[str, str]:
"""列出指定群组的所有数据库文件"""
group_dir = self.get_group_dir(group_id)
databases = {}
# 话题数据库
topics_db = self.get_topics_db_path(group_id)
if os.path.exists(topics_db):
databases['topics'] = topics_db
# 文件数据库
files_db = self.get_files_db_path(group_id)
if os.path.exists(files_db):
databases['files'] = files_db
return databases
def get_database_info(self, group_id: str) -> Dict[str, Any]:
"""获取数据库信息"""
databases = self.list_group_databases(group_id)
info = {
'group_id': group_id,
'group_dir': self.get_group_dir(group_id),
'databases': {}
}
for db_type, db_path in databases.items():
if os.path.exists(db_path):
stat = os.stat(db_path)
info['databases'][db_type] = {
'path': db_path,
'size': stat.st_size,
'modified': stat.st_mtime
}
return info
def migrate_old_databases(self, group_id: str, old_paths: Dict[str, str]) -> Dict[str, str]:
"""迁移旧的数据库文件到新的目录结构"""
migration_results = {}
for db_type, old_path in old_paths.items():
if not os.path.exists(old_path):
continue
if db_type == 'topics':
new_path = self.get_topics_db_path(group_id)
elif db_type == 'files':
new_path = self.get_files_db_path(group_id)
else:
continue
try:
# 如果新路径已存在,备份
if os.path.exists(new_path):
backup_path = f"{new_path}.backup"
os.rename(new_path, backup_path)
print(f"📦 备份现有数据库: {backup_path}")
# 移动文件
os.rename(old_path, new_path)
migration_results[db_type] = {
'old_path': old_path,
'new_path': new_path,
'status': 'success'
}
print(f"✅ 迁移数据库: {old_path} -> {new_path}")
except Exception as e:
migration_results[db_type] = {
'old_path': old_path,
'new_path': new_path,
'status': 'failed',
'error': str(e)
}
print(f"❌ 迁移失败: {old_path} -> {new_path}, 错误: {e}")
return migration_results
def list_all_groups(self) -> list:
"""列出所有存在的群组ID"""
groups = []
if not os.path.exists(self.base_dir):
return groups
for item in os.listdir(self.base_dir):
item_path = os.path.join(self.base_dir, item)
if os.path.isdir(item_path) and item.isdigit(): # 群组ID目录
# 检查是否有数据库文件
topics_db = self.get_topics_db_path(item)
if os.path.exists(topics_db):
groups.append({
'group_id': item,
'group_dir': item_path,
'topics_db': topics_db
})
return groups
def cleanup_empty_dirs(self):
"""清理空的群组目录"""
if not os.path.exists(self.base_dir):
return
for item in os.listdir(self.base_dir):
item_path = os.path.join(self.base_dir, item)
if os.path.isdir(item_path) and item.isdigit(): # 群组ID目录
if not os.listdir(item_path): # 空目录
os.rmdir(item_path)
print(f"🗑️ 删除空目录: {item_path}")
# 全局实例
db_path_manager = DatabasePathManager()
def get_db_path_manager() -> DatabasePathManager:
"""获取数据库路径管理器实例"""
return db_path_manager
|
2951121599/Bili-Insight
| 3,313
|
gpt_analyze.py
|
# -*- coding:utf-8 -*-
import logging
import os
from langchain import OpenAI
from langchain import PromptTemplate
from langchain.chains.summarize import load_summarize_chain
from langchain.docstore.document import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from openai.error import AuthenticationError
from get_markdown import get_markdown
def summary(text, api_key=None, method='summary'):
if method == 'markmap':
return get_markdown(text, api_key)
else:
return summary_text(text, api_key)
def summary_text(text, api_key=None):
"""
使用 GPT-3.5 模型分析总结文本
:param text: 文本
:param api_key: apikey from openai
:return: 分析结果
"""
try:
# 初始化文本分割器,指定每个块的大小为2000。
text_splitter = RecursiveCharacterTextSplitter(chunk_size=8000, chunk_overlap=0)
# 切分文本
texts = text_splitter.split_text(text)
# 使用 Document 类创建文档对象
docs = [Document(page_content=t) for t in texts]
# 我们定义一个模板字符串,用于提示 GPT-3.5 总结原始文本并生成汉语总结。
template_str = """我希望你是一名专业的视频内容编辑,帮我用总结视频的内容精华。
请你将视频字幕文本进行总结:(字幕中可能有错别字,如果你发现了错别字请改正)
{text}
SUMMARY IN CHINESE:"""
prompt_template = PromptTemplate(input_variables=["text"], template=template_str)
# 我们还定义了另一个模板字符串,用于提示 GPT-3.5 通过添加更多上下文来完善现有的汉语总结。
refine_template = (
"Your job is to produce a final summary\n"
"We have provided an existing summary up to a certain point: {existing_answer}\n"
"We have the opportunity to refine the existing summary"
"(only if needed) with some more context below.\n"
"{text}\n"
"Given the new context, refine the original summary in chinese"
"If the context isn't useful, return the original summary."
)
refine_prompt = PromptTemplate(input_variables=["existing_answer", "text"], template=refine_template)
# 使用 OpenAI API 密钥创建 OpenAI 对象
if api_key:
openai_api_key = api_key
else:
openai_api_key = os.getenv('OPENAI_API_KEY')
llm = OpenAI(temperature=0, model_name="gpt-3.5-turbo-16k", openai_api_key=openai_api_key)
# 加载总结和完善模型链,并向其提供刚才定义的两个模板字符串作为问题和细化问题的提示。
chain = load_summarize_chain(llm, chain_type="refine", return_intermediate_steps=True,
question_prompt=prompt_template, refine_prompt=refine_prompt, verbose=True)
# 将文档对象传递给模型链,并请求只返回输出文本。
review = chain({"input_documents": docs}, return_only_outputs=True)
# 返回 GPT-3.5 生成的文本摘要
return review["output_text"]
except AuthenticationError as e:
print("OpenAI API authentication error:", e.json_body)
return "请检查apikey"
except Exception as e:
logging.error("Summary error:", exc_info=True)
return "生成总结出错"
if __name__ == '__main__':
# 测试
print(summary_text("""
每个人都有变好的能力,但是能帮助你的人是你自己,也只有你自己。所有的困境都有出路,人的改变是在关系中发生的,心理治疗既需要自我觉醒,又需要和谐的人际关系建立,两者不可或缺。心理问题往往都是人际关系的问题,不仅是你和别人,还有你和自己的关系。让自己变得更好,才是解决问题的关键。当你不再和自己纠缠,所处的一切关系才会顺畅。作为咨询师,她是一个倾听者,倾听来访者内心的痛苦与不安。作为来访者,她是一个诉说者,诉说内心的难过与彷徨。
"""))
print(summary_text("""
用户是 B 站的视频观众,他们希望通过使用这个插件来更好地理解视频的内容。当用户鼠标至视频标题时,插件会自动展示内容总结,通过思维导图/词云等方式以可视化的形式呈现给用户,方便用户快速了解视频内容。
"""))
|
2977094657/ZsxqCrawler
| 7,972
|
image_cache_manager.py
|
"""
图片缓存管理器
负责下载、缓存和提供本地图片服务
"""
import os
import hashlib
import requests
import mimetypes
from pathlib import Path
from typing import Optional, Tuple
from urllib.parse import urlparse
import time
class ImageCacheManager:
"""图片缓存管理器"""
def __init__(self, cache_dir: str = "cache/images"):
"""
初始化图片缓存管理器
Args:
cache_dir: 缓存目录路径
"""
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(parents=True, exist_ok=True)
# 支持的图片格式
self.supported_formats = {
'image/jpeg': '.jpg',
'image/jpg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
'image/webp': '.webp',
'image/bmp': '.bmp'
}
# 默认请求头
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Referer': 'https://wx.zsxq.com/',
'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Cache-Control': 'no-cache',
'Pragma': 'no-cache'
}
def _get_cache_key(self, url: str) -> str:
"""
根据URL生成缓存键
Args:
url: 图片URL
Returns:
缓存键(文件名前缀)
"""
return hashlib.md5(url.encode('utf-8')).hexdigest()
def _get_file_extension(self, content_type: str, url: str) -> str:
"""
根据Content-Type和URL获取文件扩展名
Args:
content_type: HTTP响应的Content-Type
url: 图片URL
Returns:
文件扩展名
"""
# 优先使用Content-Type
if content_type in self.supported_formats:
return self.supported_formats[content_type]
# 从URL路径推断
parsed_url = urlparse(url)
path = parsed_url.path.lower()
for ext in ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp']:
if path.endswith(ext):
return ext if ext != '.jpeg' else '.jpg'
# 默认使用jpg
return '.jpg'
def _get_cache_path(self, url: str, content_type: str = None) -> Path:
"""
获取缓存文件路径
Args:
url: 图片URL
content_type: 内容类型
Returns:
缓存文件路径
"""
cache_key = self._get_cache_key(url)
# 如果已存在文件,直接返回
for ext in ['.jpg', '.png', '.gif', '.webp', '.bmp']:
existing_file = self.cache_dir / f"{cache_key}{ext}"
if existing_file.exists():
return existing_file
# 生成新文件路径
extension = self._get_file_extension(content_type or '', url)
return self.cache_dir / f"{cache_key}{extension}"
def is_cached(self, url: str) -> bool:
"""
检查图片是否已缓存
Args:
url: 图片URL
Returns:
是否已缓存
"""
if not url:
return False
cache_key = self._get_cache_key(url)
# 检查是否存在任何格式的缓存文件
for ext in ['.jpg', '.png', '.gif', '.webp', '.bmp']:
cache_file = self.cache_dir / f"{cache_key}{ext}"
if cache_file.exists():
return True
return False
def get_cached_path(self, url: str) -> Optional[Path]:
"""
获取已缓存图片的路径
Args:
url: 图片URL
Returns:
缓存文件路径,如果不存在则返回None
"""
if not self.is_cached(url):
return None
cache_key = self._get_cache_key(url)
# 查找存在的缓存文件
for ext in ['.jpg', '.png', '.gif', '.webp', '.bmp']:
cache_file = self.cache_dir / f"{cache_key}{ext}"
if cache_file.exists():
return cache_file
return None
def download_and_cache(self, url: str, timeout: int = 30) -> Tuple[bool, Optional[Path], Optional[str]]:
"""
下载并缓存图片
Args:
url: 图片URL
timeout: 请求超时时间
Returns:
(是否成功, 缓存文件路径, 错误信息)
"""
if not url:
return False, None, "URL为空"
try:
# 检查是否已缓存
if self.is_cached(url):
cached_path = self.get_cached_path(url)
return True, cached_path, None
# 下载图片
response = requests.get(url, headers=self.headers, timeout=timeout, stream=True)
response.raise_for_status()
# 检查内容类型
content_type = response.headers.get('content-type', '').lower()
if not any(fmt in content_type for fmt in self.supported_formats.keys()):
return False, None, f"不支持的图片格式: {content_type}"
# 获取缓存路径
cache_path = self._get_cache_path(url, content_type)
# 保存文件
with open(cache_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
return True, cache_path, None
except requests.exceptions.RequestException as e:
return False, None, f"下载失败: {str(e)}"
except Exception as e:
return False, None, f"缓存失败: {str(e)}"
def get_cache_info(self) -> dict:
"""
获取缓存统计信息
Returns:
缓存统计信息
"""
if not self.cache_dir.exists():
return {
"total_files": 0,
"total_size": 0,
"cache_dir": str(self.cache_dir)
}
total_files = 0
total_size = 0
for file_path in self.cache_dir.iterdir():
if file_path.is_file():
total_files += 1
total_size += file_path.stat().st_size
return {
"total_files": total_files,
"total_size": total_size,
"total_size_mb": round(total_size / (1024 * 1024), 2),
"cache_dir": str(self.cache_dir)
}
def clear_cache(self) -> Tuple[bool, str]:
"""
清空缓存
Returns:
(是否成功, 消息)
"""
try:
if not self.cache_dir.exists():
return True, "缓存目录不存在"
deleted_count = 0
for file_path in self.cache_dir.iterdir():
if file_path.is_file():
file_path.unlink()
deleted_count += 1
return True, f"已删除 {deleted_count} 个缓存文件"
except Exception as e:
return False, f"清空缓存失败: {str(e)}"
# 全局缓存管理器实例字典,按群组ID存储
_cache_managers = {}
def get_image_cache_manager(group_id: str = None) -> ImageCacheManager:
"""
获取图片缓存管理器实例
Args:
group_id: 群组ID,如果提供则使用群组专用缓存目录
Returns:
图片缓存管理器实例
"""
global _cache_managers
if group_id:
# 使用群组专用缓存目录
if group_id not in _cache_managers:
from db_path_manager import get_db_path_manager
path_manager = get_db_path_manager()
# 在群组数据库目录下创建images子目录
db_dir = path_manager.get_group_data_dir(group_id)
cache_dir = db_dir / "images"
_cache_managers[group_id] = ImageCacheManager(str(cache_dir))
return _cache_managers[group_id]
else:
# 使用默认全局缓存目录
if 'default' not in _cache_managers:
_cache_managers['default'] = ImageCacheManager()
return _cache_managers['default']
def clear_group_cache_manager(group_id: str):
"""清除指定群组的缓存管理器实例"""
global _cache_managers
if group_id in _cache_managers:
del _cache_managers[group_id]
|
2977094657/ZsxqCrawler
| 2,193
|
frontend/tailwind.config.js
|
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: ["class"],
content: [
'./pages/**/*.{ts,tsx}',
'./components/**/*.{ts,tsx}',
'./app/**/*.{ts,tsx}',
'./src/**/*.{ts,tsx}',
],
prefix: "",
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: "0" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
plugins: [
require("tailwindcss-animate"),
require("@tailwindcss/typography"),
],
}
|
2951121599/Bili-Insight
| 1,148
|
api_streaming.py
|
import json
import logging
import time
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import StreamingResponse
from gpt_analyze import summary_text
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def fake_streamer():
for i in range(20):
time.sleep(0.5)
yield json.dumps({"data": i})
@app.get("/")
async def main():
return StreamingResponse(fake_streamer(), media_type="text/plain")
@app.post("/")
async def create_item(request: Request):
json_post_raw = await request.json()
json_post = json.dumps(json_post_raw)
json_post_list = json.loads(json_post)
text = json_post_list.get('text')
api_key = json_post_list.get('apiKey')
logging.info('input %s', text)
return StreamingResponse(fake_streamer())
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=8000, workers=1)
|
2951121599/Bili-Insight
| 2,314
|
README.md
|
# Bili-Insight
<div align="center">
<img src="img/Bili-Insight.png" width=20%>
</div>
Bili Insight,借助GPT洞察B站视频内容[Chrome插件](https://chrome.google.com/webstore/detail/bili-insight%EF%BC%8C%E6%B4%9E%E5%AF%9Fb%E7%AB%99%E8%A7%86%E9%A2%91%E5%86%85%E5%AE%B9%E6%8F%92%E4%BB%B6/akodljjoaekbfjacabnihcbcbioidnfg?hl=zh-CN)。它可以让你不用点开视频,以可视化的方式更快地了解视频的基本信息和总结内容。
<p align="center">
🤗 <a href="https://yfor-bili-insight2.hf.space/" target="_blank"> Huggingface Space</a>
📺 <a href="https://b23.tv/P9ao5bc" target="_blank">介绍视频1</a>
📺 <a href="https://www.bilibili.com/video/BV1KV4y1S7Rw/" target="_blank">介绍视频2</a>
📑 <a href="https://emoumcwvfx.feishu.cn/docx/FUNYdH8ClolsBjxrEm3crZt0nTh" target="_blank">项目规划文档</a>
</p>
用户浏览B站时,把鼠标悬停至视频或标题上,插件会在视频旁弹出卡片。自动展示视频基本信息,并将总结内容通过词云&思维导图的方式以可视化的形式呈现,方便用户快速了解视频内容。
* up主视频的点赞、投币、收藏、分享数据
* up主视频的投稿时间、视频长度数据
* up主投稿视频的所在分区
* up主视频的内容总结。默认为视频简介。待请求完成后,会替换为视频内容总结
* up主视频字幕、标题、简介、tag生成的词云
## 演示示例


## 设计
```mermaid
sequenceDiagram
participant 用户
participant 浏览器
participant B站
用户->>+浏览器: 鼠标悬浮在B站视频上
浏览器->>+B站: 查询视频信息
B站->>+浏览器: 返回视频信息
浏览器->>用户: 展示视频信息
浏览器->>字幕网站: 查询字幕信息
字幕网站->>+浏览器: 返回字幕信息
浏览器->>+后端/HuggingFace(Langchain): 请求总结字幕
后端/HuggingFace(Langchain)->>+openai: ChatGPT接口
openai->>+后端/HuggingFace(Langchain): 总结字幕结果
后端/HuggingFace(Langchain)->>+浏览器: 总结字幕结果
浏览器->>用户: 展示视频信息(字幕总结)
```
### Refine链原理

### Huggingface部署

## 加入我们
<b>1. 添加个人联系方式</b>
<div align="center">
<img src="img/Wechat_Taylor.jpeg" width=20%>
<br/><br/><br/><br/><br/>
</div>
<b>2. 加入开发/体验/内测组</b>
<div align="center">
<img src="img/Wechat_Group.jpeg" width=30%>
</div>
## 参考资料
* [吕立青:BiliGPT](https://github.com/JimmyLv/BibiGPT)
* [插件:让你瞬间了解B站UP主](https://github.com/gaogaotiantian/biliscope)
* [Bilibili-Evolved](https://github.com/the1812/Bilibili-Evolved)
## LICENSE
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="知识共享许可协议" style="border-width:0" src="https://img.shields.io/badge/license-CC%20BY--NC--SA%204.0-lightgrey" /></a><br />本作品采用<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议</a>进行许可。
|
281677160/openwrt-package
| 4,188
|
luci-app-qfirehose/po/zh_Hans/qfirehose.po
|
# 中文翻译文件
msgid ""
msgstr "Content-Type: text/plain; charset=UTF-8\n"
# 应用标题和描述
msgid "Qfirehose"
msgstr "固件烧写"
msgid "Qfirehose is a command-line tool for flashing Qualcomm firmware on OpenWrt."
msgstr "Qfirehose是一个用于在OpenWrt上烧写高通固件的命令行工具。"
# 界面元素
msgid "Version"
msgstr "版本"
msgid "Firmware File"
msgstr "固件文件"
msgid "Upgrade package directory path"
msgstr "升级包目录路径"
msgid "Communication Port"
msgstr "通讯端口"
msgid "Diagnose port, will auto-detect if not specified"
msgstr "通讯端口,如果不指定将自动检测"
msgid "USB Device"
msgstr "USB设备"
msgid "When multiple modules exist on the board, use -s specify which module you want to upgrade"
msgstr "当主板上存在多个模块时,使用-s指定要升级的模块"
msgid "Device Type"
msgstr "设备类型"
msgid "Device Type, default nand, support emmc/ufs"
msgstr "设备类型,默认为NAND,支持eMMC/UFS"
msgid "NAND (Default)"
msgstr "NAND(默认)"
msgid "eMMC"
msgstr "eMMC"
msgid "UFS"
msgstr "UFS"
msgid "Skip MD5 Check"
msgstr "跳过MD5校验"
msgid "Skip MD5 checksum verification"
msgstr "跳过MD5校验和验证"
msgid "Catch USB Monitor Log"
msgstr "捕获USB监视器日志"
msgid "Save USB monitor log to file (requires debugfs and usbmon)"
msgstr "保存USB监视器日志到文件(需要debugfs和usbmon)"
msgid "Signed Firmware"
msgstr "签名固件"
msgid "For AG215S-GLR signed firmware packages"
msgstr "用于AG215S-GLR签名固件包"
msgid "Flash Firmware"
msgstr "开始烧写"
msgid "Log"
msgstr "日志"
msgid "Log file will be saved to /var/log/qfirehose/"
msgstr "日志文件将保存到 /var/log/qfirehose/ 目录"
# 警告和提示信息
msgid "Please select a firmware file first."
msgstr "请先选择固件文件。"
msgid "Firmware flashed successfully."
msgstr "固件烧写成功。"
msgid "Failed to flash firmware: "
msgstr "固件烧写失败:"
msgid "Error: "
msgstr "错误:"
msgid "Warning"
msgstr "警告"
msgid "Warning."
msgstr "警告。"
msgid "Please ensure before proceeding:"
msgstr "请在继续之前确保:"
msgid "The firmware you selected is from official channels and compatible with your MODEM."
msgstr "您选择的固件来自官方渠道并且与您的调制解调器兼容。"
msgid "The firmware version to be flashed should be higher than the version currently in use."
msgstr "要烧写的固件版本应高于当前使用的版本。"
msgid "Use of software is completely on your own risk."
msgstr "使用本软件的风险完全由您自己承担。"
msgid "Flashing wrong firmware or failed flash can brick your modem permanently."
msgstr "烧写错误的固件或烧写失败可能会永久损坏您的调制解调器。"
msgid "Avoid flashing, if device works without issues and updated firmware does not contain new necessary changes."
msgstr "如果设备运行正常且更新的固件不包含必要的新更改,请避免烧写。"
msgid "Do not flash, if you are not willing to take this risk or do not know what you are doing."
msgstr "如果您不愿意承担此风险或不知道自己在做什么,请不要进行烧写。"
msgid "After succesful flashing, you should use terminal to issue factory reset for modem settings with AT&F command."
msgstr "烧写成功后,您应该使用终端通过AT&F命令对调制解调器设置进行出厂重置。"
msgid "mPCIe users (mostly): If modem has completely disappeared after succesful flashing, reason might be that some firmware updates set default mode to USB3 which is unsupported by some mPCIe slots, in this case, you should connect it to USB port using mPCIe -> USB adapter, even most of cheap chinese modules can reveal device. After this you should issue a command to use USB2, which may vary between models, but on most Quectel modems is: AT+QUSBCFG=\"SS\",0"
msgstr "mPCIe用户(主要):如果在成功烧写后调制解调器完全消失,原因可能是某些固件更新将默认模式设置为某些mPCIe插槽不支持的USB3,在这种情况下,您应该使用mPCIe -> USB适配器将其连接到USB端口,即使是大多数便宜的中国模块也可以显示设备。之后,您应该发出使用USB2的命令,这可能因型号而异,但在大多数Quectel调制解调器上是:AT+QUSBCFG=\"SS\",0"
msgid "Cancel"
msgstr "取消"
msgid "Continue"
msgstr "继续"
# 操作提示和状态信息
msgid "Flashing Firmware"
msgstr "正在烧写固件"
msgid "Starting firmware flash process..."
msgstr "开始固件烧写过程..."
msgid "Firmware package: "
msgstr "固件包:"
msgid "Cleaning up working directory..."
msgstr "清理工作目录..."
msgid "Creating extraction directory..."
msgstr "创建解压目录..."
msgid "Extracting firmware package..."
msgstr "解压固件包..."
msgid "Starting Qfirehose with command:"
msgstr "执行Qfirehose命令:"
msgid "For detailed log, please check "
msgstr "详细日志请查看 "
msgid "Erase All Before Download"
msgstr "下载前擦除所有数据"
msgid "Will erase all data including calibration data, please be careful"
msgstr "将擦除所有数据(包括校准数据),请谨慎使用"
msgid "Flashing firmware, please wait..."
msgstr "正在烧写固件,请稍候..."
msgid "Log file will be saved to /var/log/qfirehose/"
msgstr "日志文件将保存到 /var/log/qfirehose/ 目录"
|
2951121599/Bili-Insight
| 5,468
|
get_markdown.py
|
# -*- coding:utf-8 -*-
import logging
import os
from langchain import OpenAI
from langchain import PromptTemplate
from langchain.chains.summarize import load_summarize_chain
from langchain.docstore.document import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from openai.error import AuthenticationError
def get_markdown(text, api_key=None):
"""
使用 GPT-3.5 模型分析总结文本
:param text: 文本
:param api_key: apikey from openai
:return: 分析结果
"""
try:
# 初始化文本分割器,指定每个块的大小为2000。
text_splitter = RecursiveCharacterTextSplitter(chunk_size=8000, chunk_overlap=0)
# 切分文本
texts = text_splitter.split_text(text)
# 使用 Document 类创建文档对象
docs = [Document(page_content=t) for t in texts]
# 我们定义一个模板字符串,用于提示 GPT-3.5 总结原始文本并生成汉语总结。
template_str = """我希望你是一名专业的视频内容编辑,。
请根据内容生成兼容脑图的Markdown格式,包含一级内容,和分级目录。一级目录不要超过6条,分级目录最多三个
(字幕中可能有错别字,如果你发现了错别字请改正),
记得不要重复句子,确保所有的句子都足够精简,清晰完整,祝你好运!
下面是内容:
{text}
"""
prompt_template = PromptTemplate(input_variables=["text"], template=template_str)
# 我们还定义了另一个模板字符串,用于提示 GPT-3.5 通过添加更多上下文来完善现有的汉语总结。
refine_template = (
"Your job is to produce a final summary\n"
"We have provided an existing summary up to a certain point: {existing_answer}\n"
"We have the opportunity to refine the existing summary"
"(only if needed) with some more context below.\n"
"{text}\n"
"Given the new context, refine the original summary in chinese"
"然后以无序列表的方式返回,不要超过5条。"
"If the context isn't useful, return the original summary."
)
refine_prompt = PromptTemplate(input_variables=["existing_answer", "text"], template=refine_template)
# 使用 OpenAI API 密钥创建 OpenAI 对象
if api_key:
openai_api_key = api_key
else:
openai_api_key = os.getenv('OPENAI_API_KEY')
llm = OpenAI(temperature=0, model_name="gpt-3.5-turbo-16k", openai_api_key=openai_api_key)
# 加载总结和完善模型链,并向其提供刚才定义的两个模板字符串作为问题和细化问题的提示。
chain = load_summarize_chain(llm, chain_type="refine", return_intermediate_steps=True,
question_prompt=prompt_template, refine_prompt=refine_prompt, verbose=True)
# 将文档对象传递给模型链,并请求只返回输出文本。
review = chain({"input_documents": docs}, return_only_outputs=True)
# 返回 GPT-3.5 生成的文本摘要
return review["output_text"]
except AuthenticationError as e:
print("OpenAI API authentication error:", e.json_body)
return "请检查apikey"
except Exception as e:
logging.error("生成出错:", exc_info=True)
return "生成出错"
if __name__ == '__main__':
# 测试
print(get_markdown("""
都说今年是5g的商用元年 但我一直都有点困惑 4g已经够快了 5g到底有什么用呢 为了探究这个问题 我报名oppo的5g星火计划 成功拿到了一台他们最新的oppo reno 5 g版 但是当下有5g天火的地方并不多 最好的体验机会就是5月十日就参与oppo的星火计划 开幕式 那里布置5g基站 但很巧的是 那天我期中考试 可我还是想体验一下5g的速度 往上一搜 发现有5g信号的地方有世园会金融街和北京邮电大学 这就很巧了 朋友们 我就在这儿上学呀 而这里解释一下 5g信号覆盖的是我们的稀土城校区 而我们大一大二都在30km外的沙河校区 所以我一下课就坐了校车来到了西土城 一进学校 这个高贵的符号便出现了 但是当我迫不及待的色素时 突然就懵了 这玩意儿难道比4g快很多吗 事实上 当我花了600兆流量在学校的各个地方测了十多次座 发现速度的确只有4g的水平 我试着下载了一些音乐和应用之类的东西 发现速度只有几兆每秒 在回去的路上 我不由得陷入了对人生和社会的大思考 所以我联系了学校信息化技术中心的老师 很巧的是那种联通正好在我们学校开个沟通会 老师就让我去了 更巧的是 刚好有个在联通的学长看过我的视频 他打天梯分后告诉我 我连不上5g是因为联通还在和学校进行测试 还未向用户开放 我实际上体验到的还是4g的速度啊 听到这里我心凉了半截 但是最巧的事情来了 测试预期在那周周五结束 顺利的话 周末就会开放 所以我又拿小车来到了西土城 而这次 i'm not a dummy you were summon human what i ta get it to you unsuperhuman innovative and i made a ral so that anything you can take a shit off for me in the i'm never stating more than never demonstrating how to give him all the fuking audience a feeling like a seventeen 这玩意是真的快 平均下载速率700mb ps左右 上传在80左右 几乎是设计速度的十倍 还记不记得上次我测了十多次速 才花了600兆流量 5g测一次就得1000了啊 我一开始的时候还想下个程序看看下载速率 结果下一些生活类应用时 根本来不及到那个有速率的页面就已经下完了 之后下一次更大的游戏时 发现速度保持在60兆每秒左右 用5g下歌的体验更优秀 一首十兆的歌进度条只有全空和全满两种状态 根本就没有在中间呆过 在各个平台看最高码率的视频也可 以随便出进度条可缓存来看 几乎没有区别 玩游戏的延迟也稳定在60ms以下 在体验上唯一和4g甚至和3g一脉相承的 就只有没有开会员的百度云了啊 别说5g这玩意 5g上6g也没辙 体验了一整天 5g我最大的感受有两点 第一就是这玩意用起来是真的爽 5g的普及会极大的优化当下的网络体验 比如有时候你引上来想玩游戏 然后给你蹦出来一个300兆的更新 这种感觉是很难受的 但是在5g的速度下 下载更新包几乎和解压塔一样快 第二就是云存储肯定 是趋势小王 最快的时候下载速度有90兆每秒 已经快赶上手机里sd卡的读取速度了 这么快的网速下 你把照片和视频保存在本地看 还是上传到云端 需要的时候下载下来再看 几乎没有区别 如果说有什么遗憾的话 就是联通的朋友跟我说 现在大多数5g部署都采用nsa 也就是非独立组网架构 将来才会升级到sa架构 呃不是通信专业的朋友 可能听不懂我在说什么啊 呃其实我也听不懂 但是在升级后速度会更快 实验会更低 终于在对着测试软件傻笑了一天后 天色逐渐暗了下 来我对这个速度的兴奋感也逐渐变得平淡 在回去的路上 我还是陷入了对人生和社会的大思考 想想我们在手机上要做哪些 对网速有要求的 是无非就是看视频 玩游戏 但这些需求在4g下也得到了满足啊 用5g体验当然会更好 但总有些杀鸡用牛刀的感觉啊 有这种想法的网友也不在少数 事实上 从拿到这个手机的第一天开始 我们每天都会在网上搜我 这有什么用回答 你总是预测vr ar全民自动驾驶 万物互联 但这些听起来总是太遥远 实现起来太复杂 所以这次我换了一个 搜索方式我搜了一下4g有什么用 但是把时间限定在了2012年到2013年 也就是4g即将商用的时间 站在未来看 前人对现在的预测真的是很有趣的一件事情 当时大多数人都在抱怨4g没有什么用 资费还那么贵 而我那时候也是 但是5年过后 大多数人已经没有那种流量有什么用的意识了 而当年对4g应用的预测的确可以看见一些未来的端倪 但都有些太缺乏想象力了 比如都知道4g可以看高清视频 但是当时都在说用手机看电影有多方便 没有人预测到短 视频的彻底爆发啊 比如都知道4g有利于普及移动支付 但当时的理想方式是一个手机绑信用卡加上nfc 没有人想到靠着网络加二维码这么简单粗暴的方式真的就干掉了现金 比如都知道4g的上传速度可以视频直播了 但当时的设想是应用于专业的新闻领域 没有想到这个全民皆可直播时代的来临 更不用说还有各种电商外卖打车平台的兴起 在短短的5年里 4g和它催生的服务深刻地改变了我们每一个人的生活 好像在5年前 你可能是觉得哦网速是快一点是吧 人对 未来的预测都跳脱不出当下技术和思维的限制 最典型的例子就是 如果你问一个50年前的人未来什么样子 他可能会告诉你 汽车会在天上跑 50年过去了 汽车没有上天 但是计算机和信息技术的诞生 对社会的改变绝对不会比会飞的汽车更小 50年是如此 5年说不定也是如此 5年前大多数文章都没有预测到4g栽培出的移动互联网 这个参天大树 那么5g这片更肥沃的土壤里会开出怎样的花 我相信还是会超过所有人的预料 最近联通的朋友还带我去参观了一个有 关5g的展 看到了不少有意思的应用 我现在最大的期望就是当我5年后再打开这个视频 会发现速度其实是5g最无聊的应用 ok我视频的全部内容啦 非常感谢你能看到这里啊 当然更要感谢中国联通的朋友 在北京邮电大学 如果你这个视频做的不错的话 求赞求收藏 全品是转发 就是哪个大大的关注 各位的支持就是做视频的最大动力啊 最近要高考了呃 就就祝各位高考的朋友都能考出一个理想的成绩 ok各位我们下期再见嗯"""))
|
2951121599/Bili-Insight
| 1,727
|
api.py
|
import json
import logging
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from gpt_analyze import summary_text
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/")
async def create_item(request: Request):
json_post_raw = await request.json()
json_post = json.dumps(json_post_raw)
json_post_list = json.loads(json_post)
text = json_post_list.get('text')
api_key = json_post_list.get('apiKey')
logging.info('input %s', text)
summary_text = summary_text(text, api_key)
# summary_text = "x"
logging.info('summary %s', summary_text)
logging.info('input length %s,summary length %s', len(text), len(summary_text))
response = {
"summary": summary_text
}
return response
@app.post("/run/predict")
async def predict(request: Request):
"""
mock the gradio rest api
"""
json_post_raw = await request.json()
json_post = json.dumps(json_post_raw)
json_post_list = json.loads(json_post)
data = json_post_list.get('data')
text = data[0]
api_key = data[1]
logging.info('input %s', text)
summary_text = summary_text(text, api_key)
# summary_text = "x"
logging.info('summary %s', summary_text)
logging.info('input length %s,summary length %s', len(text), len(summary_text))
response = {
"data": [summary_text]
}
return response
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=8000, workers=1)
|
2951121599/Bili-Insight
| 1,407
|
chrome-extension/bg_page.js
|
chrome.runtime.onMessage.addListener(
function (text, sender, onSuccess) {
let data = JSON.parse(text)
if (data.type === 'subtitleUrl') {
getSubtitleUrl(data, onSuccess)
}
if (data.type === 'summary') {
getSummary(data, onSuccess)
}
return true; // Will respond asynchronously.
}
);
function getSubtitleUrl(data, onSuccess) {
fetch(data.url)
.then(response => response.json())
.then(responseText => onSuccess(responseText))
}
function getSummary(data, onSuccess) {
chrome.storage.sync.get({
"enableWordCloud": true,
"apiKey": '',
minSize: 5
}, function (items) {
const url = 'https://yfor-bili-insight2.hf.space/run/predict'
// const url = 'http://127.0.0.1:7860/run/predict'
fetch(url, {
method: "POST", // or 'PUT'
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
"data": [
data.text,
items.apiKey ? items.apiKey : '',
data.method ? data.method : '',
]
}
)
})
.then(response => response.json())
.then(responseText => onSuccess({
"summary": responseText["data"][0]
}))
});
}
|
281677160/openwrt-package
| 2,710
|
luci-app-qfirehose/root/usr/sbin/qfirehose-start
|
#!/bin/sh
# 启用调试输出
set -x
# 清理旧的调试日志
rm -f /tmp/qfirehose_debug.log
# 记录当前用户和权限信息
echo "Current user: $(whoami)" > /tmp/qfirehose_debug.log
echo "Current groups: $(groups)" >> /tmp/qfirehose_debug.log
echo "Script permissions:" >> /tmp/qfirehose_debug.log
ls -l "$0" >> /tmp/qfirehose_debug.log
# 确保目录存在并有正确权限
mkdir -p /tmp/qfirehoseupload
chmod 777 /tmp/qfirehoseupload
mkdir -p /tmp/qfirehose_log
chmod 777 /tmp/qfirehose_log
# 生成带时间戳的日志文件名
timestamp=$(date +%Y%m%d_%H%M%S)
log_file="/tmp/qfirehose_log/qfirehose_${timestamp}.log"
pid_file="/tmp/qfirehose_log/pid"
# 创建符号链接指向最新的日志文件
ln -sf "$log_file" /tmp/qfirehose_log/current.log
# 获取参数
args="$*"
# 记录执行命令
echo "Command arguments: $args" >> "$log_file"
# 记录目录权限
echo "Directory permissions before:" >> "$log_file"
ls -la /tmp/qfirehoseupload >> "$log_file"
# 检查qfirehose是否可执行
if [ ! -x /usr/bin/qfirehose ]; then
echo "Error: qfirehose is not executable" >> "$log_file"
exit 1
fi
# 检查目录权限
if [ ! -w /tmp/qfirehose_log ]; then
echo "Error: log directory is not writable" >> "$log_file"
exit 1
fi
# 修复解压目录的权限
firmware_path=$(echo "$args" | grep -o '\-f [^ ]*' | cut -d' ' -f2)
if [ -n "$firmware_path" ] && [ -d "$firmware_path" ]; then
echo "Fixing permissions for firmware directory: $firmware_path" >> "$log_file"
chmod -R 777 "$firmware_path"
chown -R nobody:nogroup "$firmware_path"
fi
# 记录修改后的权限
echo "Directory permissions after:" >> "$log_file"
ls -la /tmp/qfirehoseupload >> "$log_file"
# 修改命令行参数中的日志路径
args=$(echo "$args" | sed 's|-l /var/log/qfirehose|-l /tmp/qfirehose_log|g')
# 从参数中提取固件路径
firmware_path=$(echo "$args" | grep -o '\-f [^ ]*' | cut -d' ' -f2)
if [ -z "$firmware_path" ]; then
echo "Error: firmware path not found in arguments" >> "$log_file"
exit 1
fi
# 提取文件名和目录名
filename=$(basename "$firmware_path")
dirname=$(dirname "$firmware_path")
# 清理旧文件,但保留上传的固件包
echo "Cleaning old files..." >> "$log_file"
find "$dirname" -type f ! -name "$filename" -delete 2>> "$log_file"
# 创建解压目录
echo "Creating extraction directory..." >> "$log_file"
unzip_dir="${firmware_path%.*}" # 移除.zip后缀
mkdir -p "$unzip_dir" 2>> "$log_file"
# 解压固件包
echo "Extracting firmware..." >> "$log_file"
unzip -o "$firmware_path" -d "$unzip_dir" 2>&1 | tee -a "$log_file"
# 更新参数中的固件路径为解压后的目录
args=$(echo "$args" | sed "s|-f [^ ]*|-f $unzip_dir|")
# 启动qfirehose并将其放入后台运行
echo "Starting qfirehose..." >> "$log_file"
(/usr/bin/qfirehose $args 2>&1 | tee -a "$log_file" & echo $!) > "$pid_file" 2>> "$log_file"
# 检查是否成功启动
if [ $? -eq 0 ]; then
echo "Successfully started qfirehose" >> "$log_file"
cat "$pid_file" | tee -a "$log_file"
else
echo "Failed to start qfirehose" >> "$log_file"
exit 1
fi
|
2951121599/Bili-Insight
| 2,076
|
test/bili-insight.js
|
biliInsightOptions = {
enableWordCloud: true,
minSize: 5
}
function fakeShow(event) {
let videoId = 1111
videoProfileCard.enable()
videoProfileCard.updateCursor(110, 110);
videoProfileCard.updateTarget(document.getRootNode());
videoProfileCard.updateVideoId(videoId);
let videoData = {
"pubdate": 1559822398,
"duration": 454,
"title": '【何同学】有多快?5G在日常使用中的真实体验',
"desc": '感谢龚哥从上海帮我办了两次电话卡,感谢我班团支书辅导我数电实验,感谢龚哥从上海帮我办了两次电话卡,感谢我班团支书辅导我数电实验',
"transcript": '都说今年是5G的商用元年,但我一直都有点困惑,但我一直都有点困惑,4G已经够快了',
"tid": 95,
"stat": {
"aid": 54737593,
"view": 30608261,
"danmaku": 226217,
"reply": 72217,
"favorite": 920545,
"coin": 2545941,
"share": 571844,
"now_rank": 0,
"his_rank": 1,
"like": 2465359,
"dislike": 0,
"evaluation": "",
"argue_msg": ""
}
}
cacheAndUpdate((data) => videoProfileCard.updateData(data), videoId, "info", {
data: {
"like": videoData["stat"]["like"],
"coin": videoData["stat"]["coin"],
"favorite": videoData["stat"]["favorite"],
"share": videoData["stat"]["share"],
"pubdate": videoData["pubdate"],
"duration": videoData["duration"],
"summary": videoData["desc"]
}
})
updateVideoData(videoId, (data) => videoProfileCard.updateData(data), videoData);
summary = `## Links
- <https://markmap.js.org/>
- [GitHub](https://github.com/gera2ld/markmap)
## Related Projects
- [coc-markmap](https://github.com/gera2ld/coc-markmap)
- [gatsby-remark-markmap](https://github.com/gera2ld/gatsby-remark-markmap)
## Features
- links
- **strong** ~~del~~ *italic* ==highlight==
- multiline
text`
cacheAndUpdate((data) => videoProfileCard.updateData(data), videoId, "markmap", {
data: summary
})
}
fakeShow()
document.getElementById('display').addEventListener('click', fakeShow);
|
2951121599/Bili-Insight
| 32,135
|
test/test.js
|
var a = {
"font_size": 0.4,
"font_color": "#FFFFFF",
"background_alpha": 0.5,
"background_color": "#9C27B0",
"Stroke": "none",
"type": "AIsubtitle",
"lang": "zh",
"version": "v1.4.0.4",
"body": [
{
"from": 0.2,
"to": 2.39,
"sid": 1,
"location": 2,
"content": "都说今年是5g的商用元年"
},
{
"from": 2.39,
"to": 4.25,
"sid": 2,
"location": 2,
"content": "但我一直都有点困惑"
},
{
"from": 4.25,
"to": 5.87,
"sid": 3,
"location": 2,
"content": "4g已经够快了"
},
{
"from": 5.87,
"to": 7.88,
"sid": 4,
"location": 2,
"content": "5g到底有什么用呢"
},
{
"from": 7.92,
"to": 9.42,
"sid": 5,
"location": 2,
"content": "为了探究这个问题"
},
{
"from": 9.42,
"to": 11.22,
"sid": 6,
"location": 2,
"content": "我报名oppo的5g星火计划"
},
{
"from": 11.22,
"to": 13.75,
"sid": 7,
"location": 2,
"content": "成功拿到了一台他们最新的oppo reno 5 g版"
},
{
"from": 13.75,
"to": 15.61,
"sid": 8,
"location": 2,
"content": "但是当下有5g天火的地方并不多"
},
{
"from": 15.61,
"to": 18.67,
"sid": 9,
"location": 2,
"content": "最好的体验机会就是5月十日就参与oppo的星火计划"
},
{
"from": 18.67,
"to": 19.21,
"sid": 10,
"location": 2,
"content": "开幕式"
},
{
"from": 19.21,
"to": 20.74,
"sid": 11,
"location": 2,
"content": "那里布置5g基站"
},
{
"from": 20.84,
"to": 22.1,
"sid": 12,
"location": 2,
"content": "但很巧的是"
},
{
"from": 22.1,
"to": 24.78,
"sid": 13,
"location": 2,
"content": "那天我期中考试"
},
{
"from": 26.02,
"to": 27.96,
"sid": 14,
"location": 2,
"content": "可我还是想体验一下5g的速度"
},
{
"from": 27.96,
"to": 28.71,
"sid": 15,
"location": 2,
"content": "往上一搜"
},
{
"from": 28.71,
"to": 34.04,
"sid": 16,
"location": 2,
"content": "发现有5g信号的地方有世园会金融街和北京邮电大学"
},
{
"from": 34.36,
"to": 35.26,
"sid": 17,
"location": 2,
"content": "这就很巧了"
},
{
"from": 35.26,
"to": 36.01,
"sid": 18,
"location": 2,
"content": "朋友们"
},
{
"from": 36.01,
"to": 40.08,
"sid": 19,
"location": 2,
"content": "我就在这儿上学呀"
},
{
"from": 40.88,
"to": 42.13,
"sid": 20,
"location": 2,
"content": "而这里解释一下"
},
{
"from": 42.13,
"to": 44.44,
"sid": 21,
"location": 2,
"content": "5g信号覆盖的是我们的稀土城校区"
},
{
"from": 44.44,
"to": 47.36,
"sid": 22,
"location": 2,
"content": "而我们大一大二都在30km外的沙河校区"
},
{
"from": 47.36,
"to": 50.36,
"sid": 23,
"location": 2,
"content": "所以我一下课就坐了校车来到了西土城"
},
{
"from": 50.36,
"to": 51.26,
"sid": 24,
"location": 2,
"content": "一进学校"
},
{
"from": 51.26,
"to": 53.48,
"sid": 25,
"location": 2,
"content": "这个高贵的符号便出现了"
},
{
"from": 53.62,
"to": 55.81,
"sid": 26,
"location": 2,
"content": "但是当我迫不及待的色素时"
},
{
"from": 55.81,
"to": 57.05,
"sid": 27,
"location": 2,
"content": "突然就懵了"
},
{
"from": 57.05,
"to": 60.14,
"sid": 28,
"location": 2,
"content": "这玩意儿难道比4g快很多吗"
},
{
"from": 60.14,
"to": 60.95,
"sid": 29,
"location": 2,
"content": "事实上"
},
{
"from": 60.95,
"to": 64.13,
"sid": 30,
"location": 2,
"content": "当我花了600兆流量在学校的各个地方测了十多次座"
},
{
"from": 64.13,
"to": 67.04,
"sid": 31,
"location": 2,
"content": "发现速度的确只有4g的水平"
},
{
"from": 67.04,
"to": 70.04,
"sid": 32,
"location": 2,
"content": "我试着下载了一些音乐和应用之类的东西"
},
{
"from": 70.04,
"to": 72.3,
"sid": 33,
"location": 2,
"content": "发现速度只有几兆每秒"
},
{
"from": 72.42,
"to": 73.71,
"sid": 34,
"location": 2,
"content": "在回去的路上"
},
{
"from": 73.71,
"to": 76.82,
"sid": 35,
"location": 2,
"content": "我不由得陷入了对人生和社会的大思考"
},
{
"from": 76.84,
"to": 79.69,
"sid": 36,
"location": 2,
"content": "所以我联系了学校信息化技术中心的老师"
},
{
"from": 79.69,
"to": 83.08,
"sid": 37,
"location": 2,
"content": "很巧的是那种联通正好在我们学校开个沟通会"
},
{
"from": 83.08,
"to": 84.6,
"sid": 38,
"location": 2,
"content": "老师就让我去了"
},
{
"from": 84.66,
"to": 85.74,
"sid": 39,
"location": 2,
"content": "更巧的是"
},
{
"from": 85.74,
"to": 88.39,
"sid": 40,
"location": 2,
"content": "刚好有个在联通的学长看过我的视频"
},
{
"from": 88.39,
"to": 90.01,
"sid": 41,
"location": 2,
"content": "他打天梯分后告诉我"
},
{
"from": 90.01,
"to": 93.22,
"sid": 42,
"location": 2,
"content": "我连不上5g是因为联通还在和学校进行测试"
},
{
"from": 93.22,
"to": 94.85,
"sid": 43,
"location": 2,
"content": "还未向用户开放"
},
{
"from": 94.85,
"to": 97.73,
"sid": 44,
"location": 2,
"content": "我实际上体验到的还是4g的速度啊"
},
{
"from": 97.73,
"to": 99.35,
"sid": 45,
"location": 2,
"content": "听到这里我心凉了半截"
},
{
"from": 99.35,
"to": 100.88,
"sid": 46,
"location": 2,
"content": "但是最巧的事情来了"
},
{
"from": 100.88,
"to": 103.42,
"sid": 47,
"location": 2,
"content": "测试预期在那周周五结束"
},
{
"from": 103.42,
"to": 104.32,
"sid": 48,
"location": 2,
"content": "顺利的话"
},
{
"from": 104.32,
"to": 106.03,
"sid": 49,
"location": 2,
"content": "周末就会开放"
},
{
"from": 106.03,
"to": 108.34,
"sid": 50,
"location": 2,
"content": "所以我又拿小车来到了西土城"
},
{
"from": 108.34,
"to": 109.46,
"sid": 51,
"location": 2,
"content": "而这次"
},
{
"from": 113.58,
"to": 114.84,
"sid": 52,
"location": 2,
"content": "i'm not a dummy"
},
{
"from": 114.84,
"to": 115.68,
"sid": 53,
"location": 2,
"content": "you were summon human"
},
{
"from": 115.68,
"to": 116.76,
"sid": 54,
"location": 2,
"content": "what i ta get it to you"
},
{
"from": 116.76,
"to": 117.3,
"sid": 55,
"location": 2,
"content": "unsuperhuman"
},
{
"from": 117.3,
"to": 117.66,
"sid": 56,
"location": 2,
"content": "innovative"
},
{
"from": 117.66,
"to": 118.32,
"sid": 57,
"location": 2,
"content": "and i made a ral"
},
{
"from": 118.32,
"to": 120.46,
"sid": 58,
"location": 2,
"content": "so that anything you can take a shit off for me in the"
},
{
"from": 120.46,
"to": 121.72,
"sid": 59,
"location": 2,
"content": "i'm never stating more than never demonstrating"
},
{
"from": 121.72,
"to": 122.86,
"sid": 60,
"location": 2,
"content": "how to give him all the fuking audience"
},
{
"from": 122.86,
"to": 123.82,
"sid": 61,
"location": 2,
"content": "a feeling like a seventeen"
},
{
"from": 128.54,
"to": 130.03,
"sid": 62,
"location": 2,
"content": "这玩意是真的快"
},
{
"from": 130.03,
"to": 132.96,
"sid": 63,
"location": 2,
"content": "平均下载速率700mb ps左右"
},
{
"from": 132.96,
"to": 134.74,
"sid": 64,
"location": 2,
"content": "上传在80左右"
},
{
"from": 134.74,
"to": 136.63,
"sid": 65,
"location": 2,
"content": "几乎是设计速度的十倍"
},
{
"from": 136.63,
"to": 138.82,
"sid": 66,
"location": 2,
"content": "还记不记得上次我测了十多次速"
},
{
"from": 138.82,
"to": 140.2,
"sid": 67,
"location": 2,
"content": "才花了600兆流量"
},
{
"from": 140.2,
"to": 143.92,
"sid": 68,
"location": 2,
"content": "5g测一次就得1000了啊"
},
{
"from": 143.92,
"to": 146.7,
"sid": 69,
"location": 2,
"content": "我一开始的时候还想下个程序看看下载速率"
},
{
"from": 146.7,
"to": 148.62,
"sid": 70,
"location": 2,
"content": "结果下一些生活类应用时"
},
{
"from": 148.62,
"to": 152.31,
"sid": 71,
"location": 2,
"content": "根本来不及到那个有速率的页面就已经下完了"
},
{
"from": 152.31,
"to": 153.99,
"sid": 72,
"location": 2,
"content": "之后下一次更大的游戏时"
},
{
"from": 153.99,
"to": 156.079,
"sid": 73,
"location": 2,
"content": "发现速度保持在60兆每秒左右"
},
{
"from": 156.079,
"to": 158.089,
"sid": 74,
"location": 2,
"content": "用5g下歌的体验更优秀"
},
{
"from": 158.089,
"to": 161.929,
"sid": 75,
"location": 2,
"content": "一首十兆的歌进度条只有全空和全满两种状态"
},
{
"from": 161.929,
"to": 163.81,
"sid": 76,
"location": 2,
"content": "根本就没有在中间呆过"
},
{
"from": 163.81,
"to": 166.09,
"sid": 77,
"location": 2,
"content": "在各个平台看最高码率的视频也可"
},
{
"from": 166.09,
"to": 168.34,
"sid": 78,
"location": 2,
"content": "以随便出进度条可缓存来看"
},
{
"from": 168.34,
"to": 169.74,
"sid": 79,
"location": 2,
"content": "几乎没有区别"
},
{
"from": 169.74,
"to": 172.68,
"sid": 80,
"location": 2,
"content": "玩游戏的延迟也稳定在60ms以下"
},
{
"from": 172.78,
"to": 176.59,
"sid": 81,
"location": 2,
"content": "在体验上唯一和4g甚至和3g一脉相承的"
},
{
"from": 176.59,
"to": 178.9,
"sid": 82,
"location": 2,
"content": "就只有没有开会员的百度云了啊"
},
{
"from": 178.9,
"to": 179.8,
"sid": 83,
"location": 2,
"content": "别说5g这玩意"
},
{
"from": 179.8,
"to": 181.46,
"sid": 84,
"location": 2,
"content": "5g上6g也没辙"
},
{
"from": 181.66,
"to": 182.56,
"sid": 85,
"location": 2,
"content": "体验了一整天"
},
{
"from": 182.56,
"to": 184.69,
"sid": 86,
"location": 2,
"content": "5g我最大的感受有两点"
},
{
"from": 184.69,
"to": 186.91,
"sid": 87,
"location": 2,
"content": "第一就是这玩意用起来是真的爽"
},
{
"from": 186.91,
"to": 190.38,
"sid": 88,
"location": 2,
"content": "5g的普及会极大的优化当下的网络体验"
},
{
"from": 190.48,
"to": 192.76,
"sid": 89,
"location": 2,
"content": "比如有时候你引上来想玩游戏"
},
{
"from": 192.76,
"to": 194.95,
"sid": 90,
"location": 2,
"content": "然后给你蹦出来一个300兆的更新"
},
{
"from": 194.95,
"to": 196.75,
"sid": 91,
"location": 2,
"content": "这种感觉是很难受的"
},
{
"from": 196.75,
"to": 198.19,
"sid": 92,
"location": 2,
"content": "但是在5g的速度下"
},
{
"from": 198.19,
"to": 201.5,
"sid": 93,
"location": 2,
"content": "下载更新包几乎和解压塔一样快"
},
{
"from": 201.5,
"to": 202.7,
"sid": 94,
"location": 2,
"content": "第二就是云存储肯定"
},
{
"from": 202.7,
"to": 203.84,
"sid": 95,
"location": 2,
"content": "是趋势小王"
},
{
"from": 203.84,
"to": 206.06,
"sid": 96,
"location": 2,
"content": "最快的时候下载速度有90兆每秒"
},
{
"from": 206.06,
"to": 208.69,
"sid": 97,
"location": 2,
"content": "已经快赶上手机里sd卡的读取速度了"
},
{
"from": 208.69,
"to": 209.95,
"sid": 98,
"location": 2,
"content": "这么快的网速下"
},
{
"from": 209.95,
"to": 212.35,
"sid": 99,
"location": 2,
"content": "你把照片和视频保存在本地看"
},
{
"from": 212.35,
"to": 213.7,
"sid": 100,
"location": 2,
"content": "还是上传到云端"
},
{
"from": 213.7,
"to": 215.43,
"sid": 101,
"location": 2,
"content": "需要的时候下载下来再看"
},
{
"from": 215.43,
"to": 217.2,
"sid": 102,
"location": 2,
"content": "几乎没有区别"
},
{
"from": 217.2,
"to": 219.03,
"sid": 103,
"location": 2,
"content": "如果说有什么遗憾的话"
},
{
"from": 219.03,
"to": 220.53,
"sid": 104,
"location": 2,
"content": "就是联通的朋友跟我说"
},
{
"from": 220.53,
"to": 222.98,
"sid": 105,
"location": 2,
"content": "现在大多数5g部署都采用nsa"
},
{
"from": 222.98,
"to": 224.87,
"sid": 106,
"location": 2,
"content": "也就是非独立组网架构"
},
{
"from": 224.87,
"to": 227.25,
"sid": 107,
"location": 2,
"content": "将来才会升级到sa架构"
},
{
"from": 227.25,
"to": 228.81,
"sid": 108,
"location": 2,
"content": "呃不是通信专业的朋友"
},
{
"from": 228.81,
"to": 230.13,
"sid": 109,
"location": 2,
"content": "可能听不懂我在说什么啊"
},
{
"from": 230.13,
"to": 231.7,
"sid": 110,
"location": 2,
"content": "呃其实我也听不懂"
},
{
"from": 231.7,
"to": 233.8,
"sid": 111,
"location": 2,
"content": "但是在升级后速度会更快"
},
{
"from": 233.8,
"to": 235.06,
"sid": 112,
"location": 2,
"content": "实验会更低"
},
{
"from": 235.06,
"to": 238.33,
"sid": 113,
"location": 2,
"content": "终于在对着测试软件傻笑了一天后"
},
{
"from": 238.33,
"to": 239.68,
"sid": 114,
"location": 2,
"content": "天色逐渐暗了下"
},
{
"from": 239.68,
"to": 244.02,
"sid": 115,
"location": 2,
"content": "来我对这个速度的兴奋感也逐渐变得平淡"
},
{
"from": 244.44,
"to": 245.82,
"sid": 116,
"location": 2,
"content": "在回去的路上"
},
{
"from": 245.82,
"to": 248.7,
"sid": 117,
"location": 2,
"content": "我还是陷入了对人生和社会的大思考"
},
{
"from": 248.7,
"to": 250.8,
"sid": 118,
"location": 2,
"content": "想想我们在手机上要做哪些"
},
{
"from": 250.8,
"to": 251.76,
"sid": 119,
"location": 2,
"content": "对网速有要求的"
},
{
"from": 251.76,
"to": 253.7,
"sid": 120,
"location": 2,
"content": "是无非就是看视频"
},
{
"from": 253.7,
"to": 254.76,
"sid": 121,
"location": 2,
"content": "玩游戏"
},
{
"from": 254.899,
"to": 258.229,
"sid": 122,
"location": 2,
"content": "但这些需求在4g下也得到了满足啊"
},
{
"from": 258.229,
"to": 260.029,
"sid": 123,
"location": 2,
"content": "用5g体验当然会更好"
},
{
"from": 260.029,
"to": 263.38,
"sid": 124,
"location": 2,
"content": "但总有些杀鸡用牛刀的感觉啊"
},
{
"from": 263.38,
"to": 265.8,
"sid": 125,
"location": 2,
"content": "有这种想法的网友也不在少数"
},
{
"from": 265.979,
"to": 266.909,
"sid": 126,
"location": 2,
"content": "事实上"
},
{
"from": 266.909,
"to": 269.099,
"sid": 127,
"location": 2,
"content": "从拿到这个手机的第一天开始"
},
{
"from": 269.099,
"to": 271.019,
"sid": 128,
"location": 2,
"content": "我们每天都会在网上搜我"
},
{
"from": 271.019,
"to": 272.699,
"sid": 129,
"location": 2,
"content": "这有什么用回答"
},
{
"from": 272.699,
"to": 275.789,
"sid": 130,
"location": 2,
"content": "你总是预测vr ar全民自动驾驶"
},
{
"from": 275.789,
"to": 276.839,
"sid": 131,
"location": 2,
"content": "万物互联"
},
{
"from": 276.839,
"to": 278.789,
"sid": 132,
"location": 2,
"content": "但这些听起来总是太遥远"
},
{
"from": 278.789,
"to": 280.4,
"sid": 133,
"location": 2,
"content": "实现起来太复杂"
},
{
"from": 280.599,
"to": 282.219,
"sid": 134,
"location": 2,
"content": "所以这次我换了一个"
},
{
"from": 282.219,
"to": 285.77,
"sid": 135,
"location": 2,
"content": "搜索方式我搜了一下4g有什么用"
},
{
"from": 285.77,
"to": 289.46,
"sid": 136,
"location": 2,
"content": "但是把时间限定在了2012年到2013年"
},
{
"from": 289.46,
"to": 292.1,
"sid": 137,
"location": 2,
"content": "也就是4g即将商用的时间"
},
{
"from": 292.1,
"to": 293.57,
"sid": 138,
"location": 2,
"content": "站在未来看"
},
{
"from": 293.57,
"to": 297.42,
"sid": 139,
"location": 2,
"content": "前人对现在的预测真的是很有趣的一件事情"
},
{
"from": 297.52,
"to": 300.37,
"sid": 140,
"location": 2,
"content": "当时大多数人都在抱怨4g没有什么用"
},
{
"from": 300.37,
"to": 301.63,
"sid": 141,
"location": 2,
"content": "资费还那么贵"
},
{
"from": 301.63,
"to": 303.19,
"sid": 142,
"location": 2,
"content": "而我那时候也是"
},
{
"from": 303.19,
"to": 304.6,
"sid": 143,
"location": 2,
"content": "但是5年过后"
},
{
"from": 304.6,
"to": 307.98,
"sid": 144,
"location": 2,
"content": "大多数人已经没有那种流量有什么用的意识了"
},
{
"from": 308.2,
"to": 312.85,
"sid": 145,
"location": 2,
"content": "而当年对4g应用的预测的确可以看见一些未来的端倪"
},
{
"from": 312.85,
"to": 315.36,
"sid": 146,
"location": 2,
"content": "但都有些太缺乏想象力了"
},
{
"from": 315.5,
"to": 318.17,
"sid": 147,
"location": 2,
"content": "比如都知道4g可以看高清视频"
},
{
"from": 318.17,
"to": 321.17,
"sid": 148,
"location": 2,
"content": "但是当时都在说用手机看电影有多方便"
},
{
"from": 321.17,
"to": 322.34,
"sid": 149,
"location": 2,
"content": "没有人预测到短"
},
{
"from": 322.34,
"to": 324.459,
"sid": 150,
"location": 2,
"content": "视频的彻底爆发啊"
},
{
"from": 324.459,
"to": 327.099,
"sid": 151,
"location": 2,
"content": "比如都知道4g有利于普及移动支付"
},
{
"from": 327.099,
"to": 331.2,
"sid": 152,
"location": 2,
"content": "但当时的理想方式是一个手机绑信用卡加上nfc"
},
{
"from": 331.36,
"to": 337.03,
"sid": 153,
"location": 2,
"content": "没有人想到靠着网络加二维码这么简单粗暴的方式真的就干掉了现金"
},
{
"from": 337.03,
"to": 340.52,
"sid": 154,
"location": 2,
"content": "比如都知道4g的上传速度可以视频直播了"
},
{
"from": 340.62,
"to": 343.92,
"sid": 155,
"location": 2,
"content": "但当时的设想是应用于专业的新闻领域"
},
{
"from": 343.92,
"to": 346.96,
"sid": 156,
"location": 2,
"content": "没有想到这个全民皆可直播时代的来临"
},
{
"from": 346.979,
"to": 350.7,
"sid": 157,
"location": 2,
"content": "更不用说还有各种电商外卖打车平台的兴起"
},
{
"from": 350.84,
"to": 352.58,
"sid": 158,
"location": 2,
"content": "在短短的5年里"
},
{
"from": 352.58,
"to": 357.6,
"sid": 159,
"location": 2,
"content": "4g和它催生的服务深刻地改变了我们每一个人的生活"
},
{
"from": 357.86,
"to": 359.21,
"sid": 160,
"location": 2,
"content": "好像在5年前"
},
{
"from": 359.21,
"to": 362.64,
"sid": 161,
"location": 2,
"content": "你可能是觉得哦网速是快一点是吧"
},
{
"from": 362.82,
"to": 363.42,
"sid": 162,
"location": 2,
"content": "人对"
},
{
"from": 363.42,
"to": 366.45,
"sid": 163,
"location": 2,
"content": "未来的预测都跳脱不出当下技术和思维的限制"
},
{
"from": 366.45,
"to": 368.19,
"sid": 164,
"location": 2,
"content": "最典型的例子就是"
},
{
"from": 368.19,
"to": 370.77,
"sid": 165,
"location": 2,
"content": "如果你问一个50年前的人未来什么样子"
},
{
"from": 370.77,
"to": 371.88,
"sid": 166,
"location": 2,
"content": "他可能会告诉你"
},
{
"from": 371.88,
"to": 373.26,
"sid": 167,
"location": 2,
"content": "汽车会在天上跑"
},
{
"from": 373.38,
"to": 374.67,
"sid": 168,
"location": 2,
"content": "50年过去了"
},
{
"from": 374.67,
"to": 375.93,
"sid": 169,
"location": 2,
"content": "汽车没有上天"
},
{
"from": 375.93,
"to": 378.24,
"sid": 170,
"location": 2,
"content": "但是计算机和信息技术的诞生"
},
{
"from": 378.24,
"to": 381.64,
"sid": 171,
"location": 2,
"content": "对社会的改变绝对不会比会飞的汽车更小"
},
{
"from": 381.92,
"to": 383.51,
"sid": 172,
"location": 2,
"content": "50年是如此"
},
{
"from": 383.51,
"to": 385.58,
"sid": 173,
"location": 2,
"content": "5年说不定也是如此"
},
{
"from": 385.58,
"to": 390.08,
"sid": 174,
"location": 2,
"content": "5年前大多数文章都没有预测到4g栽培出的移动互联网"
},
{
"from": 390.08,
"to": 391.52,
"sid": 175,
"location": 2,
"content": "这个参天大树"
},
{
"from": 391.659,
"to": 395.229,
"sid": 176,
"location": 2,
"content": "那么5g这片更肥沃的土壤里会开出怎样的花"
},
{
"from": 395.229,
"to": 398.58,
"sid": 177,
"location": 2,
"content": "我相信还是会超过所有人的预料"
},
{
"from": 398.84,
"to": 401.48,
"sid": 178,
"location": 2,
"content": "最近联通的朋友还带我去参观了一个有"
},
{
"from": 401.48,
"to": 402.44,
"sid": 179,
"location": 2,
"content": "关5g的展"
},
{
"from": 402.44,
"to": 404.92,
"sid": 180,
"location": 2,
"content": "看到了不少有意思的应用"
},
{
"from": 405.08,
"to": 409.22,
"sid": 181,
"location": 2,
"content": "我现在最大的期望就是当我5年后再打开这个视频"
},
{
"from": 409.22,
"to": 413.5,
"sid": 182,
"location": 2,
"content": "会发现速度其实是5g最无聊的应用"
},
{
"from": 414.96,
"to": 416.3,
"sid": 183,
"location": 2,
"content": "ok我视频的全部内容啦"
},
{
"from": 416.3,
"to": 417.98,
"sid": 184,
"location": 2,
"content": "非常感谢你能看到这里啊"
},
{
"from": 417.98,
"to": 419.72,
"sid": 185,
"location": 2,
"content": "当然更要感谢中国联通的朋友"
},
{
"from": 419.72,
"to": 421.22,
"sid": 186,
"location": 2,
"content": "在北京邮电大学"
},
{
"from": 421.22,
"to": 422.9,
"sid": 187,
"location": 2,
"content": "如果你这个视频做的不错的话"
},
{
"from": 422.9,
"to": 423.44,
"sid": 188,
"location": 2,
"content": "求赞求收藏"
},
{
"from": 423.44,
"to": 424.1,
"sid": 189,
"location": 2,
"content": "全品是转发"
},
{
"from": 424.1,
"to": 425.24,
"sid": 190,
"location": 2,
"content": "就是哪个大大的关注"
},
{
"from": 425.24,
"to": 427.77,
"sid": 191,
"location": 2,
"content": "各位的支持就是做视频的最大动力啊"
},
{
"from": 427.77,
"to": 429.03,
"sid": 192,
"location": 2,
"content": "最近要高考了呃"
},
{
"from": 429.03,
"to": 432.76,
"sid": 193,
"location": 2,
"content": "就就祝各位高考的朋友都能考出一个理想的成绩"
},
{
"from": 432.76,
"to": 435.88,
"sid": 194,
"location": 2,
"content": "ok各位我们下期再见嗯"
}
]
}
let rawSubTitles = a["body"]
var rawTranscript = []
rawSubTitles.forEach(element => {
rawTranscript.push(element["content"])
});
let longText = rawTranscript.join(" ")
console.log(longText)
|
281677160/openwrt-package
| 1,891
|
luci-app-syncthing/luasrc/model/cbi/syncthing.lua
|
-- Copyright 2008 Yanira <[email protected]>
-- Licensed to the public under the Apache License 2.0.
require("nixio.fs")
m = Map("syncthing", translate("Syncthing Synchronization Tool"))
m:section(SimpleSection).template = "syncthing/syncthing_status"
s = m:section(TypedSection, "syncthing")
s.addremove = false
s.anonymous = true
o = s:option(Flag, "enabled", translate("Enabled"))
o.default = 0
o.rmempty = false
gui_address = s:option(Value, "gui_address", translate("GUI access address"))
gui_address.description = translate("Use 0.0.0.0:8384 to monitor all access.")
gui_address.default = "http://0.0.0.0:8384"
gui_address.placeholder = "http://0.0.0.0:8384"
gui_address.rmempty = false
home = s:option(Value, "home", translate("Configuration file directory"))
home.description = translate("Only the configuration saved in /etc/syncthing will be automatically backed up!")
home.default = "/etc/syncthing"
home.placeholder = "/etc/syncthing"
home.rmempty = false
user = s:option(ListValue, "user", translate("User"))
user.description = translate("The default is syncthing, but it may cause permission denied. Syncthing officially does not recommend running as root.")
user:value("", translate("syncthing"))
for u in luci.util.execi("cat /etc/passwd | cut -d ':' -f1") do
user:value(u)
end
macprocs = s:option(Value, "macprocs", translate("Thread limit"))
macprocs.description = translate("0 to match the number of CPUs (default), >0 to explicitly specify concurrency.")
macprocs.default = "0"
macprocs.placeholder = "0"
macprocs.datatype="range(0,32)"
macprocs.rmempty = false
nice = s:option(Value, "nice", "Nice")
nice.description = translate("Explicitly specify nice. 0 is the highest and 19 is the lowest. (negative values are not allowed to be set temporarily)")
nice.default = "19"
nice.placeholder = "19"
nice.datatype="range(0,19)"
nice.rmempty = false
return m
|
281677160/openwrt-package
| 1,010
|
luci-app-syncthing/po/zh_Hans/syncthing.po
|
msgid "Syncthing"
msgstr "Syncthing"
msgid "Syncthing Synchronization Tool"
msgstr "Syncthing 存储同步工具"
msgid "Open Syncthing page"
msgstr "打开储存同步页面"
msgid "GUI access address"
msgstr "GUI访问地址"
msgid "Use 0.0.0.0:8384 to monitor all access."
msgstr "使用0.0.0.0:8384监听所有访问。"
msgid "Configuration file directory"
msgstr "配置文件存储目录"
msgid "Only the configuration saved in /etc/syncthing will be automatically backed up!"
msgstr "只有保存在 /etc/syncthing 的配置会被自动备份!"
msgid "User"
msgstr "用户"
msgid "The default is syncthing, but it may cause permission denied. Syncthing officially does not recommend running as root."
msgstr "默认为syncthing,但可能引起权限不足问题。Syncthing官方不建议以root身份运行。"
msgid "Thread limit"
msgstr "线程限制"
msgid "0 to match the number of CPUs (default), >0 to explicitly specify concurrency."
msgstr "使用0来匹配CPU核心数,或输入大于0的数来显式指定并发数。"
msgid "Explicitly specify nice. 0 is the highest and 19 is the lowest. (negative values are not allowed to be set temporarily)"
msgstr "显式指定进程Nice值。其中0最高,19最低。(暂不允许设置负值)"
|
2977094657/ZsxqCrawler
| 8,857
|
frontend/src/app/page.tsx
|
'use client';
import { useState, useEffect } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { apiClient, DatabaseStats, Group } from '@/lib/api';
import CrawlPanel from '@/components/CrawlPanel';
import FilePanel from '@/components/FilePanel';
import DataPanel from '@/components/DataPanel';
import TaskPanel from '@/components/TaskPanel';
import ConfigPanel from '@/components/ConfigPanel';
import GroupSelector from '@/components/GroupSelector';
import AccountPanel from '@/components/AccountPanel';
import { toast } from 'sonner';
export default function Home() {
const [stats, setStats] = useState<DatabaseStats | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedGroup, setSelectedGroup] = useState<Group | null>(null);
useEffect(() => {
loadStats();
}, []);
const loadStats = async () => {
try {
setLoading(true);
const data = await apiClient.getDatabaseStats();
setStats(data);
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : '加载统计信息失败');
} finally {
setLoading(false);
}
};
const refreshStats = () => {
loadStats();
};
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<Progress value={undefined} className="w-64 mb-4" />
<p className="text-muted-foreground">加载中...</p>
</div>
</div>
);
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="w-96">
<CardHeader>
<CardTitle className="text-red-600">连接错误</CardTitle>
<CardDescription>无法连接到后端API服务</CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-4">{error}</p>
<Button onClick={loadStats} className="w-full">
重试连接
</Button>
</CardContent>
</Card>
</div>
);
}
// 检查是否已配置
if (stats && stats.configured === false) {
return <ConfigPanel onConfigSaved={loadStats} />;
}
// 如果已配置但未选择群组,显示群组选择界面
if (stats && stats.configured !== false && !selectedGroup) {
return <GroupSelector onGroupSelected={setSelectedGroup} />;
}
return (
<div className="min-h-screen bg-background">
<div className="container mx-auto p-6">
{/* 页面标题和群组信息 */}
<div className="mb-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-4xl font-bold mb-2">🌟 知识星球数据采集器</h1>
<p className="text-muted-foreground">
知识星球内容爬取与文件下载工具,支持话题采集、评论获取、文件批量下载等功能
</p>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
onClick={() => setSelectedGroup(null)}
className="flex items-center gap-2"
>
← 返回群组选择
</Button>
</div>
</div>
{/* 当前选中的群组信息 */}
{selectedGroup && (
<Card className="mt-4">
<CardContent className="pt-4">
<div className="flex items-center gap-4">
{selectedGroup.background_url && (
<img
src={selectedGroup.background_url}
alt={selectedGroup.name}
className="w-16 h-16 rounded-lg object-cover"
/>
)}
<div className="flex-1">
<h2 className="text-xl font-semibold">{selectedGroup.name}</h2>
<div className="flex items-center gap-2 mt-1">
<Badge variant="secondary">{selectedGroup.type}</Badge>
<Badge variant="outline">ID: {selectedGroup.group_id}</Badge>
{selectedGroup.owner && (
<span className="text-sm text-muted-foreground">
群主: {selectedGroup.owner.name}
</span>
)}
</div>
</div>
{selectedGroup.statistics && (
<div className="flex gap-6 text-center">
<div>
<div className="text-lg font-semibold">
{selectedGroup.statistics.members_count || 0}
</div>
<div className="text-xs text-muted-foreground">成员</div>
</div>
<div>
<div className="text-lg font-semibold">
{selectedGroup.statistics.topics_count || 0}
</div>
<div className="text-xs text-muted-foreground">话题</div>
</div>
</div>
)}
</div>
</CardContent>
</Card>
)}
</div>
{/* 统计概览 */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">话题总数</CardTitle>
<Badge variant="secondary">📝</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{stats?.topic_database.timestamp_info.total_topics || 0}
</div>
<p className="text-xs text-muted-foreground">
{stats?.topic_database.timestamp_info.has_data ? '已有数据' : '暂无数据'}
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">文件总数</CardTitle>
<Badge variant="secondary">📁</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{stats?.file_database.stats.files || 0}
</div>
<p className="text-xs text-muted-foreground">
已收集文件信息
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">数据时间范围</CardTitle>
<Badge variant="secondary">📅</Badge>
</CardHeader>
<CardContent>
<div className="text-sm">
{stats?.topic_database.timestamp_info.has_data ? (
<>
<div className="font-medium">
{stats.topic_database.timestamp_info.oldest_timestamp}
</div>
<div className="text-muted-foreground">至</div>
<div className="font-medium">
{stats.topic_database.timestamp_info.newest_timestamp}
</div>
</>
) : (
<div className="text-muted-foreground">暂无数据</div>
)}
</div>
</CardContent>
</Card>
</div>
{/* 主要功能面板 */}
<Tabs defaultValue="crawl" className="space-y-6">
<TabsList className="grid w-full grid-cols-5">
<TabsTrigger value="crawl">话题采集</TabsTrigger>
<TabsTrigger value="files">文件管理</TabsTrigger>
<TabsTrigger value="data">数据查看</TabsTrigger>
<TabsTrigger value="tasks">任务状态</TabsTrigger>
<TabsTrigger value="accounts">账号管理</TabsTrigger>
</TabsList>
<TabsContent value="crawl">
<CrawlPanel onStatsUpdate={refreshStats} selectedGroup={selectedGroup} />
</TabsContent>
<TabsContent value="files">
<FilePanel onStatsUpdate={refreshStats} selectedGroup={selectedGroup} />
</TabsContent>
<TabsContent value="data">
<DataPanel selectedGroup={selectedGroup} />
</TabsContent>
<TabsContent value="tasks">
<TaskPanel />
</TabsContent>
<TabsContent value="accounts">
<AccountPanel />
</TabsContent>
</Tabs>
</div>
</div>
);
}
|
2977094657/ZsxqCrawler
| 6,031
|
frontend/src/app/globals.css
|
@import "tailwindcss";
@import "tw-animate-css";
@import "yet-another-react-lightbox/styles.css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
/* 修复 ScrollArea 组件导致的 display: table 问题 */
@layer components {
/* 覆盖 Radix ScrollArea 内部的 display: table 样式 */
[data-radix-scroll-area-viewport] > div[style*="display: table"],
[data-radix-scroll-area-viewport] > div[style*="display:table"] {
display: block !important;
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
table-layout: auto !important;
}
/* 更通用的 ScrollArea 内容修复 */
[data-radix-scroll-area-viewport] div[style*="min-width: 100%"] {
display: block !important;
width: 100% !important;
max-width: 100% !important;
}
/* 确保话题卡片容器的宽度限制 */
.topic-cards-container {
width: 100%;
max-width: 100%;
box-sizing: border-box;
overflow: hidden;
}
.topic-cards-container > div {
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
}
/* 确保卡片本身不会超出容器宽度 */
.topic-cards-container [data-slot="card"] {
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
}
/* 内容行数限制 */
.line-clamp-8 {
display: -webkit-box;
-webkit-line-clamp: 8;
-webkit-box-orient: vertical;
overflow: hidden;
}
/* 评论数量限制 - 现在使用动态计算,保留类名以防需要 */
.comments-clamp-3 {
/* 不再使用固定高度截断 */
}
.comments-expanded {
/* 不再使用固定高度 */
}
/* 强制链接对齐 - 覆盖prose类的样式 */
.prose a[style*="display: inline-flex"],
.prose a[style*="inline-flex"] {
display: inline-flex !important;
align-items: center !important;
vertical-align: middle !important;
}
/* 更强的选择器来覆盖prose类 */
.prose.prose-sm a[style*="display: inline-flex"],
.prose.prose-xs a[style*="display: inline-flex"] {
display: inline-flex !important;
align-items: center !important;
vertical-align: middle !important;
}
}
|
281677160/openwrt-package
| 19,927
|
luci-app-passwall/htdocs/luci-static/resources/view/passwall/qrcode.min.js
|
var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this.parsedData=[];for(var b=[],d=0,e=this.data.length;e>d;d++){var f=this.data.charCodeAt(d);f>65536?(b[0]=240|(1835008&f)>>>18,b[1]=128|(258048&f)>>>12,b[2]=128|(4032&f)>>>6,b[3]=128|63&f):f>2048?(b[0]=224|(61440&f)>>>12,b[1]=128|(4032&f)>>>6,b[2]=128|63&f):f>128?(b[0]=192|(1984&f)>>>6,b[1]=128|63&f):b[0]=f,this.parsedData=this.parsedData.concat(b)}this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function b(a,b){this.typeNumber=a,this.errorCorrectLevel=b,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function i(a,b){if(void 0==a.length)throw new Error(a.length+"/"+b);for(var c=0;c<a.length&&0==a[c];)c++;this.num=new Array(a.length-c+b);for(var d=0;d<a.length-c;d++)this.num[d]=a[d+c]}function j(a,b){this.totalCount=a,this.dataCount=b}function k(){this.buffer=[],this.length=0}function m(){return"undefined"!=typeof CanvasRenderingContext2D}function n(){var a=!1,b=navigator.userAgent;return/android/i.test(b)&&(a=!0,aMat=b.toString().match(/android ([0-9]\.[0-9])/i),aMat&&aMat[1]&&(a=parseFloat(aMat[1]))),a}function r(a,b){for(var c=1,e=s(a),f=0,g=l.length;g>=f;f++){var h=0;switch(b){case d.L:h=l[f][0];break;case d.M:h=l[f][1];break;case d.Q:h=l[f][2];break;case d.H:h=l[f][3]}if(h>=e)break;c++}if(c>l.length)throw new Error("Too long data");return c}function s(a){var b=encodeURI(a).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return b.length+(b.length!=a?3:0)}a.prototype={getLength:function(){return this.parsedData.length},write:function(a){for(var b=0,c=this.parsedData.length;c>b;b++)a.put(this.parsedData[b],8)}},b.prototype={addData:function(b){var c=new a(b);this.dataList.push(c),this.dataCache=null},isDark:function(a,b){if(0>a||this.moduleCount<=a||0>b||this.moduleCount<=b)throw new Error(a+","+b);return this.modules[a][b]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var d=0;d<this.moduleCount;d++){this.modules[d]=new Array(this.moduleCount);for(var e=0;e<this.moduleCount;e++)this.modules[d][e]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(a,c),this.typeNumber>=7&&this.setupTypeNumber(a),null==this.dataCache&&(this.dataCache=b.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,b){for(var c=-1;7>=c;c++)if(!(-1>=a+c||this.moduleCount<=a+c))for(var d=-1;7>=d;d++)-1>=b+d||this.moduleCount<=b+d||(this.modules[a+c][b+d]=c>=0&&6>=c&&(0==d||6==d)||d>=0&&6>=d&&(0==c||6==c)||c>=2&&4>=c&&d>=2&&4>=d?!0:!1)},getBestMaskPattern:function(){for(var a=0,b=0,c=0;8>c;c++){this.makeImpl(!0,c);var d=f.getLostPoint(this);(0==c||a>d)&&(a=d,b=c)}return b},createMovieClip:function(a,b,c){var d=a.createEmptyMovieClip(b,c),e=1;this.make();for(var f=0;f<this.modules.length;f++)for(var g=f*e,h=0;h<this.modules[f].length;h++){var i=h*e,j=this.modules[f][h];j&&(d.beginFill(0,100),d.moveTo(i,g),d.lineTo(i+e,g),d.lineTo(i+e,g+e),d.lineTo(i,g+e),d.endFill())}return d},setupTimingPattern:function(){for(var a=8;a<this.moduleCount-8;a++)null==this.modules[a][6]&&(this.modules[a][6]=0==a%2);for(var b=8;b<this.moduleCount-8;b++)null==this.modules[6][b]&&(this.modules[6][b]=0==b%2)},setupPositionAdjustPattern:function(){for(var a=f.getPatternPosition(this.typeNumber),b=0;b<a.length;b++)for(var c=0;c<a.length;c++){var d=a[b],e=a[c];if(null==this.modules[d][e])for(var g=-2;2>=g;g++)for(var h=-2;2>=h;h++)this.modules[d+g][e+h]=-2==g||2==g||-2==h||2==h||0==g&&0==h?!0:!1}},setupTypeNumber:function(a){for(var b=f.getBCHTypeNumber(this.typeNumber),c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=d}for(var c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=d}},setupTypeInfo:function(a,b){for(var c=this.errorCorrectLevel<<3|b,d=f.getBCHTypeInfo(c),e=0;15>e;e++){var g=!a&&1==(1&d>>e);6>e?this.modules[e][8]=g:8>e?this.modules[e+1][8]=g:this.modules[this.moduleCount-15+e][8]=g}for(var e=0;15>e;e++){var g=!a&&1==(1&d>>e);8>e?this.modules[8][this.moduleCount-e-1]=g:9>e?this.modules[8][15-e-1+1]=g:this.modules[8][15-e-1]=g}this.modules[this.moduleCount-8][8]=!a},mapData:function(a,b){for(var c=-1,d=this.moduleCount-1,e=7,g=0,h=this.moduleCount-1;h>0;h-=2)for(6==h&&h--;;){for(var i=0;2>i;i++)if(null==this.modules[d][h-i]){var j=!1;g<a.length&&(j=1==(1&a[g]>>>e));var k=f.getMask(b,d,h-i);k&&(j=!j),this.modules[d][h-i]=j,e--,-1==e&&(g++,e=7)}if(d+=c,0>d||this.moduleCount<=d){d-=c,c=-c;break}}}},b.PAD0=236,b.PAD1=17,b.createData=function(a,c,d){for(var e=j.getRSBlocks(a,c),g=new k,h=0;h<d.length;h++){var i=d[h];g.put(i.mode,4),g.put(i.getLength(),f.getLengthInBits(i.mode,a)),i.write(g)}for(var l=0,h=0;h<e.length;h++)l+=e[h].dataCount;if(g.getLengthInBits()>8*l)throw new Error("code length overflow. ("+g.getLengthInBits()+">"+8*l+")");for(g.getLengthInBits()+4<=8*l&&g.put(0,4);0!=g.getLengthInBits()%8;)g.putBit(!1);for(;;){if(g.getLengthInBits()>=8*l)break;if(g.put(b.PAD0,8),g.getLengthInBits()>=8*l)break;g.put(b.PAD1,8)}return b.createBytes(g,e)},b.createBytes=function(a,b){for(var c=0,d=0,e=0,g=new Array(b.length),h=new Array(b.length),j=0;j<b.length;j++){var k=b[j].dataCount,l=b[j].totalCount-k;d=Math.max(d,k),e=Math.max(e,l),g[j]=new Array(k);for(var m=0;m<g[j].length;m++)g[j][m]=255&a.buffer[m+c];c+=k;var n=f.getErrorCorrectPolynomial(l),o=new i(g[j],n.getLength()-1),p=o.mod(n);h[j]=new Array(n.getLength()-1);for(var m=0;m<h[j].length;m++){var q=m+p.getLength()-h[j].length;h[j][m]=q>=0?p.get(q):0}}for(var r=0,m=0;m<b.length;m++)r+=b[m].totalCount;for(var s=new Array(r),t=0,m=0;d>m;m++)for(var j=0;j<b.length;j++)m<g[j].length&&(s[t++]=g[j][m]);for(var m=0;e>m;m++)for(var j=0;j<b.length;j++)m<h[j].length&&(s[t++]=h[j][m]);return s};for(var c={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},d={L:1,M:0,Q:3,H:2},e={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},f={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(a){for(var b=a<<10;f.getBCHDigit(b)-f.getBCHDigit(f.G15)>=0;)b^=f.G15<<f.getBCHDigit(b)-f.getBCHDigit(f.G15);return(a<<10|b)^f.G15_MASK},getBCHTypeNumber:function(a){for(var b=a<<12;f.getBCHDigit(b)-f.getBCHDigit(f.G18)>=0;)b^=f.G18<<f.getBCHDigit(b)-f.getBCHDigit(f.G18);return a<<12|b},getBCHDigit:function(a){for(var b=0;0!=a;)b++,a>>>=1;return b},getPatternPosition:function(a){return f.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,b,c){switch(a){case e.PATTERN000:return 0==(b+c)%2;case e.PATTERN001:return 0==b%2;case e.PATTERN010:return 0==c%3;case e.PATTERN011:return 0==(b+c)%3;case e.PATTERN100:return 0==(Math.floor(b/2)+Math.floor(c/3))%2;case e.PATTERN101:return 0==b*c%2+b*c%3;case e.PATTERN110:return 0==(b*c%2+b*c%3)%2;case e.PATTERN111:return 0==(b*c%3+(b+c)%2)%2;default:throw new Error("bad maskPattern:"+a)}},getErrorCorrectPolynomial:function(a){for(var b=new i([1],0),c=0;a>c;c++)b=b.multiply(new i([1,g.gexp(c)],0));return b},getLengthInBits:function(a,b){if(b>=1&&10>b)switch(a){case c.MODE_NUMBER:return 10;case c.MODE_ALPHA_NUM:return 9;case c.MODE_8BIT_BYTE:return 8;case c.MODE_KANJI:return 8;default:throw new Error("mode:"+a)}else if(27>b)switch(a){case c.MODE_NUMBER:return 12;case c.MODE_ALPHA_NUM:return 11;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 10;default:throw new Error("mode:"+a)}else{if(!(41>b))throw new Error("type:"+b);switch(a){case c.MODE_NUMBER:return 14;case c.MODE_ALPHA_NUM:return 13;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 12;default:throw new Error("mode:"+a)}}},getLostPoint:function(a){for(var b=a.getModuleCount(),c=0,d=0;b>d;d++)for(var e=0;b>e;e++){for(var f=0,g=a.isDark(d,e),h=-1;1>=h;h++)if(!(0>d+h||d+h>=b))for(var i=-1;1>=i;i++)0>e+i||e+i>=b||(0!=h||0!=i)&&g==a.isDark(d+h,e+i)&&f++;f>5&&(c+=3+f-5)}for(var d=0;b-1>d;d++)for(var e=0;b-1>e;e++){var j=0;a.isDark(d,e)&&j++,a.isDark(d+1,e)&&j++,a.isDark(d,e+1)&&j++,a.isDark(d+1,e+1)&&j++,(0==j||4==j)&&(c+=3)}for(var d=0;b>d;d++)for(var e=0;b-6>e;e++)a.isDark(d,e)&&!a.isDark(d,e+1)&&a.isDark(d,e+2)&&a.isDark(d,e+3)&&a.isDark(d,e+4)&&!a.isDark(d,e+5)&&a.isDark(d,e+6)&&(c+=40);for(var e=0;b>e;e++)for(var d=0;b-6>d;d++)a.isDark(d,e)&&!a.isDark(d+1,e)&&a.isDark(d+2,e)&&a.isDark(d+3,e)&&a.isDark(d+4,e)&&!a.isDark(d+5,e)&&a.isDark(d+6,e)&&(c+=40);for(var k=0,e=0;b>e;e++)for(var d=0;b>d;d++)a.isDark(d,e)&&k++;var l=Math.abs(100*k/b/b-50)/5;return c+=10*l}},g={glog:function(a){if(1>a)throw new Error("glog("+a+")");return g.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;a>=256;)a-=255;return g.EXP_TABLE[a]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)},h=0;8>h;h++)g.EXP_TABLE[h]=1<<h;for(var h=8;256>h;h++)g.EXP_TABLE[h]=g.EXP_TABLE[h-4]^g.EXP_TABLE[h-5]^g.EXP_TABLE[h-6]^g.EXP_TABLE[h-8];for(var h=0;255>h;h++)g.LOG_TABLE[g.EXP_TABLE[h]]=h;i.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var b=new Array(this.getLength()+a.getLength()-1),c=0;c<this.getLength();c++)for(var d=0;d<a.getLength();d++)b[c+d]^=g.gexp(g.glog(this.get(c))+g.glog(a.get(d)));return new i(b,0)},mod:function(a){if(this.getLength()-a.getLength()<0)return this;for(var b=g.glog(this.get(0))-g.glog(a.get(0)),c=new Array(this.getLength()),d=0;d<this.getLength();d++)c[d]=this.get(d);for(var d=0;d<a.getLength();d++)c[d]^=g.gexp(g.glog(a.get(d))+b);return new i(c,0).mod(a)}},j.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],j.getRSBlocks=function(a,b){var c=j.getRsBlockTable(a,b);if(void 0==c)throw new Error("bad rs block @ typeNumber:"+a+"/errorCorrectLevel:"+b);for(var d=c.length/3,e=[],f=0;d>f;f++)for(var g=c[3*f+0],h=c[3*f+1],i=c[3*f+2],k=0;g>k;k++)e.push(new j(h,i));return e},j.getRsBlockTable=function(a,b){switch(b){case d.L:return j.RS_BLOCK_TABLE[4*(a-1)+0];case d.M:return j.RS_BLOCK_TABLE[4*(a-1)+1];case d.Q:return j.RS_BLOCK_TABLE[4*(a-1)+2];case d.H:return j.RS_BLOCK_TABLE[4*(a-1)+3];default:return void 0}},k.prototype={get:function(a){var b=Math.floor(a/8);return 1==(1&this.buffer[b]>>>7-a%8)},put:function(a,b){for(var c=0;b>c;c++)this.putBit(1==(1&a>>>b-c-1))},getLengthInBits:function(){return this.length},putBit:function(a){var b=Math.floor(this.length/8);this.buffer.length<=b&&this.buffer.push(0),a&&(this.buffer[b]|=128>>>this.length%8),this.length++}};var l=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]],o=function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){function g(a,b){var c=document.createElementNS("http://www.w3.org/2000/svg",a);for(var d in b)b.hasOwnProperty(d)&&c.setAttribute(d,b[d]);return c}var b=this._htOption,c=this._el,d=a.getModuleCount();Math.floor(b.width/d),Math.floor(b.height/d),this.clear();var h=g("svg",{viewBox:"0 0 "+String(d)+" "+String(d),width:"100%",height:"100%",fill:b.colorLight});h.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"),c.appendChild(h),h.appendChild(g("rect",{fill:b.colorDark,width:"1",height:"1",id:"template"}));for(var i=0;d>i;i++)for(var j=0;d>j;j++)if(a.isDark(i,j)){var k=g("use",{x:String(i),y:String(j)});k.setAttributeNS("http://www.w3.org/1999/xlink","href","#template"),h.appendChild(k)}},a.prototype.clear=function(){for(;this._el.hasChildNodes();)this._el.removeChild(this._el.lastChild)},a}(),p="svg"===document.documentElement.tagName.toLowerCase(),q=p?o:m()?function(){function a(){this._elImage.src=this._elCanvas.toDataURL("image/png"),this._elImage.style.display="block",this._elCanvas.style.display="none"}function d(a,b){var c=this;if(c._fFail=b,c._fSuccess=a,null===c._bSupportDataURI){var d=document.createElement("img"),e=function(){c._bSupportDataURI=!1,c._fFail&&_fFail.call(c)},f=function(){c._bSupportDataURI=!0,c._fSuccess&&c._fSuccess.call(c)};return d.onabort=e,d.onerror=e,d.onload=f,d.src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",void 0}c._bSupportDataURI===!0&&c._fSuccess?c._fSuccess.call(c):c._bSupportDataURI===!1&&c._fFail&&c._fFail.call(c)}if(this._android&&this._android<=2.1){var b=1/window.devicePixelRatio,c=CanvasRenderingContext2D.prototype.drawImage;CanvasRenderingContext2D.prototype.drawImage=function(a,d,e,f,g,h,i,j){if("nodeName"in a&&/img/i.test(a.nodeName))for(var l=arguments.length-1;l>=1;l--)arguments[l]=arguments[l]*b;else"undefined"==typeof j&&(arguments[1]*=b,arguments[2]*=b,arguments[3]*=b,arguments[4]*=b);c.apply(this,arguments)}}var e=function(a,b){this._bIsPainted=!1,this._android=n(),this._htOption=b,this._elCanvas=document.createElement("canvas"),this._elCanvas.width=b.width,this._elCanvas.height=b.height,a.appendChild(this._elCanvas),this._el=a,this._oContext=this._elCanvas.getContext("2d"),this._bIsPainted=!1,this._elImage=document.createElement("img"),this._elImage.style.display="none",this._el.appendChild(this._elImage),this._bSupportDataURI=null};return e.prototype.draw=function(a){var b=this._elImage,c=this._oContext,d=this._htOption,e=a.getModuleCount(),f=d.width/e,g=d.height/e,h=Math.round(f),i=Math.round(g);b.style.display="none",this.clear();for(var j=0;e>j;j++)for(var k=0;e>k;k++){var l=a.isDark(j,k),m=k*f,n=j*g;c.strokeStyle=l?d.colorDark:d.colorLight,c.lineWidth=1,c.fillStyle=l?d.colorDark:d.colorLight,c.fillRect(m,n,f,g),c.strokeRect(Math.floor(m)+.5,Math.floor(n)+.5,h,i),c.strokeRect(Math.ceil(m)-.5,Math.ceil(n)-.5,h,i)}this._bIsPainted=!0},e.prototype.makeImage=function(){this._bIsPainted&&d.call(this,a)},e.prototype.isPainted=function(){return this._bIsPainted},e.prototype.clear=function(){this._oContext.clearRect(0,0,this._elCanvas.width,this._elCanvas.height),this._bIsPainted=!1},e.prototype.round=function(a){return a?Math.floor(1e3*a)/1e3:a},e}():function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){for(var b=this._htOption,c=this._el,d=a.getModuleCount(),e=Math.floor(b.width/d),f=Math.floor(b.height/d),g=['<table style="border:0;border-collapse:collapse;">'],h=0;d>h;h++){g.push("<tr>");for(var i=0;d>i;i++)g.push('<td style="border:0;border-collapse:collapse;padding:0;margin:0;width:'+e+"px;height:"+f+"px;background-color:"+(a.isDark(h,i)?b.colorDark:b.colorLight)+';"></td>');g.push("</tr>")}g.push("</table>"),c.innerHTML=g.join("");var j=c.childNodes[0],k=(b.width-j.offsetWidth)/2,l=(b.height-j.offsetHeight)/2;k>0&&l>0&&(j.style.margin=l+"px "+k+"px")},a.prototype.clear=function(){this._el.innerHTML=""},a}();QRCode=function(a,b){if(this._htOption={width:256,height:256,typeNumber:4,colorDark:"#000000",colorLight:"#ffffff",correctLevel:d.H},"string"==typeof b&&(b={text:b}),b)for(var c in b)this._htOption[c]=b[c];"string"==typeof a&&(a=document.getElementById(a)),this._android=n(),this._el=a,this._oQRCode=null,this._oDrawing=new q(this._el,this._htOption),this._htOption.text&&this.makeCode(this._htOption.text)},QRCode.prototype.makeCode=function(a){this._oQRCode=new b(r(a,this._htOption.correctLevel),this._htOption.correctLevel),this._oQRCode.addData(a),this._oQRCode.make(),this._el.title=a,this._oDrawing.draw(this._oQRCode),this.makeImage()},QRCode.prototype.makeImage=function(){"function"==typeof this._oDrawing.makeImage&&(!this._android||this._android>=3)&&this._oDrawing.makeImage()},QRCode.prototype.clear=function(){this._oDrawing.clear()},QRCode.CorrectLevel=d}();
|
2951121599/Bili-Insight
| 1,083
|
chrome-extension/popup/options.css
|
button {
padding: 5px 10px;
border-width: 0px;
border-radius: 3px;
background: #1E90FF;
cursor: pointer;
outline: none;
color: white;
font-size: 14px;
}
.item {
padding: 4px 0;
}
.btn-primary {
color: #fff;
background-color: #2196f3;
border-color: transparent;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none !important;
}
label {
font-size: 14px;
}
input[type="number"] {
-moz-appearance: textfield;
box-sizing: border-box;
}
.btn {
display: inline-block;
margin-bottom: 0;
font-weight: normal;
text-align: center;
white-space: nowrap;
vertical-align: middle;
touch-action: manipulation;
cursor: pointer;
background-image: none;
border: 1px solid transparent;
padding: 0 16px;
height: 32px;
font-size: 13px;
border-radius: 3px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#status {
height: 24px;
font-size: 14px;
color: green;
}
|
2951121599/Bili-Insight
| 1,015
|
chrome-extension/popup/popup.html
|
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Bili Insight</title>
<link rel="stylesheet" href="./options.css">
</head>
<body style="padding: 20px 100px;">
<h1>B站视频内容总结预览插件:通过使用这个插件来更快地了解视频的内容。</h1>
<div class="item">
<label for="api-key">apikey:</label>
<input type="password" id="api-key" style="width: 300px;">
</div>
<div id="status" class="item"></div>
<div class="item">
<button id="save" class="btn btn-primary">保存</button>
</div>
<p>
用户是 B 站的视频观众,他们希望通过使用这个插件来更好地理解视频的内容。
当浏览B站时,把鼠标悬停至视频标题时,插件会自动展示内容总结,通过词云/思维导图等方式以可视化的形式呈现给用户,方便用户快速了解视频内容。
* up主视频字幕、标题、简介、tag生成的内容总结
</p>
<div>
<img src="/images/Insight_640x400.png" width="640px" alt="Bili Insight,洞察B站视频内容插件." />
</div>
<h3>
代码
</h3>
<ul>
<li><a href="https://github.com/wangqmshf/Bili-Insight" target="_blank">Bili-Insight</a></li>
</ul>
<script src="popup.js"></script>
</body>
</html>
|
2977094657/ZsxqCrawler
| 10,382
|
frontend/src/components/AccountPanel.tsx
|
'use client';
import React, { useEffect, useState } from 'react';
import { apiClient, Account, AccountSelf } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { toast } from 'sonner';
interface AccountWithInfo extends Account {
selfInfo?: AccountSelf | null;
loadingSelf?: boolean;
}
export default function AccountPanel() {
const [accounts, setAccounts] = useState<AccountWithInfo[]>([]);
const [loading, setLoading] = useState<boolean>(false);
// 添加账号弹窗
const [creating, setCreating] = useState<boolean>(false);
const [createOpen, setCreateOpen] = useState<boolean>(false);
const [name, setName] = useState<string>('');
const [cookie, setCookie] = useState<string>('');
const [makeDefault, setMakeDefault] = useState<boolean>(false);
const loadAccounts = async () => {
setLoading(true);
try {
const res = await apiClient.listAccounts();
const list: AccountWithInfo[] = (res.accounts || []).map(acc => ({ ...acc, loadingSelf: true }));
setAccounts(list);
// 并发加载所有账号的自我信息
const promises = list.map(async (acc) => {
try {
const selfRes = await apiClient.getAccountSelf(acc.id);
return { id: acc.id, selfInfo: selfRes?.self || null };
} catch {
return { id: acc.id, selfInfo: null };
}
});
const results = await Promise.all(promises);
// 更新账号列表,填入自我信息
setAccounts(prev => prev.map(acc => {
const result = results.find(r => r.id === acc.id);
return { ...acc, selfInfo: result?.selfInfo || null, loadingSelf: false };
}));
} catch (e) {
toast.error('加载账号列表失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
loadAccounts();
}, []);
const handleCreate = async () => {
if (!cookie.trim()) {
toast.error('请填写Cookie');
return;
}
setCreating(true);
try {
await apiClient.createAccount({ cookie: cookie.trim(), name: name.trim() || undefined, make_default: makeDefault });
toast.success('账号已添加');
setCookie('');
setName('');
setMakeDefault(false);
setCreateOpen(false);
await loadAccounts();
} catch (e: any) {
toast.error(`添加失败: ${e?.message || '未知错误'}`);
} finally {
setCreating(false);
}
};
const handleDelete = async (id: string) => {
if (!confirm('确认删除该账号?删除后分配到此账号的群组将回退到默认账号。')) return;
try {
await apiClient.deleteAccount(id);
toast.success('账号已删除');
await loadAccounts();
} catch (e: any) {
toast.error(`删除失败: ${e?.message || '未知错误'}`);
}
};
const handleSetDefault = async (id: string) => {
try {
await apiClient.setDefaultAccount(id);
toast.success('已设为默认账号');
await loadAccounts();
} catch (e: any) {
toast.error(`设置失败: ${e?.message || '未知错误'}`);
}
};
const handleRefresh = async (id: string) => {
// 标记该账号为刷新中
setAccounts(prev => prev.map(acc =>
acc.id === id ? { ...acc, loadingSelf: true } : acc
));
try {
const res = await apiClient.refreshAccountSelf(id);
setAccounts(prev => prev.map(acc =>
acc.id === id ? { ...acc, selfInfo: res?.self || null, loadingSelf: false } : acc
));
toast.success('信息已刷新');
} catch (e: any) {
toast.error(`刷新失败: ${e?.message || '未知错误'}`);
setAccounts(prev => prev.map(acc =>
acc.id === id ? { ...acc, loadingSelf: false } : acc
));
}
};
return (
<div className="space-y-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<div>
<CardTitle>账号管理</CardTitle>
<CardDescription>表格展示账号信息,支持设为默认、刷新与删除操作</CardDescription>
</div>
<div>
<Button variant="default" onClick={() => setCreateOpen(true)}>添加账号</Button>
</div>
</CardHeader>
<CardContent>
{loading ? (
<div className="text-sm text-muted-foreground">加载中...</div>
) : accounts.length === 0 ? (
<div className="text-sm text-muted-foreground">暂无账号,请先添加</div>
) : (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>账号名称</TableHead>
<TableHead>用户信息</TableHead>
<TableHead>UID</TableHead>
<TableHead>位置</TableHead>
<TableHead>Cookie</TableHead>
<TableHead>默认</TableHead>
<TableHead>创建时间</TableHead>
<TableHead className="text-right">操作</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{accounts.map((acc) => (
<TableRow key={acc.id}>
<TableCell className="font-medium">{acc.name || acc.id}</TableCell>
<TableCell>
{acc.loadingSelf ? (
<span className="text-xs text-gray-400">加载中...</span>
) : acc.selfInfo ? (
<div className="flex items-center gap-2">
{acc.selfInfo.avatar_url && (
<img
src={apiClient.getProxyImageUrl(acc.selfInfo.avatar_url)}
alt={acc.selfInfo.name || ''}
className="w-6 h-6 rounded-full"
onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = 'none'; }}
/>
)}
<div className="text-sm">
<div className="font-medium">{acc.selfInfo.name || '未命名'}</div>
{acc.selfInfo.grade && (
<div className="text-xs text-gray-500">{acc.selfInfo.grade}</div>
)}
</div>
</div>
) : (
<span className="text-xs text-gray-400">无信息</span>
)}
</TableCell>
<TableCell className="text-sm text-gray-600">
{acc.selfInfo?.uid || '-'}
</TableCell>
<TableCell className="text-sm text-gray-600">
{acc.selfInfo?.location || '-'}
</TableCell>
<TableCell className="max-w-[200px] truncate text-xs text-gray-500">
{acc.cookie || '***'}
</TableCell>
<TableCell>
{acc.is_default ? <Badge variant="secondary">默认</Badge> : <span className="text-gray-400">-</span>}
</TableCell>
<TableCell className="text-sm text-gray-600">{acc.created_at || '-'}</TableCell>
<TableCell className="text-right space-x-2">
<Button
size="sm"
variant="outline"
onClick={() => handleRefresh(acc.id)}
disabled={acc.loadingSelf}
>
{acc.loadingSelf ? '刷新中...' : '刷新'}
</Button>
{!acc.is_default && acc.id !== 'default' && (
<Button size="sm" variant="outline" onClick={() => handleSetDefault(acc.id)}>
设为默认
</Button>
)}
{acc.id !== 'default' && (
<Button size="sm" variant="destructive" onClick={() => handleDelete(acc.id)}>
删除
</Button>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>添加新账号</DialogTitle>
<DialogDescription>仅保存 Cookie 与名称,Cookie 将被安全掩码展示</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="acc-name">账号名称(可选)</Label>
<Input id="acc-name" placeholder="例如:个人号/备用号" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="acc-cookie">Cookie</Label>
<Textarea
id="acc-cookie"
placeholder="粘贴完整的 Cookie 值..."
rows={4}
value={cookie}
onChange={(e) => setCookie(e.target.value)}
/>
</div>
<div className="flex items-center gap-2">
<input
id="acc-default"
type="checkbox"
checked={makeDefault}
onChange={(e) => setMakeDefault(e.target.checked)}
/>
<Label htmlFor="acc-default">设为默认账号</Label>
</div>
</div>
<DialogFooter className="mt-4">
<Button variant="outline" onClick={() => setCreateOpen(false)}>取消</Button>
<Button onClick={handleCreate} disabled={creating || !cookie.trim()} className="min-w-24">
{creating ? '提交中...' : '添加账号'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
|
2977094657/ZsxqCrawler
| 13,747
|
frontend/src/components/CrawlPanel.tsx
|
'use client';
import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { Settings } from 'lucide-react';
import { apiClient, Group } from '@/lib/api';
import { toast } from 'sonner';
import CrawlSettingsDialog from './CrawlSettingsDialog';
import CrawlLatestDialog from './CrawlLatestDialog';
interface CrawlPanelProps {
onStatsUpdate: () => void;
selectedGroup?: Group | null;
}
export default function CrawlPanel({ onStatsUpdate, selectedGroup }: CrawlPanelProps) {
const [loading, setLoading] = useState<string | null>(null);
const [historicalPages, setHistoricalPages] = useState(10);
const [historicalPerPage, setHistoricalPerPage] = useState(20);
// 添加组件实例标识
const instanceId = Math.random().toString(36).substr(2, 9);
console.log(`🏷️ CrawlPanel实例 ${instanceId} 已创建`);
// 爬取设置状态
const [crawlSettingsOpen, setCrawlSettingsOpen] = useState(false);
const [crawlLatestOpen, setCrawlLatestOpen] = useState(false);
const [crawlInterval, setCrawlInterval] = useState(3.5);
const [longSleepInterval, setLongSleepInterval] = useState(240);
const [pagesPerBatch, setPagesPerBatch] = useState(15);
const [crawlIntervalMin, setCrawlIntervalMin] = useState<number>(2);
const [crawlIntervalMax, setCrawlIntervalMax] = useState<number>(5);
const [longSleepIntervalMin, setLongSleepIntervalMin] = useState<number>(180);
const [longSleepIntervalMax, setLongSleepIntervalMax] = useState<number>(300);
const handleCrawlHistorical = async () => {
if (!selectedGroup) {
toast.error('请先选择一个群组');
return;
}
try {
setLoading('historical');
const response = await apiClient.crawlHistorical(selectedGroup.group_id, historicalPages, historicalPerPage);
toast.success(`任务已创建: ${response.task_id}`);
onStatsUpdate();
} catch (error) {
toast.error(`创建任务失败: ${error instanceof Error ? error.message : '未知错误'}`);
} finally {
setLoading(null);
}
};
const handleCrawlAll = async () => {
if (!selectedGroup) {
toast.error('请先选择一个群组');
return;
}
try {
setLoading('all');
// 构建爬取设置
console.log(`🚀 CrawlPanel实例 ${instanceId} 构建爬取设置前的状态值:`);
console.log(' crawlIntervalMin:', crawlIntervalMin);
console.log(' crawlIntervalMax:', crawlIntervalMax);
console.log(' longSleepIntervalMin:', longSleepIntervalMin);
console.log(' longSleepIntervalMax:', longSleepIntervalMax);
console.log(' pagesPerBatch:', pagesPerBatch);
const crawlSettings = {
crawlIntervalMin,
crawlIntervalMax,
longSleepIntervalMin,
longSleepIntervalMax,
pagesPerBatch: Math.max(pagesPerBatch, 5)
};
console.log(`🚀 CrawlPanel实例 ${instanceId} 最终发送的爬取设置:`, crawlSettings);
const response = await apiClient.crawlAll(selectedGroup.group_id, crawlSettings);
toast.success(`任务已创建: ${response.task_id}`);
onStatsUpdate();
} catch (error) {
toast.error(`创建任务失败: ${error instanceof Error ? error.message : '未知错误'}`);
} finally {
setLoading(null);
}
};
const handleCrawlLatestConfirm = async (params: {
mode: 'latest' | 'range';
startTime?: string;
endTime?: string;
lastDays?: number;
perPage?: number;
}) => {
if (!selectedGroup) {
toast.error('请先选择一个群组');
return;
}
try {
setLoading('latest');
// 构建爬取设置
const crawlSettings = {
crawlIntervalMin,
crawlIntervalMax,
longSleepIntervalMin,
longSleepIntervalMax,
pagesPerBatch: Math.max(pagesPerBatch, 5),
};
let response: any;
if (params.mode === 'latest') {
response = await apiClient.crawlLatestUntilComplete(selectedGroup.group_id, crawlSettings);
} else {
response = await apiClient.crawlByTimeRange(selectedGroup.group_id, {
startTime: params.startTime,
endTime: params.endTime,
lastDays: params.lastDays,
perPage: params.perPage,
crawlIntervalMin,
crawlIntervalMax,
longSleepIntervalMin,
longSleepIntervalMax,
pagesPerBatch: Math.max(pagesPerBatch, 5),
});
}
toast.success(`任务已创建: ${response.task_id}`);
onStatsUpdate();
setCrawlLatestOpen(false);
} catch (error) {
toast.error(`创建任务失败: ${error instanceof Error ? error.message : '未知错误'}`);
} finally {
setLoading(null);
}
};
// 处理爬取设置变更
const handleCrawlSettingsChange = (settings: {
crawlInterval: number;
longSleepInterval: number;
pagesPerBatch: number;
crawlIntervalMin?: number;
crawlIntervalMax?: number;
longSleepIntervalMin?: number;
longSleepIntervalMax?: number;
}) => {
console.log(`🔧 CrawlPanel实例 ${instanceId} 收到爬取设置变更:`, settings);
setCrawlInterval(settings.crawlInterval);
setLongSleepInterval(settings.longSleepInterval);
setPagesPerBatch(settings.pagesPerBatch);
setCrawlIntervalMin(settings.crawlIntervalMin || 2);
setCrawlIntervalMax(settings.crawlIntervalMax || 5);
setLongSleepIntervalMin(settings.longSleepIntervalMin || 180);
setLongSleepIntervalMax(settings.longSleepIntervalMax || 300);
console.log('🔧 设置后的状态值:');
console.log(' crawlIntervalMin:', settings.crawlIntervalMin || 2);
console.log(' crawlIntervalMax:', settings.crawlIntervalMax || 5);
console.log(' longSleepIntervalMin:', settings.longSleepIntervalMin || 180);
console.log(' longSleepIntervalMax:', settings.longSleepIntervalMax || 300);
console.log(' pagesPerBatch:', settings.pagesPerBatch);
};
const handleClearTopicDatabase = async () => {
if (!selectedGroup) {
toast.error('请先选择一个群组');
return;
}
try {
setLoading('clear');
const response = await apiClient.clearTopicDatabase(selectedGroup.group_id);
toast.success('话题数据库已清除');
onStatsUpdate();
} catch (error) {
toast.error(`清除数据库失败: ${error instanceof Error ? error.message : '未知错误'}`);
} finally {
setLoading(null);
}
};
return (
<div className="space-y-6">
{/* 爬取设置 */}
<div className="flex justify-between items-center">
<div>
<h3 className="text-lg font-semibold">话题采集</h3>
<p className="text-sm text-muted-foreground">配置爬取间隔和批次设置</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => setCrawlSettingsOpen(true)}
className="flex items-center gap-2"
>
<Settings className="h-4 w-4" />
爬取设置
</Button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{/* 获取最新话题 */}
<Card className="border border-gray-200 shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Badge variant="secondary">🆕</Badge>
获取最新话题
</CardTitle>
<CardDescription>
默认从最新开始,也可按时间区间采集
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-sm text-muted-foreground space-y-2">
<p>✅ 默认:直接从最新话题开始增量抓取</p>
<p>🕒 可选:按时间区间采集(首次也可用)</p>
</div>
<Button
onClick={() => setCrawlLatestOpen(true)}
disabled={loading === 'latest'}
className="w-full"
>
{loading === 'latest' ? '创建任务中...' : '获取最新'}
</Button>
</CardContent>
</Card>
{/* 增量爬取历史 */}
<Card className="border border-gray-200 shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Badge variant="secondary">📚</Badge>
增量爬取历史
</CardTitle>
<CardDescription>
基于数据库最老时间戳,精确补充历史数据
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-2">
<div className="space-y-2">
<Label htmlFor="historical-pages">爬取页数</Label>
<Input
id="historical-pages"
type="number"
value={historicalPages}
onChange={(e) => setHistoricalPages(Number(e.target.value))}
min={1}
max={1000}
/>
</div>
<div className="space-y-2">
<Label htmlFor="historical-per-page">每页数量</Label>
<Input
id="historical-per-page"
type="number"
value={historicalPerPage}
onChange={(e) => setHistoricalPerPage(Number(e.target.value))}
min={1}
max={100}
/>
</div>
</div>
<Button
onClick={handleCrawlHistorical}
disabled={loading === 'historical'}
className="w-full"
>
{loading === 'historical' ? '创建任务中...' : '开始爬取'}
</Button>
<div className="text-xs text-muted-foreground">
<p>✅ 适合:精确补充历史,有目标的回填</p>
<p>📊 总计爬取: {historicalPages * historicalPerPage} 条记录</p>
</div>
</CardContent>
</Card>
{/* 获取所有历史数据 */}
<Card className="border border-gray-200 shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Badge variant="secondary">🔄</Badge>
获取所有历史数据
</CardTitle>
<CardDescription>
无限爬取,从最老数据无限挖掘
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-sm text-muted-foreground space-y-2">
<p>⚠️ 这是一个长时间运行的任务</p>
<p>🔄 将持续爬取直到没有更多历史数据</p>
<p>📈 适合:全量归档,完整数据收集</p>
</div>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="destructive"
disabled={loading === 'all'}
className="w-full"
>
{loading === 'all' ? '创建任务中...' : '开始全量爬取'}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认全量爬取</AlertDialogTitle>
<AlertDialogDescription>
这将开始一个长时间运行的任务,持续爬取所有历史数据直到完成。
任务可能需要数小时甚至更长时间,确定要继续吗?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction onClick={handleCrawlAll}>
确认开始
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</CardContent>
</Card>
{/* 清除话题数据库 */}
<Card className="border border-gray-200 shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Badge variant="destructive">🗑️</Badge>
清除话题数据库
</CardTitle>
<CardDescription>
清除所有话题、评论、用户等数据
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-sm text-muted-foreground space-y-2">
<p>⚠️ 将删除所有话题数据</p>
<p>🔄 清除评论、用户、图片等</p>
<p>💾 不会删除配置和设置</p>
</div>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="destructive"
disabled={loading === 'clear'}
className="w-full"
>
{loading === 'clear' ? '清除中...' : '清除数据库'}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="text-red-600">确认清除数据库</AlertDialogTitle>
<AlertDialogDescription className="text-red-700">
这将永久删除所有话题数据,包括话题、评论、用户信息等。
此操作不可恢复,确定要继续吗?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction
onClick={handleClearTopicDatabase}
className="bg-red-600 hover:bg-red-700 focus:ring-red-600"
>
确认清除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</CardContent>
</Card>
</div>
<CrawlLatestDialog
open={crawlLatestOpen}
onOpenChange={setCrawlLatestOpen}
submitting={loading === 'latest'}
onConfirm={handleCrawlLatestConfirm}
defaultLastDays={7}
defaultPerPage={20}
/>
{/* 爬取设置对话框 */}
<CrawlSettingsDialog
open={crawlSettingsOpen}
onOpenChange={setCrawlSettingsOpen}
crawlInterval={crawlInterval}
longSleepInterval={longSleepInterval}
pagesPerBatch={pagesPerBatch}
onSettingsChange={handleCrawlSettingsChange}
/>
</div>
);
}
|
2977094657/ZsxqCrawler
| 8,735
|
frontend/src/components/FilePanel.tsx
|
'use client';
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { apiClient, Group } from '@/lib/api';
import { toast } from 'sonner';
interface FilePanelProps {
onStatsUpdate: () => void;
selectedGroup?: Group | null;
}
interface FileStats {
database_stats: Record<string, number>;
download_stats: {
total_files: number;
downloaded: number;
pending: number;
failed: number;
};
}
export default function FilePanel({ onStatsUpdate, selectedGroup }: FilePanelProps) {
const [loading, setLoading] = useState<string | null>(null);
const [fileStats, setFileStats] = useState<FileStats | null>(null);
const [maxFiles, setMaxFiles] = useState<number | undefined>(undefined);
const [sortBy, setSortBy] = useState('download_count');
useEffect(() => {
loadFileStats();
}, []);
const loadFileStats = async () => {
try {
const stats = await apiClient.getFileStats();
setFileStats(stats);
} catch (error) {
console.error('加载文件统计失败:', error);
}
};
const handleClearFileDatabase = async () => {
try {
setLoading('clear');
const response = await apiClient.clearFileDatabase();
toast.success('文件数据库已清除');
onStatsUpdate();
loadFileStats();
} catch (error) {
toast.error(`清除数据库失败: ${error instanceof Error ? error.message : '未知错误'}`);
} finally {
setLoading(null);
}
};
const handleDownloadFiles = async () => {
try {
setLoading('download');
const response = await apiClient.downloadFiles(maxFiles, sortBy);
toast.success(`任务已创建: ${response.task_id}`);
onStatsUpdate();
loadFileStats();
} catch (error) {
toast.error(`创建任务失败: ${error instanceof Error ? error.message : '未知错误'}`);
} finally {
setLoading(null);
}
};
return (
<div className="space-y-6">
{/* 文件统计概览 */}
{fileStats && (
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<Card className="border border-gray-200 shadow-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">文件总数</CardTitle>
<Badge variant="secondary">📁</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{fileStats.download_stats.total_files}</div>
<p className="text-xs text-muted-foreground">已收集文件信息</p>
</CardContent>
</Card>
<Card className="border border-gray-200 shadow-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">已下载</CardTitle>
<Badge variant="secondary" className="bg-green-100 text-green-800">✅</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-green-600">{fileStats.download_stats.downloaded}</div>
<p className="text-xs text-muted-foreground">下载完成</p>
</CardContent>
</Card>
<Card className="border border-gray-200 shadow-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">待下载</CardTitle>
<Badge variant="secondary" className="bg-yellow-100 text-yellow-800">⏳</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-yellow-600">{fileStats.download_stats.pending}</div>
<p className="text-xs text-muted-foreground">等待下载</p>
</CardContent>
</Card>
<Card className="border border-gray-200 shadow-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">下载失败</CardTitle>
<Badge variant="secondary" className="bg-red-100 text-red-800">❌</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-red-600">{fileStats.download_stats.failed}</div>
<p className="text-xs text-muted-foreground">需要重试</p>
</CardContent>
</Card>
</div>
)}
{/* 功能操作面板 */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* 下载文件 */}
<Card className="border border-gray-200 shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Badge variant="secondary">⬇️</Badge>
下载文件
</CardTitle>
<CardDescription>
自动收集文件列表并根据设置的条件批量下载
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="max-files">最大下载文件数</Label>
<Input
id="max-files"
type="number"
placeholder="留空表示无限制"
value={maxFiles || ''}
onChange={(e) => setMaxFiles(e.target.value ? Number(e.target.value) : undefined)}
min={1}
/>
</div>
<div className="space-y-2">
<Label htmlFor="sort-by">排序方式</Label>
<Select value={sortBy} onValueChange={setSortBy}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="download_count">按下载次数排序</SelectItem>
<SelectItem value="time">按时间顺序排序</SelectItem>
</SelectContent>
</Select>
</div>
<Button
onClick={handleDownloadFiles}
disabled={loading === 'download'}
className="w-full"
>
{loading === 'download' ? '创建任务中...' : '开始下载'}
</Button>
<div className="text-xs text-muted-foreground space-y-1">
<p>🔍 自动收集文件列表</p>
<p>📁 文件将保存到 downloads 目录</p>
<p>🔄 支持断点续传和重复检测</p>
</div>
</CardContent>
</Card>
{/* 清除下载数据库 */}
<Card className="border border-gray-200 shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Badge variant="destructive">🗑️</Badge>
清除下载数据库
</CardTitle>
<CardDescription>
清除所有文件记录和下载状态
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-sm text-muted-foreground space-y-2">
<p>⚠️ 将删除所有文件记录</p>
<p>🔄 清除下载状态和进度</p>
<p>💾 不会删除已下载的文件</p>
</div>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
disabled={loading === 'clear'}
variant="destructive"
className="w-full"
>
{loading === 'clear' ? '清除中...' : '清除数据库'}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="text-red-600">确认清除文件数据库</AlertDialogTitle>
<AlertDialogDescription className="text-red-700">
这将永久删除所有文件记录和下载状态,但不会删除已下载的文件。
此操作不可恢复,确定要继续吗?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction
onClick={handleClearFileDatabase}
className="bg-red-600 hover:bg-red-700 focus:ring-red-600"
>
确认清除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</CardContent>
</Card>
</div>
</div>
);
}
|
2977094657/ZsxqCrawler
| 6,393
|
frontend/src/components/CrawlLatestDialog.tsx
|
'use client';
import React, { useEffect, useState } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
type Mode = 'latest' | 'range';
interface CrawlLatestDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onConfirm: (params: {
mode: Mode;
startTime?: string;
endTime?: string;
lastDays?: number;
perPage?: number;
}) => void;
submitting?: boolean;
defaultLastDays?: number;
defaultPerPage?: number;
}
export default function CrawlLatestDialog({
open,
onOpenChange,
onConfirm,
submitting = false,
defaultLastDays = 7,
defaultPerPage = 20,
}: CrawlLatestDialogProps) {
const [mode, setMode] = useState<Mode>('latest');
const [lastDays, setLastDays] = useState<number | ''>(defaultLastDays);
const [startTime, setStartTime] = useState('');
const [endTime, setEndTime] = useState('');
const [perPage, setPerPage] = useState<number | ''>(defaultPerPage);
useEffect(() => {
if (open) {
setMode('latest');
setLastDays(defaultLastDays);
setStartTime('');
setEndTime('');
setPerPage(defaultPerPage);
}
}, [open, defaultLastDays, defaultPerPage]);
const handleConfirm = () => {
const payload: {
mode: Mode;
startTime?: string;
endTime?: string;
lastDays?: number;
perPage?: number;
} = { mode };
if (mode === 'range') {
if (startTime) payload.startTime = new Date(startTime).toISOString();
if (endTime) payload.endTime = new Date(endTime).toISOString();
if (lastDays !== '' && !Number.isNaN(Number(lastDays))) {
payload.lastDays = Number(lastDays);
}
if (perPage !== '' && !Number.isNaN(Number(perPage))) {
payload.perPage = Number(perPage);
}
}
onConfirm(payload);
};
const isConfirmDisabled =
submitting || (mode === 'range' && lastDays === '' && !startTime && !endTime);
return (
<Dialog open={open} onOpenChange={(v) => !submitting && onOpenChange(v)}>
<DialogContent className="sm:max-w-[560px]">
<DialogHeader>
<DialogTitle>获取最新话题</DialogTitle>
<DialogDescription>
默认从最新开始抓取;也可以按时间区间采集,首次数据库为空也可使用。
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<Label>采集方式</Label>
<div className="flex gap-2">
<Button
type="button"
variant={mode === 'latest' ? 'default' : 'outline'}
size="sm"
onClick={() => setMode('latest')}
className="flex-1"
>
从最新开始(默认)
</Button>
<Button
type="button"
variant={mode === 'range' ? 'default' : 'outline'}
size="sm"
onClick={() => setMode('range')}
className="flex-1"
>
按时间区间
</Button>
</div>
</div>
{mode === 'range' ? (
<div className="space-y-4">
<div className="space-y-2">
<Label>最近天数(可选)</Label>
<Input
type="number"
min="1"
max="3650"
placeholder={`${defaultLastDays}`}
value={lastDays}
onChange={(e) => {
const v = e.target.value;
if (v === '') setLastDays('');
else {
const n = parseInt(v);
if (!Number.isNaN(n)) setLastDays(n);
}
}}
/>
<p className="text-xs text-muted-foreground">
填写“最近N天”或下方自定义开始/结束时间,留空则不限制该项。
</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="space-y-2">
<Label>开始时间(可选)</Label>
<Input
type="datetime-local"
value={startTime}
onChange={(e) => setStartTime(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label>结束时间(可选)</Label>
<Input
type="datetime-local"
value={endTime}
onChange={(e) => setEndTime(e.target.value)}
/>
</div>
</div>
<div className="space-y-2">
<Label>每页数量</Label>
<Input
type="number"
min="1"
max="100"
value={perPage}
onChange={(e) => {
const v = e.target.value;
if (v === '') setPerPage('');
else {
const n = parseInt(v);
if (!Number.isNaN(n)) setPerPage(n);
}
}}
onBlur={(e) => {
if (e.target.value === '' || parseInt(e.target.value) < 1) {
setPerPage(defaultPerPage);
}
}}
/>
<p className="text-xs text-muted-foreground">
用于时间区间采集的每页数量,默认 {defaultPerPage}。
</p>
</div>
</div>
) : (
<div className="text-xs text-muted-foreground space-y-1">
<p>• 直接点击“确认开始”将从最新话题向后增量抓取。</p>
<p>• 如需限定时间范围,请切换到“按时间区间”。</p>
</div>
)}
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={submitting}
>
取消
</Button>
<Button type="button" onClick={handleConfirm} disabled={isConfirmDisabled}>
{submitting ? '创建任务中...' : '确认开始'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
|
281677160/openwrt-package
| 31,563
|
luci-app-passwall/luasrc/controller/passwall.lua
|
-- Copyright (C) 2018-2020 L-WRT Team
-- Copyright (C) 2021-2025 xiaorouji
module("luci.controller.passwall", package.seeall)
local api = require "luci.passwall.api"
local appname = "passwall" -- not available
local uci = api.uci -- in funtion index()
local fs = api.fs
local http = require "luci.http"
local util = require "luci.util"
local i18n = require "luci.i18n"
local jsonStringify = luci.jsonc.stringify
function index()
if not nixio.fs.access("/etc/config/passwall") then
if nixio.fs.access("/usr/share/passwall/0_default_config") then
luci.sys.call('cp -f /usr/share/passwall/0_default_config /etc/config/passwall')
else return end
end
local api = require "luci.passwall.api"
local appname = "passwall" -- global definitions not available
local uci = api.uci -- in function index()
local fs = api.fs
entry({"admin", "services", appname}).dependent = true
entry({"admin", "services", appname, "reset_config"}, call("reset_config")).leaf = true
entry({"admin", "services", appname, "show"}, call("show_menu")).leaf = true
entry({"admin", "services", appname, "hide"}, call("hide_menu")).leaf = true
local e
if uci:get(appname, "@global[0]", "hide_from_luci") ~= "1" then
e = entry({"admin", "services", appname}, alias("admin", "services", appname, "settings"), _("Pass Wall"), -1)
else
e = entry({"admin", "services", appname}, alias("admin", "services", appname, "settings"), nil, -1)
end
e.dependent = true
e.acl_depends = { "luci-app-passwall" }
--[[ Client ]]
entry({"admin", "services", appname, "settings"}, cbi(appname .. "/client/global"), _("Basic Settings"), 1).dependent = true
entry({"admin", "services", appname, "node_list"}, cbi(appname .. "/client/node_list"), _("Node List"), 2).dependent = true
entry({"admin", "services", appname, "node_subscribe"}, cbi(appname .. "/client/node_subscribe"), _("Node Subscribe"), 3).dependent = true
entry({"admin", "services", appname, "other"}, cbi(appname .. "/client/other", {autoapply = true}), _("Other Settings"), 92).leaf = true
if fs.access("/usr/sbin/haproxy") then
entry({"admin", "services", appname, "haproxy"}, cbi(appname .. "/client/haproxy"), _("Load Balancing"), 93).leaf = true
end
entry({"admin", "services", appname, "app_update"}, cbi(appname .. "/client/app_update"), _("App Update"), 95).leaf = true
entry({"admin", "services", appname, "rule"}, cbi(appname .. "/client/rule"), _("Rule Manage"), 96).leaf = true
entry({"admin", "services", appname, "rule_list"}, cbi(appname .. "/client/rule_list", {autoapply = true}), _("Rule List"), 97).leaf = true
entry({"admin", "services", appname, "node_subscribe_config"}, cbi(appname .. "/client/node_subscribe_config")).leaf = true
entry({"admin", "services", appname, "node_config"}, cbi(appname .. "/client/node_config")).leaf = true
entry({"admin", "services", appname, "shunt_rules"}, cbi(appname .. "/client/shunt_rules")).leaf = true
entry({"admin", "services", appname, "socks_config"}, cbi(appname .. "/client/socks_config")).leaf = true
entry({"admin", "services", appname, "acl"}, cbi(appname .. "/client/acl"), _("Access control"), 98).leaf = true
entry({"admin", "services", appname, "acl_config"}, cbi(appname .. "/client/acl_config")).leaf = true
entry({"admin", "services", appname, "log"}, form(appname .. "/client/log"), _("Watch Logs"), 999).leaf = true
--[[ Server ]]
entry({"admin", "services", appname, "server"}, cbi(appname .. "/server/index"), _("Server-Side"), 99).leaf = true
entry({"admin", "services", appname, "server_user"}, cbi(appname .. "/server/user")).leaf = true
--[[ API ]]
entry({"admin", "services", appname, "server_user_status"}, call("server_user_status")).leaf = true
entry({"admin", "services", appname, "server_user_log"}, call("server_user_log")).leaf = true
entry({"admin", "services", appname, "server_get_log"}, call("server_get_log")).leaf = true
entry({"admin", "services", appname, "server_clear_log"}, call("server_clear_log")).leaf = true
entry({"admin", "services", appname, "link_add_node"}, call("link_add_node")).leaf = true
entry({"admin", "services", appname, "socks_autoswitch_add_node"}, call("socks_autoswitch_add_node")).leaf = true
entry({"admin", "services", appname, "socks_autoswitch_remove_node"}, call("socks_autoswitch_remove_node")).leaf = true
entry({"admin", "services", appname, "gen_client_config"}, call("gen_client_config")).leaf = true
entry({"admin", "services", appname, "get_now_use_node"}, call("get_now_use_node")).leaf = true
entry({"admin", "services", appname, "get_redir_log"}, call("get_redir_log")).leaf = true
entry({"admin", "services", appname, "get_socks_log"}, call("get_socks_log")).leaf = true
entry({"admin", "services", appname, "get_chinadns_log"}, call("get_chinadns_log")).leaf = true
entry({"admin", "services", appname, "get_log"}, call("get_log")).leaf = true
entry({"admin", "services", appname, "clear_log"}, call("clear_log")).leaf = true
entry({"admin", "services", appname, "index_status"}, call("index_status")).leaf = true
entry({"admin", "services", appname, "haproxy_status"}, call("haproxy_status")).leaf = true
entry({"admin", "services", appname, "socks_status"}, call("socks_status")).leaf = true
entry({"admin", "services", appname, "connect_status"}, call("connect_status")).leaf = true
entry({"admin", "services", appname, "ping_node"}, call("ping_node")).leaf = true
entry({"admin", "services", appname, "urltest_node"}, call("urltest_node")).leaf = true
entry({"admin", "services", appname, "set_node"}, call("set_node")).leaf = true
entry({"admin", "services", appname, "copy_node"}, call("copy_node")).leaf = true
entry({"admin", "services", appname, "clear_all_nodes"}, call("clear_all_nodes")).leaf = true
entry({"admin", "services", appname, "delete_select_nodes"}, call("delete_select_nodes")).leaf = true
entry({"admin", "services", appname, "update_rules"}, call("update_rules")).leaf = true
entry({"admin", "services", appname, "subscribe_del_node"}, call("subscribe_del_node")).leaf = true
entry({"admin", "services", appname, "subscribe_del_all"}, call("subscribe_del_all")).leaf = true
entry({"admin", "services", appname, "subscribe_manual"}, call("subscribe_manual")).leaf = true
entry({"admin", "services", appname, "subscribe_manual_all"}, call("subscribe_manual_all")).leaf = true
--[[rule_list]]
entry({"admin", "services", appname, "read_rulelist"}, call("read_rulelist")).leaf = true
--[[Components update]]
entry({"admin", "services", appname, "check_passwall"}, call("app_check")).leaf = true
local coms = require "luci.passwall.com"
local com
for _, com in ipairs(coms.order) do
entry({"admin", "services", appname, "check_" .. com}, call("com_check", com)).leaf = true
entry({"admin", "services", appname, "update_" .. com}, call("com_update", com)).leaf = true
end
--[[Backup]]
entry({"admin", "services", appname, "create_backup"}, call("create_backup")).leaf = true
entry({"admin", "services", appname, "restore_backup"}, call("restore_backup")).leaf = true
--[[geoview]]
entry({"admin", "services", appname, "geo_view"}, call("geo_view")).leaf = true
end
local function http_write_json(content)
http.prepare_content("application/json")
http.write(jsonStringify(content or {code = 1}))
end
function reset_config()
luci.sys.call('/etc/init.d/passwall stop')
luci.sys.call('[ -f "/usr/share/passwall/0_default_config" ] && cp -f /usr/share/passwall/0_default_config /etc/config/passwall')
http.redirect(api.url())
end
function show_menu()
api.sh_uci_del(appname, "@global[0]", "hide_from_luci", true)
luci.sys.call("rm -rf /tmp/luci-*")
luci.sys.call("/etc/init.d/rpcd restart >/dev/null")
http.redirect(api.url())
end
function hide_menu()
api.sh_uci_set(appname, "@global[0]", "hide_from_luci", "1", true)
luci.sys.call("rm -rf /tmp/luci-*")
luci.sys.call("/etc/init.d/rpcd restart >/dev/null")
http.redirect(luci.dispatcher.build_url("admin", "status", "overview"))
end
function link_add_node()
-- 分片接收以突破uhttpd的限制
local tmp_file = "/tmp/links.conf"
local chunk = http.formvalue("chunk")
local chunk_index = tonumber(http.formvalue("chunk_index"))
local total_chunks = tonumber(http.formvalue("total_chunks"))
if chunk and chunk_index ~= nil and total_chunks ~= nil then
-- 按顺序拼接到文件
local mode = "a"
if chunk_index == 0 then
mode = "w"
end
local f = io.open(tmp_file, mode)
if f then
f:write(chunk)
f:close()
end
-- 如果是最后一片,才执行
if chunk_index + 1 == total_chunks then
luci.sys.call("lua /usr/share/passwall/subscribe.lua add log")
end
end
end
function socks_autoswitch_add_node()
local id = http.formvalue("id")
local key = http.formvalue("key")
if id and id ~= "" and key and key ~= "" then
uci:set(appname, id, "enable_autoswitch", "1")
local new_list = uci:get(appname, id, "autoswitch_backup_node") or {}
for i = #new_list, 1, -1 do
if (uci:get(appname, new_list[i], "remarks") or ""):find(key) then
table.remove(new_list, i)
end
end
for k, e in ipairs(api.get_valid_nodes()) do
if e.node_type == "normal" and e["remark"]:find(key) then
table.insert(new_list, e.id)
end
end
uci:set_list(appname, id, "autoswitch_backup_node", new_list)
api.uci_save(uci, appname)
end
http.redirect(api.url("socks_config", id))
end
function socks_autoswitch_remove_node()
local id = http.formvalue("id")
local key = http.formvalue("key")
if id and id ~= "" and key and key ~= "" then
uci:set(appname, id, "enable_autoswitch", "1")
local new_list = uci:get(appname, id, "autoswitch_backup_node") or {}
for i = #new_list, 1, -1 do
if (uci:get(appname, new_list[i], "remarks") or ""):find(key) then
table.remove(new_list, i)
end
end
uci:set_list(appname, id, "autoswitch_backup_node", new_list)
api.uci_save(uci, appname)
end
http.redirect(api.url("socks_config", id))
end
function gen_client_config()
local id = http.formvalue("id")
local config_file = api.TMP_PATH .. "/config_" .. id
luci.sys.call(string.format("/usr/share/passwall/app.sh run_socks flag=config_%s node=%s bind=127.0.0.1 socks_port=1080 config_file=%s no_run=1", id, id, config_file))
if nixio.fs.access(config_file) then
http.prepare_content("application/json")
http.write(luci.sys.exec("cat " .. config_file))
luci.sys.call("rm -f " .. config_file)
else
http.redirect(api.url("node_list"))
end
end
function get_now_use_node()
local path = "/tmp/etc/passwall/acl/default"
local e = {}
local tcp_node = api.get_cache_var("ACL_GLOBAL_TCP_node")
if tcp_node then
e["TCP"] = tcp_node
end
local udp_node = api.get_cache_var("ACL_GLOBAL_UDP_node")
if udp_node then
e["UDP"] = udp_node
end
http_write_json(e)
end
function get_redir_log()
local name = http.formvalue("name")
local proto = http.formvalue("proto")
local path = "/tmp/etc/passwall/acl/" .. name
proto = proto:upper()
if proto == "UDP" and (uci:get(appname, "@global[0]", "udp_node") or "nil") == "tcp" and not fs.access(path .. "/" .. proto .. ".log") then
proto = "TCP"
end
if fs.access(path .. "/" .. proto .. ".log") then
local content = luci.sys.exec("tail -n 19999 ".. path .. "/" .. proto .. ".log")
content = content:gsub("\n", "<br />")
http.write(content)
else
http.write(string.format("<script>alert('%s');window.close();</script>", i18n.translate("Not enabled log")))
end
end
function get_socks_log()
local name = http.formvalue("name")
local path = "/tmp/etc/passwall/SOCKS_" .. name .. ".log"
if fs.access(path) then
local content = luci.sys.exec("cat ".. path)
content = content:gsub("\n", "<br />")
http.write(content)
else
http.write(string.format("<script>alert('%s');window.close();</script>", i18n.translate("Not enabled log")))
end
end
function get_chinadns_log()
local flag = http.formvalue("flag")
local path = "/tmp/etc/passwall/acl/" .. flag .. "/chinadns_ng.log"
if fs.access(path) then
local content = luci.sys.exec("tail -n 5000 ".. path)
content = content:gsub("\n", "<br />")
http.write(content)
else
http.write(string.format("<script>alert('%s');window.close();</script>", i18n.translate("Not enabled log")))
end
end
function get_log()
-- luci.sys.exec("[ -f /tmp/log/passwall.log ] && sed '1!G;h;$!d' /tmp/log/passwall.log > /tmp/log/passwall_show.log")
http.write(luci.sys.exec("[ -f '/tmp/log/passwall.log' ] && cat /tmp/log/passwall.log"))
end
function clear_log()
luci.sys.call("echo '' > /tmp/log/passwall.log")
end
function index_status()
local e = {}
local dns_shunt = uci:get(appname, "@global[0]", "dns_shunt") or "dnsmasq"
if dns_shunt == "smartdns" then
e.dns_mode_status = luci.sys.call("pidof smartdns >/dev/null") == 0
elseif dns_shunt == "chinadns-ng" then
e.dns_mode_status = luci.sys.call("/bin/busybox top -bn1 | grep -v 'grep' | grep '/tmp/etc/passwall/bin/' | grep 'default' | grep 'chinadns_ng' >/dev/null") == 0
else
e.dns_mode_status = luci.sys.call("netstat -apn | grep ':15353 ' >/dev/null") == 0
end
e.haproxy_status = luci.sys.call(string.format("/bin/busybox top -bn1 | grep -v grep | grep '%s/bin/' | grep haproxy >/dev/null", appname)) == 0
e["tcp_node_status"] = luci.sys.call("/bin/busybox top -bn1 | grep -v 'grep' | grep '/tmp/etc/passwall/bin/' | grep 'default' | grep 'TCP' >/dev/null") == 0
if (uci:get(appname, "@global[0]", "udp_node") or "nil") == "tcp" then
e["udp_node_status"] = e["tcp_node_status"]
else
e["udp_node_status"] = luci.sys.call("/bin/busybox top -bn1 | grep -v 'grep' | grep '/tmp/etc/passwall/bin/' | grep 'default' | grep 'UDP' >/dev/null") == 0
end
http_write_json(e)
end
function haproxy_status()
local e = luci.sys.call(string.format("/bin/busybox top -bn1 | grep -v grep | grep '%s/bin/' | grep haproxy >/dev/null", appname)) == 0
http_write_json(e)
end
function socks_status()
local e = {}
local index = http.formvalue("index")
local id = http.formvalue("id")
e.index = index
e.socks_status = luci.sys.call(string.format("/bin/busybox top -bn1 | grep -v 'grep' | grep '/tmp/etc/passwall/bin/' | grep -v '_acl_' | grep '%s' | grep 'SOCKS_' > /dev/null", id)) == 0
local use_http = uci:get(appname, id, "http_port") or 0
e.use_http = 0
if tonumber(use_http) > 0 then
e.use_http = 1
e.http_status = luci.sys.call(string.format("/bin/busybox top -bn1 | grep -v 'grep' | grep '/tmp/etc/passwall/bin/' | grep -v '_acl_' | grep '%s' | grep -E 'HTTP_|HTTP2SOCKS' > /dev/null", id)) == 0
end
http_write_json(e)
end
function connect_status()
local e = {}
e.use_time = ""
local url = http.formvalue("url")
local baidu = string.find(url, "baidu")
local chn_list = uci:get(appname, "@global[0]", "chn_list") or "direct"
local gfw_list = uci:get(appname, "@global[0]", "use_gfw_list") or "1"
local proxy_mode = uci:get(appname, "@global[0]", "tcp_proxy_mode") or "proxy"
local localhost_proxy = uci:get(appname, "@global[0]", "localhost_proxy") or "1"
local socks_server = (localhost_proxy == "0") and api.get_cache_var("GLOBAL_TCP_SOCKS_server") or ""
-- 兼容 curl 8.6 time_starttransfer 错误
local curl_ver = api.get_bin_version_cache("/usr/bin/curl", "-V 2>/dev/null | head -n 1 | awk '{print $2}' | cut -d. -f1,2 | tr -d ' \n'") or "0"
url = (curl_ver == "8.6") and "-w %{http_code}:%{time_appconnect} https://" .. url
or "-w %{http_code}:%{time_starttransfer} http://" .. url
if socks_server and socks_server ~= "" then
if (chn_list == "proxy" and gfw_list == "0" and proxy_mode ~= "proxy" and baidu ~= nil) or (chn_list == "0" and gfw_list == "0" and proxy_mode == "proxy") then
-- 中国列表+百度 or 全局
url = "-x socks5h://" .. socks_server .. " " .. url
elseif baidu == nil then
-- 其他代理模式+百度以外网站
url = "-x socks5h://" .. socks_server .. " " .. url
end
end
local result = luci.sys.exec('/usr/bin/curl --max-time 5 -o /dev/null -I -sk ' .. url)
local code = tonumber(luci.sys.exec("echo -n '" .. result .. "' | awk -F ':' '{print $1}'") or "0")
if code ~= 0 then
local use_time_str = luci.sys.exec("echo -n '" .. result .. "' | awk -F ':' '{print $2}'")
local use_time = tonumber(use_time_str)
if use_time then
if use_time_str:find("%.") then
e.use_time = string.format("%.2f", use_time * 1000)
else
e.use_time = string.format("%.2f", use_time / 1000)
end
e.ping_type = "curl"
end
end
http_write_json(e)
end
function ping_node()
local index = http.formvalue("index")
local address = http.formvalue("address")
local port = http.formvalue("port")
local type = http.formvalue("type") or "icmp"
local e = {}
e.index = index
if type == "tcping" and luci.sys.exec("echo -n $(command -v tcping)") ~= "" then
if api.is_ipv6(address) then
address = api.get_ipv6_only(address)
end
e.ping = luci.sys.exec(string.format("echo -n $(tcping -q -c 1 -i 1 -t 2 -p %s %s 2>&1 | grep -o 'time=[0-9]*' | awk -F '=' '{print $2}') 2>/dev/null", port, address))
else
e.ping = luci.sys.exec("echo -n $(ping -c 1 -W 1 %q 2>&1 | grep -o 'time=[0-9]*' | awk -F '=' '{print $2}') 2>/dev/null" % address)
end
http_write_json(e)
end
function urltest_node()
local index = http.formvalue("index")
local id = http.formvalue("id")
local e = {}
e.index = index
local result = luci.sys.exec(string.format("/usr/share/passwall/test.sh url_test_node %s %s", id, "urltest_node"))
local code = tonumber(luci.sys.exec("echo -n '" .. result .. "' | awk -F ':' '{print $1}'") or "0")
if code ~= 0 then
local use_time_str = luci.sys.exec("echo -n '" .. result .. "' | awk -F ':' '{print $2}'")
local use_time = tonumber(use_time_str)
if use_time then
if use_time_str:find("%.") then
e.use_time = string.format("%.2f", use_time * 1000)
else
e.use_time = string.format("%.2f", use_time / 1000)
end
end
end
http_write_json(e)
end
function set_node()
local protocol = http.formvalue("protocol")
local section = http.formvalue("section")
uci:set(appname, "@global[0]", protocol .. "_node", section)
api.uci_save(uci, appname, true, true)
http.redirect(api.url("log"))
end
function copy_node()
local section = http.formvalue("section")
local uuid = api.gen_short_uuid()
uci:section(appname, "nodes", uuid)
for k, v in pairs(uci:get_all(appname, section)) do
local filter = k:find("%.")
if filter and filter == 1 then
else
xpcall(function()
uci:set(appname, uuid, k, v)
end,
function(e)
end)
end
end
uci:delete(appname, uuid, "add_from")
uci:set(appname, uuid, "add_mode", 1)
api.uci_save(uci, appname)
http.redirect(api.url("node_config", uuid))
end
function clear_all_nodes()
uci:set(appname, '@global[0]', "enabled", "0")
uci:set(appname, '@global[0]', "socks_enabled", "0")
uci:set(appname, '@haproxy_config[0]', "balancing_enable", "0")
uci:delete(appname, '@global[0]', "tcp_node")
uci:delete(appname, '@global[0]', "udp_node")
uci:foreach(appname, "socks", function(t)
uci:delete(appname, t[".name"])
uci:set_list(appname, t[".name"], "autoswitch_backup_node", {})
end)
uci:foreach(appname, "haproxy_config", function(t)
uci:delete(appname, t[".name"])
end)
uci:foreach(appname, "acl_rule", function(t)
uci:delete(appname, t[".name"], "tcp_node")
uci:delete(appname, t[".name"], "udp_node")
end)
uci:foreach(appname, "nodes", function(node)
uci:delete(appname, node['.name'])
end)
uci:foreach(appname, "subscribe_list", function(t)
uci:delete(appname, t[".name"], "md5")
uci:delete(appname, t[".name"], "chain_proxy")
uci:delete(appname, t[".name"], "preproxy_node")
uci:delete(appname, t[".name"], "to_node")
end)
api.uci_save(uci, appname, true, true)
end
function delete_select_nodes()
local ids = http.formvalue("ids")
string.gsub(ids, '[^' .. "," .. ']+', function(w)
if (uci:get(appname, "@global[0]", "tcp_node") or "") == w then
uci:delete(appname, '@global[0]', "tcp_node")
end
if (uci:get(appname, "@global[0]", "udp_node") or "") == w then
uci:delete(appname, '@global[0]', "udp_node")
end
uci:foreach(appname, "socks", function(t)
if t["node"] == w then
uci:delete(appname, t[".name"])
end
local auto_switch_node_list = uci:get(appname, t[".name"], "autoswitch_backup_node") or {}
for i = #auto_switch_node_list, 1, -1 do
if w == auto_switch_node_list[i] then
table.remove(auto_switch_node_list, i)
end
end
uci:set_list(appname, t[".name"], "autoswitch_backup_node", auto_switch_node_list)
end)
uci:foreach(appname, "haproxy_config", function(t)
if t["lbss"] == w then
uci:delete(appname, t[".name"])
end
end)
uci:foreach(appname, "acl_rule", function(t)
if t["tcp_node"] == w then
uci:delete(appname, t[".name"], "tcp_node")
end
if t["udp_node"] == w then
uci:delete(appname, t[".name"], "udp_node")
end
end)
uci:foreach(appname, "nodes", function(t)
if t["preproxy_node"] == w then
uci:delete(appname, t[".name"], "preproxy_node")
uci:delete(appname, t[".name"], "chain_proxy")
end
if t["to_node"] == w then
uci:delete(appname, t[".name"], "to_node")
uci:delete(appname, t[".name"], "chain_proxy")
end
local list_name = t["urltest_node"] and "urltest_node" or (t["balancing_node"] and "balancing_node")
if list_name then
local nodes = uci:get_list(appname, t[".name"], list_name)
if nodes then
local changed = false
local new_nodes = {}
for _, node in ipairs(nodes) do
if node ~= w then
table.insert(new_nodes, node)
else
changed = true
end
end
if changed then
uci:set_list(appname, t[".name"], list_name, new_nodes)
end
end
end
if t["fallback_node"] == w then
uci:delete(appname, t[".name"], "fallback_node")
end
end)
uci:foreach(appname, "subscribe_list", function(t)
if t["preproxy_node"] == w then
uci:delete(appname, t[".name"], "preproxy_node")
uci:delete(appname, t[".name"], "chain_proxy")
end
if t["to_node"] == w then
uci:delete(appname, t[".name"], "to_node")
uci:delete(appname, t[".name"], "chain_proxy")
end
end)
if (uci:get(appname, w, "add_mode") or "0") == "2" then
local add_from = uci:get(appname, w, "add_from") or ""
if add_from ~= "" then
uci:foreach(appname, "subscribe_list", function(t)
if t["remark"] == add_from then
uci:delete(appname, t[".name"], "md5")
end
end)
end
end
uci:delete(appname, w)
end)
api.uci_save(uci, appname, true, true)
end
function update_rules()
local update = http.formvalue("update")
luci.sys.call("lua /usr/share/passwall/rule_update.lua log '" .. update .. "' > /dev/null 2>&1 &")
http_write_json()
end
function server_user_status()
local e = {}
e.index = http.formvalue("index")
e.status = luci.sys.call(string.format("/bin/busybox top -bn1 | grep -v 'grep' | grep '%s/bin/' | grep -i '%s' >/dev/null", appname .. "_server", http.formvalue("id"))) == 0
http_write_json(e)
end
function server_user_log()
local id = http.formvalue("id")
if fs.access("/tmp/etc/passwall_server/" .. id .. ".log") then
local content = luci.sys.exec("cat /tmp/etc/passwall_server/" .. id .. ".log")
content = content:gsub("\n", "<br />")
http.write(content)
else
http.write(string.format("<script>alert('%s');window.close();</script>", i18n.translate("Not enabled log")))
end
end
function server_get_log()
http.write(luci.sys.exec("[ -f '/tmp/log/passwall_server.log' ] && cat /tmp/log/passwall_server.log"))
end
function server_clear_log()
luci.sys.call("echo '' > /tmp/log/passwall_server.log")
end
function app_check()
local json = api.to_check_self()
http_write_json(json)
end
function com_check(comname)
local json = api.to_check("",comname)
http_write_json(json)
end
function com_update(comname)
local json = nil
local task = http.formvalue("task")
if task == "extract" then
json = api.to_extract(comname, http.formvalue("file"), http.formvalue("subfix"))
elseif task == "move" then
json = api.to_move(comname, http.formvalue("file"))
else
json = api.to_download(comname, http.formvalue("url"), http.formvalue("size"))
end
http_write_json(json)
end
function read_rulelist()
local rule_type = http.formvalue("type")
local rule_path
if rule_type == "gfw" then
rule_path = "/usr/share/passwall/rules/gfwlist"
elseif rule_type == "chn" then
rule_path = "/usr/share/passwall/rules/chnlist"
elseif rule_type == "chnroute" then
rule_path = "/usr/share/passwall/rules/chnroute"
else
http.status(400, "Invalid rule type")
return
end
if fs.access(rule_path) then
http.prepare_content("text/plain")
http.write(fs.readfile(rule_path))
end
end
local backup_files = {
"/etc/config/passwall",
"/etc/config/passwall_server",
"/usr/share/passwall/rules/block_host",
"/usr/share/passwall/rules/block_ip",
"/usr/share/passwall/rules/direct_host",
"/usr/share/passwall/rules/direct_ip",
"/usr/share/passwall/rules/proxy_host",
"/usr/share/passwall/rules/proxy_ip"
}
function create_backup()
local date = os.date("%y%m%d%H%M")
local tar_file = "/tmp/passwall-" .. date .. "-backup.tar.gz"
fs.remove(tar_file)
local cmd = "tar -czf " .. tar_file .. " " .. table.concat(backup_files, " ")
luci.sys.call(cmd)
http.header("Content-Disposition", "attachment; filename=passwall-" .. date .. "-backup.tar.gz")
http.header("X-Backup-Filename", "passwall-" .. date .. "-backup.tar.gz")
http.prepare_content("application/octet-stream")
http.write(fs.readfile(tar_file))
fs.remove(tar_file)
end
function restore_backup()
local result = { status = "error", message = "unknown error" }
local ok, err = pcall(function()
local filename = http.formvalue("filename")
local chunk = http.formvalue("chunk")
local chunk_index = tonumber(http.formvalue("chunk_index") or "-1")
local total_chunks = tonumber(http.formvalue("total_chunks") or "-1")
if not filename then
result = { status = "error", message = "Missing filename" }
return
end
if not chunk then
result = { status = "error", message = "Missing chunk data" }
return
end
local file_path = "/tmp/" .. filename
local decoded = nixio.bin.b64decode(chunk)
if not decoded then
result = { status = "error", message = "Base64 decode failed" }
return
end
local fp = io.open(file_path, "a+")
if not fp then
result = { status = "error", message = "Failed to open file: " .. file_path }
return
end
fp:write(decoded)
fp:close()
if chunk_index + 1 == total_chunks then
luci.sys.call("echo '' > /tmp/log/passwall.log")
api.log(" * PassWall 配置文件上传成功…")
local temp_dir = '/tmp/passwall_bak'
luci.sys.call("mkdir -p " .. temp_dir)
if luci.sys.call("tar -xzf " .. file_path .. " -C " .. temp_dir) == 0 then
for _, backup_file in ipairs(backup_files) do
local temp_file = temp_dir .. backup_file
if fs.access(temp_file) then
luci.sys.call("cp -f " .. temp_file .. " " .. backup_file)
end
end
api.log(" * PassWall 配置还原成功…")
api.log(" * 重启 PassWall 服务中…\n")
luci.sys.call('/etc/init.d/passwall restart > /dev/null 2>&1 &')
luci.sys.call('/etc/init.d/passwall_server restart > /dev/null 2>&1 &')
result = { status = "success", message = "Upload completed", path = file_path }
else
api.log(" * PassWall 配置文件解压失败,请重试!")
result = { status = "error", message = "Decompression failed" }
end
luci.sys.call("rm -rf " .. temp_dir)
fs.remove(file_path)
else
result = { status = "success", message = "Chunk received" }
end
end)
if not ok then
result = { status = "error", message = tostring(err) }
end
http_write_json(result)
end
function geo_view()
local action = http.formvalue("action")
local value = http.formvalue("value")
if not value or value == "" then
http.prepare_content("text/plain")
http.write(i18n.translate("Please enter query content!"))
return
end
local geo_dir = (uci:get(appname, "@global_rules[0]", "v2ray_location_asset") or "/usr/share/v2ray/"):match("^(.*)/")
local geosite_path = geo_dir .. "/geosite.dat"
local geoip_path = geo_dir .. "/geoip.dat"
local geo_type, file_path, cmd
local geo_string = ""
if action == "lookup" then
if api.datatypes.ipaddr(value) or api.datatypes.ip6addr(value) then
geo_type, file_path = "geoip", geoip_path
else
geo_type, file_path = "geosite", geosite_path
end
cmd = string.format("geoview -type %s -action lookup -input '%s' -value '%s' -lowmem=true", geo_type, file_path, value)
geo_string = luci.sys.exec(cmd):lower()
if geo_string ~= "" then
local lines = {}
for line in geo_string:gmatch("([^\n]*)\n?") do
if line ~= "" then
table.insert(lines, geo_type .. ":" .. line)
end
end
geo_string = table.concat(lines, "\n")
end
elseif action == "extract" then
local prefix, list = value:match("^(geoip:)(.*)$")
if not prefix then
prefix, list = value:match("^(geosite:)(.*)$")
end
if prefix and list and list ~= "" then
geo_type = prefix:sub(1, -2)
file_path = (geo_type == "geoip") and geoip_path or geosite_path
cmd = string.format("geoview -type %s -action extract -input '%s' -list '%s' -lowmem=true", geo_type, file_path, list)
geo_string = luci.sys.exec(cmd)
end
end
http.prepare_content("text/plain")
if geo_string and geo_string ~="" then
http.write(geo_string)
else
http.write(i18n.translate("No results were found!"))
end
end
function subscribe_del_node()
local remark = http.formvalue("remark")
if remark and remark ~= "" then
luci.sys.call("lua /usr/share/" .. appname .. "/subscribe.lua truncate " .. luci.util.shellquote(remark) .. " > /dev/null 2>&1")
end
http.status(200, "OK")
end
function subscribe_del_all()
luci.sys.call("lua /usr/share/" .. appname .. "/subscribe.lua truncate > /dev/null 2>&1")
http.status(200, "OK")
end
function subscribe_manual()
local section = http.formvalue("section") or ""
local current_url = http.formvalue("url") or ""
if section == "" or current_url == "" then
http_write_json({ success = false, msg = "Missing section or URL, skip." })
return
end
local uci_url = api.sh_uci_get(appname, section, "url")
if not uci_url or uci_url == "" then
http_write_json({ success = false, msg = i18n.translate("Please save and apply before manually subscribing.") })
return
end
if uci_url ~= current_url then
api.sh_uci_set(appname, section, "url", current_url, true)
end
luci.sys.call("lua /usr/share/" .. appname .. "/subscribe.lua start " .. section .. " manual >/dev/null 2>&1 &")
http_write_json({ success = true, msg = "Subscribe triggered." })
end
function subscribe_manual_all()
local sections = http.formvalue("sections") or ""
local urls = http.formvalue("urls") or ""
if sections == "" or urls == "" then
http_write_json({ success = false, msg = "Missing section or URL, skip." })
return
end
local section_list = util.split(sections, ",")
local url_list = util.split(urls, ",")
-- 检查是否存在未保存配置
for i, section in ipairs(section_list) do
local uci_url = api.sh_uci_get(appname, section, "url")
if not uci_url or uci_url == "" then
http_write_json({ success = false, msg = i18n.translate("Please save and apply before manually subscribing.") })
return
end
end
-- 保存有变动的url
for i, section in ipairs(section_list) do
local current_url = url_list[i] or ""
local uci_url = api.sh_uci_get(appname, section, "url")
if current_url ~= "" and uci_url ~= current_url then
api.sh_uci_set(appname, section, "url", current_url, true)
end
end
luci.sys.call("lua /usr/share/" .. appname .. "/subscribe.lua start all manual >/dev/null 2>&1 &")
http_write_json({ success = true, msg = "Subscribe triggered." })
end
|
2951121599/Bili-Insight
| 270,684
|
chrome-extension/scripts/[email protected]
|
// https://d3js.org v6.7.0 Copyright 2021 Mike Bostock
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t="undefined"!=typeof globalThis?globalThis:t||self).d3=t.d3||{})}(this,(function(t){"use strict";function n(t,n){return t<n?-1:t>n?1:t>=n?0:NaN}function e(t){let e=t,r=t;function i(t,n,e,i){for(null==e&&(e=0),null==i&&(i=t.length);e<i;){const o=e+i>>>1;r(t[o],n)<0?e=o+1:i=o}return e}return 1===t.length&&(e=(n,e)=>t(n)-e,r=function(t){return(e,r)=>n(t(e),r)}(t)),{left:i,center:function(t,n,r,o){null==r&&(r=0),null==o&&(o=t.length);const a=i(t,n,r,o-1);return a>r&&e(t[a-1],n)>-e(t[a],n)?a-1:a},right:function(t,n,e,i){for(null==e&&(e=0),null==i&&(i=t.length);e<i;){const o=e+i>>>1;r(t[o],n)>0?i=o:e=o+1}return e}}}function r(t){return null===t?NaN:+t}const i=e(n),o=i.right,a=i.left,u=e(r).center;function c(t,n){let e=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&++e;else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(i=+i)>=i&&++e}return e}function f(t){return 0|t.length}function s(t){return!(t>0)}function l(t){return"object"!=typeof t||"length"in t?t:Array.from(t)}function h(t,n){let e,r=0,i=0,o=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(e=n-i,i+=e/++r,o+=e*(n-i));else{let a=-1;for(let u of t)null!=(u=n(u,++a,t))&&(u=+u)>=u&&(e=u-i,i+=e/++r,o+=e*(u-i))}if(r>1)return o/(r-1)}function d(t,n){const e=h(t,n);return e?Math.sqrt(e):e}function p(t,n){let e,r;if(void 0===n)for(const n of t)null!=n&&(void 0===e?n>=n&&(e=r=n):(e>n&&(e=n),r<n&&(r=n)));else{let i=-1;for(let o of t)null!=(o=n(o,++i,t))&&(void 0===e?o>=o&&(e=r=o):(e>o&&(e=o),r<o&&(r=o)))}return[e,r]}class g{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const n=this._partials;let e=0;for(let r=0;r<this._n&&r<32;r++){const i=n[r],o=t+i,a=Math.abs(t)<Math.abs(i)?t-(o-i):i-(o-t);a&&(n[e++]=a),t=o}return n[e]=t,this._n=e+1,this}valueOf(){const t=this._partials;let n,e,r,i=this._n,o=0;if(i>0){for(o=t[--i];i>0&&(n=o,e=t[--i],o=n+e,r=e-(o-n),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(e=2*r,n=o+e,e==n-o&&(o=n))}return o}}class y extends Map{constructor(t,n=x){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),null!=t)for(const[n,e]of t)this.set(n,e)}get(t){return super.get(_(this,t))}has(t){return super.has(_(this,t))}set(t,n){return super.set(b(this,t),n)}delete(t){return super.delete(m(this,t))}}class v extends Set{constructor(t,n=x){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),null!=t)for(const n of t)this.add(n)}has(t){return super.has(_(this,t))}add(t){return super.add(b(this,t))}delete(t){return super.delete(m(this,t))}}function _({_intern:t,_key:n},e){const r=n(e);return t.has(r)?t.get(r):e}function b({_intern:t,_key:n},e){const r=n(e);return t.has(r)?t.get(r):(t.set(r,e),e)}function m({_intern:t,_key:n},e){const r=n(e);return t.has(r)&&(e=t.get(e),t.delete(r)),e}function x(t){return null!==t&&"object"==typeof t?t.valueOf():t}function w(t){return t}function M(t,...n){return S(t,w,w,n)}function A(t,n,...e){return S(t,w,n,e)}function T(t){if(1!==t.length)throw new Error("duplicate key");return t[0]}function S(t,n,e,r){return function t(i,o){if(o>=r.length)return e(i);const a=new y,u=r[o++];let c=-1;for(const t of i){const n=u(t,++c,i),e=a.get(n);e?e.push(t):a.set(n,[t])}for(const[n,e]of a)a.set(n,t(e,o));return n(a)}(t,0)}function E(t,n){return Array.from(n,(n=>t[n]))}function k(t,...e){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");t=Array.from(t);let[r=n]=e;if(1===r.length||e.length>1){const i=Uint32Array.from(t,((t,n)=>n));return e.length>1?(e=e.map((n=>t.map(n))),i.sort(((t,r)=>{for(const i of e){const e=n(i[t],i[r]);if(e)return e}}))):(r=t.map(r),i.sort(((t,e)=>n(r[t],r[e])))),E(t,i)}return t.sort(r)}var N=Array.prototype.slice;function C(t){return function(){return t}}var P=Math.sqrt(50),z=Math.sqrt(10),D=Math.sqrt(2);function q(t,n,e){var r,i,o,a,u=-1;if(e=+e,(t=+t)===(n=+n)&&e>0)return[t];if((r=n<t)&&(i=t,t=n,n=i),0===(a=R(t,n,e))||!isFinite(a))return[];if(a>0){let e=Math.round(t/a),r=Math.round(n/a);for(e*a<t&&++e,r*a>n&&--r,o=new Array(i=r-e+1);++u<i;)o[u]=(e+u)*a}else{a=-a;let e=Math.round(t*a),r=Math.round(n*a);for(e/a<t&&++e,r/a>n&&--r,o=new Array(i=r-e+1);++u<i;)o[u]=(e+u)/a}return r&&o.reverse(),o}function R(t,n,e){var r=(n-t)/Math.max(0,e),i=Math.floor(Math.log(r)/Math.LN10),o=r/Math.pow(10,i);return i>=0?(o>=P?10:o>=z?5:o>=D?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(o>=P?10:o>=z?5:o>=D?2:1)}function F(t,n,e){var r=Math.abs(n-t)/Math.max(0,e),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),o=r/i;return o>=P?i*=10:o>=z?i*=5:o>=D&&(i*=2),n<t?-i:i}function O(t,n,e){let r;for(;;){const i=R(t,n,e);if(i===r||0===i||!isFinite(i))return[t,n];i>0?(t=Math.floor(t/i)*i,n=Math.ceil(n/i)*i):i<0&&(t=Math.ceil(t*i)/i,n=Math.floor(n*i)/i),r=i}}function I(t){return Math.ceil(Math.log(c(t))/Math.LN2)+1}function U(){var t=w,n=p,e=I;function r(r){Array.isArray(r)||(r=Array.from(r));var i,a,u=r.length,c=new Array(u);for(i=0;i<u;++i)c[i]=t(r[i],i,r);var f=n(c),s=f[0],l=f[1],h=e(c,s,l);if(!Array.isArray(h)){const t=l,e=+h;if(n===p&&([s,l]=O(s,l,e)),(h=q(s,l,e))[h.length-1]>=l)if(t>=l&&n===p){const t=R(s,l,e);isFinite(t)&&(t>0?l=(Math.floor(l/t)+1)*t:t<0&&(l=(Math.ceil(l*-t)+1)/-t))}else h.pop()}for(var d=h.length;h[0]<=s;)h.shift(),--d;for(;h[d-1]>l;)h.pop(),--d;var g,y=new Array(d+1);for(i=0;i<=d;++i)(g=y[i]=[]).x0=i>0?h[i-1]:s,g.x1=i<d?h[i]:l;for(i=0;i<u;++i)s<=(a=c[i])&&a<=l&&y[o(h,a,0,d)].push(r[i]);return y}return r.value=function(n){return arguments.length?(t="function"==typeof n?n:C(n),r):t},r.domain=function(t){return arguments.length?(n="function"==typeof t?t:C([t[0],t[1]]),r):n},r.thresholds=function(t){return arguments.length?(e="function"==typeof t?t:Array.isArray(t)?C(N.call(t)):C(t),r):e},r}function B(t,n){let e;if(void 0===n)for(const n of t)null!=n&&(e<n||void 0===e&&n>=n)&&(e=n);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(e<i||void 0===e&&i>=i)&&(e=i)}return e}function Y(t,n){let e;if(void 0===n)for(const n of t)null!=n&&(e>n||void 0===e&&n>=n)&&(e=n);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(e>i||void 0===e&&i>=i)&&(e=i)}return e}function L(t,e,r=0,i=t.length-1,o=n){for(;i>r;){if(i-r>600){const n=i-r+1,a=e-r+1,u=Math.log(n),c=.5*Math.exp(2*u/3),f=.5*Math.sqrt(u*c*(n-c)/n)*(a-n/2<0?-1:1);L(t,e,Math.max(r,Math.floor(e-a*c/n+f)),Math.min(i,Math.floor(e+(n-a)*c/n+f)),o)}const n=t[e];let a=r,u=i;for(j(t,r,e),o(t[i],n)>0&&j(t,r,i);a<u;){for(j(t,a,u),++a,--u;o(t[a],n)<0;)++a;for(;o(t[u],n)>0;)--u}0===o(t[r],n)?j(t,r,u):(++u,j(t,u,i)),u<=e&&(r=u+1),e<=u&&(i=u-1)}return t}function j(t,n,e){const r=t[n];t[n]=t[e],t[e]=r}function H(t,n,e){if(r=(t=Float64Array.from(function*(t,n){if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(yield n);else{let e=-1;for(let r of t)null!=(r=n(r,++e,t))&&(r=+r)>=r&&(yield r)}}(t,e))).length){if((n=+n)<=0||r<2)return Y(t);if(n>=1)return B(t);var r,i=(r-1)*n,o=Math.floor(i),a=B(L(t,o).subarray(0,o+1));return a+(Y(t.subarray(o+1))-a)*(i-o)}}function X(t,n,e=r){if(i=t.length){if((n=+n)<=0||i<2)return+e(t[0],0,t);if(n>=1)return+e(t[i-1],i-1,t);var i,o=(i-1)*n,a=Math.floor(o),u=+e(t[a],a,t);return u+(+e(t[a+1],a+1,t)-u)*(o-a)}}function G(t,n){let e,r=-1,i=-1;if(void 0===n)for(const n of t)++i,null!=n&&(e<n||void 0===e&&n>=n)&&(e=n,r=i);else for(let o of t)null!=(o=n(o,++i,t))&&(e<o||void 0===e&&o>=o)&&(e=o,r=i);return r}function V(t){return Array.from(function*(t){for(const n of t)yield*n}(t))}function $(t,n){let e,r=-1,i=-1;if(void 0===n)for(const n of t)++i,null!=n&&(e>n||void 0===e&&n>=n)&&(e=n,r=i);else for(let o of t)null!=(o=n(o,++i,t))&&(e>o||void 0===e&&o>=o)&&(e=o,r=i);return r}function W(t,n){return[t,n]}function Z(t,n,e){t=+t,n=+n,e=(i=arguments.length)<2?(n=t,t=0,1):i<3?1:+e;for(var r=-1,i=0|Math.max(0,Math.ceil((n-t)/e)),o=new Array(i);++r<i;)o[r]=t+r*e;return o}function K(t,e=n){if(1===e.length)return $(t,e);let r,i=-1,o=-1;for(const n of t)++o,(i<0?0===e(n,n):e(n,r)<0)&&(r=n,i=o);return i}var Q=J(Math.random);function J(t){return function(n,e=0,r=n.length){let i=r-(e=+e);for(;i;){const r=t()*i--|0,o=n[i+e];n[i+e]=n[r+e],n[r+e]=o}return n}}function tt(t){if(!(i=t.length))return[];for(var n=-1,e=Y(t,nt),r=new Array(e);++n<e;)for(var i,o=-1,a=r[n]=new Array(i);++o<i;)a[o]=t[o][n];return r}function nt(t){return t.length}function et(t){return t instanceof Set?t:new Set(t)}function rt(t,n){const e=t[Symbol.iterator](),r=new Set;for(const t of n){if(r.has(t))continue;let n,i;for(;({value:n,done:i}=e.next());){if(i)return!1;if(r.add(n),Object.is(t,n))break}}return!0}var it=Array.prototype.slice;function ot(t){return t}var at=1e-6;function ut(t){return"translate("+t+",0)"}function ct(t){return"translate(0,"+t+")"}function ft(t){return n=>+t(n)}function st(t,n){return n=Math.max(0,t.bandwidth()-2*n)/2,t.round()&&(n=Math.round(n)),e=>+t(e)+n}function lt(){return!this.__axis}function ht(t,n){var e=[],r=null,i=null,o=6,a=6,u=3,c="undefined"!=typeof window&&window.devicePixelRatio>1?0:.5,f=1===t||4===t?-1:1,s=4===t||2===t?"x":"y",l=1===t||3===t?ut:ct;function h(h){var d=null==r?n.ticks?n.ticks.apply(n,e):n.domain():r,p=null==i?n.tickFormat?n.tickFormat.apply(n,e):ot:i,g=Math.max(o,0)+u,y=n.range(),v=+y[0]+c,_=+y[y.length-1]+c,b=(n.bandwidth?st:ft)(n.copy(),c),m=h.selection?h.selection():h,x=m.selectAll(".domain").data([null]),w=m.selectAll(".tick").data(d,n).order(),M=w.exit(),A=w.enter().append("g").attr("class","tick"),T=w.select("line"),S=w.select("text");x=x.merge(x.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),w=w.merge(A),T=T.merge(A.append("line").attr("stroke","currentColor").attr(s+"2",f*o)),S=S.merge(A.append("text").attr("fill","currentColor").attr(s,f*g).attr("dy",1===t?"0em":3===t?"0.71em":"0.32em")),h!==m&&(x=x.transition(h),w=w.transition(h),T=T.transition(h),S=S.transition(h),M=M.transition(h).attr("opacity",at).attr("transform",(function(t){return isFinite(t=b(t))?l(t+c):this.getAttribute("transform")})),A.attr("opacity",at).attr("transform",(function(t){var n=this.parentNode.__axis;return l((n&&isFinite(n=n(t))?n:b(t))+c)}))),M.remove(),x.attr("d",4===t||2===t?a?"M"+f*a+","+v+"H"+c+"V"+_+"H"+f*a:"M"+c+","+v+"V"+_:a?"M"+v+","+f*a+"V"+c+"H"+_+"V"+f*a:"M"+v+","+c+"H"+_),w.attr("opacity",1).attr("transform",(function(t){return l(b(t)+c)})),T.attr(s+"2",f*o),S.attr(s,f*g).text(p),m.filter(lt).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",2===t?"start":4===t?"end":"middle"),m.each((function(){this.__axis=b}))}return h.scale=function(t){return arguments.length?(n=t,h):n},h.ticks=function(){return e=it.call(arguments),h},h.tickArguments=function(t){return arguments.length?(e=null==t?[]:it.call(t),h):e.slice()},h.tickValues=function(t){return arguments.length?(r=null==t?null:it.call(t),h):r&&r.slice()},h.tickFormat=function(t){return arguments.length?(i=t,h):i},h.tickSize=function(t){return arguments.length?(o=a=+t,h):o},h.tickSizeInner=function(t){return arguments.length?(o=+t,h):o},h.tickSizeOuter=function(t){return arguments.length?(a=+t,h):a},h.tickPadding=function(t){return arguments.length?(u=+t,h):u},h.offset=function(t){return arguments.length?(c=+t,h):c},h}var dt={value:()=>{}};function pt(){for(var t,n=0,e=arguments.length,r={};n<e;++n){if(!(t=arguments[n]+"")||t in r||/[\s.]/.test(t))throw new Error("illegal type: "+t);r[t]=[]}return new gt(r)}function gt(t){this._=t}function yt(t,n){return t.trim().split(/^|\s+/).map((function(t){var e="",r=t.indexOf(".");if(r>=0&&(e=t.slice(r+1),t=t.slice(0,r)),t&&!n.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}}))}function vt(t,n){for(var e,r=0,i=t.length;r<i;++r)if((e=t[r]).name===n)return e.value}function _t(t,n,e){for(var r=0,i=t.length;r<i;++r)if(t[r].name===n){t[r]=dt,t=t.slice(0,r).concat(t.slice(r+1));break}return null!=e&&t.push({name:n,value:e}),t}gt.prototype=pt.prototype={constructor:gt,on:function(t,n){var e,r=this._,i=yt(t+"",r),o=-1,a=i.length;if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++o<a;)if(e=(t=i[o]).type)r[e]=_t(r[e],t.name,n);else if(null==n)for(e in r)r[e]=_t(r[e],t.name,null);return this}for(;++o<a;)if((e=(t=i[o]).type)&&(e=vt(r[e],t.name)))return e},copy:function(){var t={},n=this._;for(var e in n)t[e]=n[e].slice();return new gt(t)},call:function(t,n){if((e=arguments.length-2)>0)for(var e,r,i=new Array(e),o=0;o<e;++o)i[o]=arguments[o+2];if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(o=0,e=(r=this._[t]).length;o<e;++o)r[o].value.apply(n,i)},apply:function(t,n,e){if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(var r=this._[t],i=0,o=r.length;i<o;++i)r[i].value.apply(n,e)}};var bt="http://www.w3.org/1999/xhtml",mt={svg:"http://www.w3.org/2000/svg",xhtml:bt,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function xt(t){var n=t+="",e=n.indexOf(":");return e>=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),mt.hasOwnProperty(n)?{space:mt[n],local:t}:t}function wt(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===bt&&n.documentElement.namespaceURI===bt?n.createElement(t):n.createElementNS(e,t)}}function Mt(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function At(t){var n=xt(t);return(n.local?Mt:wt)(n)}function Tt(){}function St(t){return null==t?Tt:function(){return this.querySelector(t)}}function Et(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function kt(){return[]}function Nt(t){return null==t?kt:function(){return this.querySelectorAll(t)}}function Ct(t){return function(){return this.matches(t)}}function Pt(t){return function(n){return n.matches(t)}}var zt=Array.prototype.find;function Dt(){return this.firstElementChild}var qt=Array.prototype.filter;function Rt(){return this.children}function Ft(t){return new Array(t.length)}function Ot(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function It(t){return function(){return t}}function Ut(t,n,e,r,i,o){for(var a,u=0,c=n.length,f=o.length;u<f;++u)(a=n[u])?(a.__data__=o[u],r[u]=a):e[u]=new Ot(t,o[u]);for(;u<c;++u)(a=n[u])&&(i[u]=a)}function Bt(t,n,e,r,i,o,a){var u,c,f,s=new Map,l=n.length,h=o.length,d=new Array(l);for(u=0;u<l;++u)(c=n[u])&&(d[u]=f=a.call(c,c.__data__,u,n)+"",s.has(f)?i[u]=c:s.set(f,c));for(u=0;u<h;++u)f=a.call(t,o[u],u,o)+"",(c=s.get(f))?(r[u]=c,c.__data__=o[u],s.delete(f)):e[u]=new Ot(t,o[u]);for(u=0;u<l;++u)(c=n[u])&&s.get(d[u])===c&&(i[u]=c)}function Yt(t){return t.__data__}function Lt(t,n){return t<n?-1:t>n?1:t>=n?0:NaN}function jt(t){return function(){this.removeAttribute(t)}}function Ht(t){return function(){this.removeAttributeNS(t.space,t.local)}}function Xt(t,n){return function(){this.setAttribute(t,n)}}function Gt(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function Vt(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function $t(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function Wt(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function Zt(t){return function(){this.style.removeProperty(t)}}function Kt(t,n,e){return function(){this.style.setProperty(t,n,e)}}function Qt(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function Jt(t,n){return t.style.getPropertyValue(n)||Wt(t).getComputedStyle(t,null).getPropertyValue(n)}function tn(t){return function(){delete this[t]}}function nn(t,n){return function(){this[t]=n}}function en(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function rn(t){return t.trim().split(/^|\s+/)}function on(t){return t.classList||new an(t)}function an(t){this._node=t,this._names=rn(t.getAttribute("class")||"")}function un(t,n){for(var e=on(t),r=-1,i=n.length;++r<i;)e.add(n[r])}function cn(t,n){for(var e=on(t),r=-1,i=n.length;++r<i;)e.remove(n[r])}function fn(t){return function(){un(this,t)}}function sn(t){return function(){cn(this,t)}}function ln(t,n){return function(){(n.apply(this,arguments)?un:cn)(this,t)}}function hn(){this.textContent=""}function dn(t){return function(){this.textContent=t}}function pn(t){return function(){var n=t.apply(this,arguments);this.textContent=null==n?"":n}}function gn(){this.innerHTML=""}function yn(t){return function(){this.innerHTML=t}}function vn(t){return function(){var n=t.apply(this,arguments);this.innerHTML=null==n?"":n}}function _n(){this.nextSibling&&this.parentNode.appendChild(this)}function bn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function mn(){return null}function xn(){var t=this.parentNode;t&&t.removeChild(this)}function wn(){var t=this.cloneNode(!1),n=this.parentNode;return n?n.insertBefore(t,this.nextSibling):t}function Mn(){var t=this.cloneNode(!0),n=this.parentNode;return n?n.insertBefore(t,this.nextSibling):t}function An(t){return t.trim().split(/^|\s+/).map((function(t){var n="",e=t.indexOf(".");return e>=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}function Tn(t){return function(){var n=this.__on;if(n){for(var e,r=0,i=-1,o=n.length;r<o;++r)e=n[r],t.type&&e.type!==t.type||e.name!==t.name?n[++i]=e:this.removeEventListener(e.type,e.listener,e.options);++i?n.length=i:delete this.__on}}}function Sn(t,n,e){return function(){var r,i=this.__on,o=function(t){return function(n){t.call(this,n,this.__data__)}}(n);if(i)for(var a=0,u=i.length;a<u;++a)if((r=i[a]).type===t.type&&r.name===t.name)return this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=o,r.options=e),void(r.value=n);this.addEventListener(t.type,o,e),r={type:t.type,name:t.name,value:n,listener:o,options:e},i?i.push(r):this.__on=[r]}}function En(t,n,e){var r=Wt(t),i=r.CustomEvent;"function"==typeof i?i=new i(n,e):(i=r.document.createEvent("Event"),e?(i.initEvent(n,e.bubbles,e.cancelable),i.detail=e.detail):i.initEvent(n,!1,!1)),t.dispatchEvent(i)}function kn(t,n){return function(){return En(this,t,n)}}function Nn(t,n){return function(){return En(this,t,n.apply(this,arguments))}}Ot.prototype={constructor:Ot,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,n){return this._parent.insertBefore(t,n)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}},an.prototype={add:function(t){this._names.indexOf(t)<0&&(this._names.push(t),this._node.setAttribute("class",this._names.join(" ")))},remove:function(t){var n=this._names.indexOf(t);n>=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Cn=[null];function Pn(t,n){this._groups=t,this._parents=n}function zn(){return new Pn([[document.documentElement]],Cn)}function Dn(t){return"string"==typeof t?new Pn([[document.querySelector(t)]],[document.documentElement]):new Pn([[t]],Cn)}Pn.prototype=zn.prototype={constructor:Pn,select:function(t){"function"!=typeof t&&(t=St(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i<e;++i)for(var o,a,u=n[i],c=u.length,f=r[i]=new Array(c),s=0;s<c;++s)(o=u[s])&&(a=t.call(o,o.__data__,s,u))&&("__data__"in o&&(a.__data__=o.__data__),f[s]=a);return new Pn(r,this._parents)},selectAll:function(t){t="function"==typeof t?function(t){return function(){var n=t.apply(this,arguments);return null==n?[]:Et(n)}}(t):Nt(t);for(var n=this._groups,e=n.length,r=[],i=[],o=0;o<e;++o)for(var a,u=n[o],c=u.length,f=0;f<c;++f)(a=u[f])&&(r.push(t.call(a,a.__data__,f,u)),i.push(a));return new Pn(r,i)},selectChild:function(t){return this.select(null==t?Dt:function(t){return function(){return zt.call(this.children,t)}}("function"==typeof t?t:Pt(t)))},selectChildren:function(t){return this.selectAll(null==t?Rt:function(t){return function(){return qt.call(this.children,t)}}("function"==typeof t?t:Pt(t)))},filter:function(t){"function"!=typeof t&&(t=Ct(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i<e;++i)for(var o,a=n[i],u=a.length,c=r[i]=[],f=0;f<u;++f)(o=a[f])&&t.call(o,o.__data__,f,a)&&c.push(o);return new Pn(r,this._parents)},data:function(t,n){if(!arguments.length)return Array.from(this,Yt);var e=n?Bt:Ut,r=this._parents,i=this._groups;"function"!=typeof t&&(t=It(t));for(var o=i.length,a=new Array(o),u=new Array(o),c=new Array(o),f=0;f<o;++f){var s=r[f],l=i[f],h=l.length,d=Et(t.call(s,s&&s.__data__,f,r)),p=d.length,g=u[f]=new Array(p),y=a[f]=new Array(p),v=c[f]=new Array(h);e(s,l,g,y,v,d,n);for(var _,b,m=0,x=0;m<p;++m)if(_=g[m]){for(m>=x&&(x=m+1);!(b=y[x])&&++x<p;);_._next=b||null}}return(a=new Pn(a,r))._enter=u,a._exit=c,a},enter:function(){return new Pn(this._enter||this._groups.map(Ft),this._parents)},exit:function(){return new Pn(this._exit||this._groups.map(Ft),this._parents)},join:function(t,n,e){var r=this.enter(),i=this,o=this.exit();return r="function"==typeof t?t(r):r.append(t+""),null!=n&&(i=n(i)),null==e?o.remove():e(o),r&&i?r.merge(i).order():i},merge:function(t){if(!(t instanceof Pn))throw new Error("invalid merge");for(var n=this._groups,e=t._groups,r=n.length,i=e.length,o=Math.min(r,i),a=new Array(r),u=0;u<o;++u)for(var c,f=n[u],s=e[u],l=f.length,h=a[u]=new Array(l),d=0;d<l;++d)(c=f[d]||s[d])&&(h[d]=c);for(;u<r;++u)a[u]=n[u];return new Pn(a,this._parents)},selection:function(){return this},order:function(){for(var t=this._groups,n=-1,e=t.length;++n<e;)for(var r,i=t[n],o=i.length-1,a=i[o];--o>=0;)(r=i[o])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=Lt);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o<r;++o){for(var a,u=e[o],c=u.length,f=i[o]=new Array(c),s=0;s<c;++s)(a=u[s])&&(f[s]=a);f.sort(n)}return new Pn(i,this._parents).order()},call:function(){var t=arguments[0];return arguments[0]=this,t.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var t=this._groups,n=0,e=t.length;n<e;++n)for(var r=t[n],i=0,o=r.length;i<o;++i){var a=r[i];if(a)return a}return null},size:function(){let t=0;for(const n of this)++t;return t},empty:function(){return!this.node()},each:function(t){for(var n=this._groups,e=0,r=n.length;e<r;++e)for(var i,o=n[e],a=0,u=o.length;a<u;++a)(i=o[a])&&t.call(i,i.__data__,a,o);return this},attr:function(t,n){var e=xt(t);if(arguments.length<2){var r=this.node();return e.local?r.getAttributeNS(e.space,e.local):r.getAttribute(e)}return this.each((null==n?e.local?Ht:jt:"function"==typeof n?e.local?$t:Vt:e.local?Gt:Xt)(e,n))},style:function(t,n,e){return arguments.length>1?this.each((null==n?Zt:"function"==typeof n?Qt:Kt)(t,n,null==e?"":e)):Jt(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?tn:"function"==typeof n?en:nn)(t,n)):this.node()[t]},classed:function(t,n){var e=rn(t+"");if(arguments.length<2){for(var r=on(this.node()),i=-1,o=e.length;++i<o;)if(!r.contains(e[i]))return!1;return!0}return this.each(("function"==typeof n?ln:n?fn:sn)(e,n))},text:function(t){return arguments.length?this.each(null==t?hn:("function"==typeof t?pn:dn)(t)):this.node().textContent},html:function(t){return arguments.length?this.each(null==t?gn:("function"==typeof t?vn:yn)(t)):this.node().innerHTML},raise:function(){return this.each(_n)},lower:function(){return this.each(bn)},append:function(t){var n="function"==typeof t?t:At(t);return this.select((function(){return this.appendChild(n.apply(this,arguments))}))},insert:function(t,n){var e="function"==typeof t?t:At(t),r=null==n?mn:"function"==typeof n?n:St(n);return this.select((function(){return this.insertBefore(e.apply(this,arguments),r.apply(this,arguments)||null)}))},remove:function(){return this.each(xn)},clone:function(t){return this.select(t?Mn:wn)},datum:function(t){return arguments.length?this.property("__data__",t):this.node().__data__},on:function(t,n,e){var r,i,o=An(t+""),a=o.length;if(!(arguments.length<2)){for(u=n?Sn:Tn,r=0;r<a;++r)this.each(u(o[r],n,e));return this}var u=this.node().__on;if(u)for(var c,f=0,s=u.length;f<s;++f)for(r=0,c=u[f];r<a;++r)if((i=o[r]).type===c.type&&i.name===c.name)return c.value},dispatch:function(t,n){return this.each(("function"==typeof n?Nn:kn)(t,n))},[Symbol.iterator]:function*(){for(var t=this._groups,n=0,e=t.length;n<e;++n)for(var r,i=t[n],o=0,a=i.length;o<a;++o)(r=i[o])&&(yield r)}};var qn=0;function Rn(){return new Fn}function Fn(){this._="@"+(++qn).toString(36)}function On(t){let n;for(;n=t.sourceEvent;)t=n;return t}function In(t,n){if(t=On(t),void 0===n&&(n=t.currentTarget),n){var e=n.ownerSVGElement||n;if(e.createSVGPoint){var r=e.createSVGPoint();return r.x=t.clientX,r.y=t.clientY,[(r=r.matrixTransform(n.getScreenCTM().inverse())).x,r.y]}if(n.getBoundingClientRect){var i=n.getBoundingClientRect();return[t.clientX-i.left-n.clientLeft,t.clientY-i.top-n.clientTop]}}return[t.pageX,t.pageY]}function Un(t){t.stopImmediatePropagation()}function Bn(t){t.preventDefault(),t.stopImmediatePropagation()}function Yn(t){var n=t.document.documentElement,e=Dn(t).on("dragstart.drag",Bn,!0);"onselectstart"in n?e.on("selectstart.drag",Bn,!0):(n.__noselect=n.style.MozUserSelect,n.style.MozUserSelect="none")}function Ln(t,n){var e=t.document.documentElement,r=Dn(t).on("dragstart.drag",null);n&&(r.on("click.drag",Bn,!0),setTimeout((function(){r.on("click.drag",null)}),0)),"onselectstart"in e?r.on("selectstart.drag",null):(e.style.MozUserSelect=e.__noselect,delete e.__noselect)}Fn.prototype=Rn.prototype={constructor:Fn,get:function(t){for(var n=this._;!(n in t);)if(!(t=t.parentNode))return;return t[n]},set:function(t,n){return t[this._]=n},remove:function(t){return this._ in t&&delete t[this._]},toString:function(){return this._}};var jn=t=>()=>t;function Hn(t,{sourceEvent:n,subject:e,target:r,identifier:i,active:o,x:a,y:u,dx:c,dy:f,dispatch:s}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},subject:{value:e,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:u,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:f,enumerable:!0,configurable:!0},_:{value:s}})}function Xn(t){return!t.ctrlKey&&!t.button}function Gn(){return this.parentNode}function Vn(t,n){return null==n?{x:t.x,y:t.y}:n}function $n(){return navigator.maxTouchPoints||"ontouchstart"in this}function Wn(t,n,e){t.prototype=n.prototype=e,e.constructor=t}function Zn(t,n){var e=Object.create(t.prototype);for(var r in n)e[r]=n[r];return e}function Kn(){}Hn.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t};var Qn=.7,Jn=1/Qn,te="\\s*([+-]?\\d+)\\s*",ne="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",ee="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",re=/^#([0-9a-f]{3,8})$/,ie=new RegExp("^rgb\\("+[te,te,te]+"\\)$"),oe=new RegExp("^rgb\\("+[ee,ee,ee]+"\\)$"),ae=new RegExp("^rgba\\("+[te,te,te,ne]+"\\)$"),ue=new RegExp("^rgba\\("+[ee,ee,ee,ne]+"\\)$"),ce=new RegExp("^hsl\\("+[ne,ee,ee]+"\\)$"),fe=new RegExp("^hsla\\("+[ne,ee,ee,ne]+"\\)$"),se={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function le(){return this.rgb().formatHex()}function he(){return this.rgb().formatRgb()}function de(t){var n,e;return t=(t+"").trim().toLowerCase(),(n=re.exec(t))?(e=n[1].length,n=parseInt(n[1],16),6===e?pe(n):3===e?new _e(n>>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?ge(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?ge(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=ie.exec(t))?new _e(n[1],n[2],n[3],1):(n=oe.exec(t))?new _e(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=ae.exec(t))?ge(n[1],n[2],n[3],n[4]):(n=ue.exec(t))?ge(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=ce.exec(t))?we(n[1],n[2]/100,n[3]/100,1):(n=fe.exec(t))?we(n[1],n[2]/100,n[3]/100,n[4]):se.hasOwnProperty(t)?pe(se[t]):"transparent"===t?new _e(NaN,NaN,NaN,0):null}function pe(t){return new _e(t>>16&255,t>>8&255,255&t,1)}function ge(t,n,e,r){return r<=0&&(t=n=e=NaN),new _e(t,n,e,r)}function ye(t){return t instanceof Kn||(t=de(t)),t?new _e((t=t.rgb()).r,t.g,t.b,t.opacity):new _e}function ve(t,n,e,r){return 1===arguments.length?ye(t):new _e(t,n,e,null==r?1:r)}function _e(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function be(){return"#"+xe(this.r)+xe(this.g)+xe(this.b)}function me(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function xe(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function we(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Te(t,n,e,r)}function Me(t){if(t instanceof Te)return new Te(t.h,t.s,t.l,t.opacity);if(t instanceof Kn||(t=de(t)),!t)return new Te;if(t instanceof Te)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),a=NaN,u=o-i,c=(o+i)/2;return u?(a=n===o?(e-r)/u+6*(e<r):e===o?(r-n)/u+2:(n-e)/u+4,u/=c<.5?o+i:2-o-i,a*=60):u=c>0&&c<1?0:a,new Te(a,u,c,t.opacity)}function Ae(t,n,e,r){return 1===arguments.length?Me(t):new Te(t,n,e,null==r?1:r)}function Te(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Se(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}Wn(Kn,de,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:le,formatHex:le,formatHsl:function(){return Me(this).formatHsl()},formatRgb:he,toString:he}),Wn(_e,ve,Zn(Kn,{brighter:function(t){return t=null==t?Jn:Math.pow(Jn,t),new _e(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?Qn:Math.pow(Qn,t),new _e(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:be,formatHex:be,formatRgb:me,toString:me})),Wn(Te,Ae,Zn(Kn,{brighter:function(t){return t=null==t?Jn:Math.pow(Jn,t),new Te(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?Qn:Math.pow(Qn,t),new Te(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new _e(Se(t>=240?t-240:t+120,i,r),Se(t,i,r),Se(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));const Ee=Math.PI/180,ke=180/Math.PI,Ne=.96422,Ce=.82521,Pe=4/29,ze=6/29,De=3*ze*ze;function qe(t){if(t instanceof Fe)return new Fe(t.l,t.a,t.b,t.opacity);if(t instanceof je)return He(t);t instanceof _e||(t=ye(t));var n,e,r=Be(t.r),i=Be(t.g),o=Be(t.b),a=Oe((.2225045*r+.7168786*i+.0606169*o)/1);return r===i&&i===o?n=e=a:(n=Oe((.4360747*r+.3850649*i+.1430804*o)/Ne),e=Oe((.0139322*r+.0971045*i+.7141733*o)/Ce)),new Fe(116*a-16,500*(n-a),200*(a-e),t.opacity)}function Re(t,n,e,r){return 1===arguments.length?qe(t):new Fe(t,n,e,null==r?1:r)}function Fe(t,n,e,r){this.l=+t,this.a=+n,this.b=+e,this.opacity=+r}function Oe(t){return t>.008856451679035631?Math.pow(t,1/3):t/De+Pe}function Ie(t){return t>ze?t*t*t:De*(t-Pe)}function Ue(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function Be(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Ye(t){if(t instanceof je)return new je(t.h,t.c,t.l,t.opacity);if(t instanceof Fe||(t=qe(t)),0===t.a&&0===t.b)return new je(NaN,0<t.l&&t.l<100?0:NaN,t.l,t.opacity);var n=Math.atan2(t.b,t.a)*ke;return new je(n<0?n+360:n,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function Le(t,n,e,r){return 1===arguments.length?Ye(t):new je(t,n,e,null==r?1:r)}function je(t,n,e,r){this.h=+t,this.c=+n,this.l=+e,this.opacity=+r}function He(t){if(isNaN(t.h))return new Fe(t.l,0,0,t.opacity);var n=t.h*Ee;return new Fe(t.l,Math.cos(n)*t.c,Math.sin(n)*t.c,t.opacity)}Wn(Fe,Re,Zn(Kn,{brighter:function(t){return new Fe(this.l+18*(null==t?1:t),this.a,this.b,this.opacity)},darker:function(t){return new Fe(this.l-18*(null==t?1:t),this.a,this.b,this.opacity)},rgb:function(){var t=(this.l+16)/116,n=isNaN(this.a)?t:t+this.a/500,e=isNaN(this.b)?t:t-this.b/200;return new _e(Ue(3.1338561*(n=Ne*Ie(n))-1.6168667*(t=1*Ie(t))-.4906146*(e=Ce*Ie(e))),Ue(-.9787684*n+1.9161415*t+.033454*e),Ue(.0719453*n-.2289914*t+1.4052427*e),this.opacity)}})),Wn(je,Le,Zn(Kn,{brighter:function(t){return new je(this.h,this.c,this.l+18*(null==t?1:t),this.opacity)},darker:function(t){return new je(this.h,this.c,this.l-18*(null==t?1:t),this.opacity)},rgb:function(){return He(this).rgb()}}));var Xe=-.14861,Ge=1.78277,Ve=-.29227,$e=-.90649,We=1.97294,Ze=We*$e,Ke=We*Ge,Qe=Ge*Ve-$e*Xe;function Je(t){if(t instanceof nr)return new nr(t.h,t.s,t.l,t.opacity);t instanceof _e||(t=ye(t));var n=t.r/255,e=t.g/255,r=t.b/255,i=(Qe*r+Ze*n-Ke*e)/(Qe+Ze-Ke),o=r-i,a=(We*(e-i)-Ve*o)/$e,u=Math.sqrt(a*a+o*o)/(We*i*(1-i)),c=u?Math.atan2(a,o)*ke-120:NaN;return new nr(c<0?c+360:c,u,i,t.opacity)}function tr(t,n,e,r){return 1===arguments.length?Je(t):new nr(t,n,e,null==r?1:r)}function nr(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function er(t,n,e,r,i){var o=t*t,a=o*t;return((1-3*t+3*o-a)*n+(4-6*o+3*a)*e+(1+3*t+3*o-3*a)*r+a*i)/6}function rr(t){var n=t.length-1;return function(e){var r=e<=0?e=0:e>=1?(e=1,n-1):Math.floor(e*n),i=t[r],o=t[r+1],a=r>0?t[r-1]:2*i-o,u=r<n-1?t[r+2]:2*o-i;return er((e-r/n)*n,a,i,o,u)}}function ir(t){var n=t.length;return function(e){var r=Math.floor(((e%=1)<0?++e:e)*n),i=t[(r+n-1)%n],o=t[r%n],a=t[(r+1)%n],u=t[(r+2)%n];return er((e-r/n)*n,i,o,a,u)}}Wn(nr,tr,Zn(Kn,{brighter:function(t){return t=null==t?Jn:Math.pow(Jn,t),new nr(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?Qn:Math.pow(Qn,t),new nr(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*Ee,n=+this.l,e=isNaN(this.s)?0:this.s*n*(1-n),r=Math.cos(t),i=Math.sin(t);return new _e(255*(n+e*(Xe*r+Ge*i)),255*(n+e*(Ve*r+$e*i)),255*(n+e*(We*r)),this.opacity)}}));var or=t=>()=>t;function ar(t,n){return function(e){return t+e*n}}function ur(t,n){var e=n-t;return e?ar(t,e>180||e<-180?e-360*Math.round(e/360):e):or(isNaN(t)?n:t)}function cr(t){return 1==(t=+t)?fr:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):or(isNaN(n)?e:n)}}function fr(t,n){var e=n-t;return e?ar(t,e):or(isNaN(t)?n:t)}var sr=function t(n){var e=cr(n);function r(t,n){var r=e((t=ve(t)).r,(n=ve(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),a=fr(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=a(n),t+""}}return r.gamma=t,r}(1);function lr(t){return function(n){var e,r,i=n.length,o=new Array(i),a=new Array(i),u=new Array(i);for(e=0;e<i;++e)r=ve(n[e]),o[e]=r.r||0,a[e]=r.g||0,u[e]=r.b||0;return o=t(o),a=t(a),u=t(u),r.opacity=1,function(t){return r.r=o(t),r.g=a(t),r.b=u(t),r+""}}}var hr=lr(rr),dr=lr(ir);function pr(t,n){n||(n=[]);var e,r=t?Math.min(n.length,t.length):0,i=n.slice();return function(o){for(e=0;e<r;++e)i[e]=t[e]*(1-o)+n[e]*o;return i}}function gr(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function yr(t,n){var e,r=n?n.length:0,i=t?Math.min(r,t.length):0,o=new Array(i),a=new Array(r);for(e=0;e<i;++e)o[e]=Mr(t[e],n[e]);for(;e<r;++e)a[e]=n[e];return function(t){for(e=0;e<i;++e)a[e]=o[e](t);return a}}function vr(t,n){var e=new Date;return t=+t,n=+n,function(r){return e.setTime(t*(1-r)+n*r),e}}function _r(t,n){return t=+t,n=+n,function(e){return t*(1-e)+n*e}}function br(t,n){var e,r={},i={};for(e in null!==t&&"object"==typeof t||(t={}),null!==n&&"object"==typeof n||(n={}),n)e in t?r[e]=Mr(t[e],n[e]):i[e]=n[e];return function(t){for(e in r)i[e]=r[e](t);return i}}var mr=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,xr=new RegExp(mr.source,"g");function wr(t,n){var e,r,i,o=mr.lastIndex=xr.lastIndex=0,a=-1,u=[],c=[];for(t+="",n+="";(e=mr.exec(t))&&(r=xr.exec(n));)(i=r.index)>o&&(i=n.slice(o,i),u[a]?u[a]+=i:u[++a]=i),(e=e[0])===(r=r[0])?u[a]?u[a]+=r:u[++a]=r:(u[++a]=null,c.push({i:a,x:_r(e,r)})),o=xr.lastIndex;return o<n.length&&(i=n.slice(o),u[a]?u[a]+=i:u[++a]=i),u.length<2?c[0]?function(t){return function(n){return t(n)+""}}(c[0].x):function(t){return function(){return t}}(n):(n=c.length,function(t){for(var e,r=0;r<n;++r)u[(e=c[r]).i]=e.x(t);return u.join("")})}function Mr(t,n){var e,r=typeof n;return null==n||"boolean"===r?or(n):("number"===r?_r:"string"===r?(e=de(n))?(n=e,sr):wr:n instanceof de?sr:n instanceof Date?vr:gr(n)?pr:Array.isArray(n)?yr:"function"!=typeof n.valueOf&&"function"!=typeof n.toString||isNaN(n)?br:_r)(t,n)}function Ar(t,n){return t=+t,n=+n,function(e){return Math.round(t*(1-e)+n*e)}}var Tr,Sr=180/Math.PI,Er={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function kr(t,n,e,r,i,o){var a,u,c;return(a=Math.sqrt(t*t+n*n))&&(t/=a,n/=a),(c=t*e+n*r)&&(e-=t*c,r-=n*c),(u=Math.sqrt(e*e+r*r))&&(e/=u,r/=u,c/=u),t*r<n*e&&(t=-t,n=-n,c=-c,a=-a),{translateX:i,translateY:o,rotate:Math.atan2(n,t)*Sr,skewX:Math.atan(c)*Sr,scaleX:a,scaleY:u}}function Nr(t,n,e,r){function i(t){return t.length?t.pop()+" ":""}return function(o,a){var u=[],c=[];return o=t(o),a=t(a),function(t,r,i,o,a,u){if(t!==i||r!==o){var c=a.push("translate(",null,n,null,e);u.push({i:c-4,x:_r(t,i)},{i:c-2,x:_r(r,o)})}else(i||o)&&a.push("translate("+i+n+o+e)}(o.translateX,o.translateY,a.translateX,a.translateY,u,c),function(t,n,e,o){t!==n?(t-n>180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:_r(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,a.rotate,u,c),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:_r(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,a.skewX,u,c),function(t,n,e,r,o,a){if(t!==e||n!==r){var u=o.push(i(o)+"scale(",null,",",null,")");a.push({i:u-4,x:_r(t,e)},{i:u-2,x:_r(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,a.scaleX,a.scaleY,u,c),o=a=null,function(t){for(var n,e=-1,r=c.length;++e<r;)u[(n=c[e]).i]=n.x(t);return u.join("")}}}var Cr=Nr((function(t){const n=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(t+"");return n.isIdentity?Er:kr(n.a,n.b,n.c,n.d,n.e,n.f)}),"px, ","px)","deg)"),Pr=Nr((function(t){return null==t?Er:(Tr||(Tr=document.createElementNS("http://www.w3.org/2000/svg","g")),Tr.setAttribute("transform",t),(t=Tr.transform.baseVal.consolidate())?kr((t=t.matrix).a,t.b,t.c,t.d,t.e,t.f):Er)}),", ",")",")");function zr(t){return((t=Math.exp(t))+1/t)/2}var Dr=function t(n,e,r){function i(t,i){var o,a,u=t[0],c=t[1],f=t[2],s=i[0],l=i[1],h=i[2],d=s-u,p=l-c,g=d*d+p*p;if(g<1e-12)a=Math.log(h/f)/n,o=function(t){return[u+t*d,c+t*p,f*Math.exp(n*t*a)]};else{var y=Math.sqrt(g),v=(h*h-f*f+r*g)/(2*f*e*y),_=(h*h-f*f-r*g)/(2*h*e*y),b=Math.log(Math.sqrt(v*v+1)-v),m=Math.log(Math.sqrt(_*_+1)-_);a=(m-b)/n,o=function(t){var r=t*a,i=zr(b),o=f/(e*y)*(i*function(t){return((t=Math.exp(2*t))-1)/(t+1)}(n*r+b)-function(t){return((t=Math.exp(t))-1/t)/2}(b));return[u+o*d,c+o*p,f*i/zr(n*r+b)]}}return o.duration=1e3*a*n/Math.SQRT2,o}return i.rho=function(n){var e=Math.max(.001,+n),r=e*e;return t(e,r,r*r)},i}(Math.SQRT2,2,4);function qr(t){return function(n,e){var r=t((n=Ae(n)).h,(e=Ae(e)).h),i=fr(n.s,e.s),o=fr(n.l,e.l),a=fr(n.opacity,e.opacity);return function(t){return n.h=r(t),n.s=i(t),n.l=o(t),n.opacity=a(t),n+""}}}var Rr=qr(ur),Fr=qr(fr);function Or(t){return function(n,e){var r=t((n=Le(n)).h,(e=Le(e)).h),i=fr(n.c,e.c),o=fr(n.l,e.l),a=fr(n.opacity,e.opacity);return function(t){return n.h=r(t),n.c=i(t),n.l=o(t),n.opacity=a(t),n+""}}}var Ir=Or(ur),Ur=Or(fr);function Br(t){return function n(e){function r(n,r){var i=t((n=tr(n)).h,(r=tr(r)).h),o=fr(n.s,r.s),a=fr(n.l,r.l),u=fr(n.opacity,r.opacity);return function(t){return n.h=i(t),n.s=o(t),n.l=a(Math.pow(t,e)),n.opacity=u(t),n+""}}return e=+e,r.gamma=n,r}(1)}var Yr=Br(ur),Lr=Br(fr);function jr(t,n){void 0===n&&(n=t,t=Mr);for(var e=0,r=n.length-1,i=n[0],o=new Array(r<0?0:r);e<r;)o[e]=t(i,i=n[++e]);return function(t){var n=Math.max(0,Math.min(r-1,Math.floor(t*=r)));return o[n](t-n)}}var Hr,Xr,Gr=0,Vr=0,$r=0,Wr=0,Zr=0,Kr=0,Qr="object"==typeof performance&&performance.now?performance:Date,Jr="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};function ti(){return Zr||(Jr(ni),Zr=Qr.now()+Kr)}function ni(){Zr=0}function ei(){this._call=this._time=this._next=null}function ri(t,n,e){var r=new ei;return r.restart(t,n,e),r}function ii(){ti(),++Gr;for(var t,n=Hr;n;)(t=Zr-n._time)>=0&&n._call.call(null,t),n=n._next;--Gr}function oi(){Zr=(Wr=Qr.now())+Kr,Gr=Vr=0;try{ii()}finally{Gr=0,function(){var t,n,e=Hr,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:Hr=n);Xr=t,ui(r)}(),Zr=0}}function ai(){var t=Qr.now(),n=t-Wr;n>1e3&&(Kr-=n,Wr=t)}function ui(t){Gr||(Vr&&(Vr=clearTimeout(Vr)),t-Zr>24?(t<1/0&&(Vr=setTimeout(oi,t-Qr.now()-Kr)),$r&&($r=clearInterval($r))):($r||(Wr=Qr.now(),$r=setInterval(ai,1e3)),Gr=1,Jr(oi)))}function ci(t,n,e){var r=new ei;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}ei.prototype=ri.prototype={constructor:ei,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?ti():+e)+(null==n?0:+n),this._next||Xr===this||(Xr?Xr._next=this:Hr=this,Xr=this),this._call=t,this._time=e,ui()},stop:function(){this._call&&(this._call=null,this._time=1/0,ui())}};var fi=pt("start","end","cancel","interrupt"),si=[];function li(t,n,e,r,i,o){var a=t.__transition;if(a){if(e in a)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=1,e.timer.restart(a,e.delay,e.time),e.delay<=t&&a(t-e.delay)}function a(o){var f,s,l,h;if(1!==e.state)return c();for(f in i)if((h=i[f]).name===e.name){if(3===h.state)return ci(a);4===h.state?(h.state=6,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[f]):+f<n&&(h.state=6,h.timer.stop(),h.on.call("cancel",t,t.__data__,h.index,h.group),delete i[f])}if(ci((function(){3===e.state&&(e.state=4,e.timer.restart(u,e.delay,e.time),u(o))})),e.state=2,e.on.call("start",t,t.__data__,e.index,e.group),2===e.state){for(e.state=3,r=new Array(l=e.tween.length),f=0,s=-1;f<l;++f)(h=e.tween[f].value.call(t,t.__data__,e.index,e.group))&&(r[++s]=h);r.length=s+1}}function u(n){for(var i=n<e.duration?e.ease.call(null,n/e.duration):(e.timer.restart(c),e.state=5,1),o=-1,a=r.length;++o<a;)r[o].call(t,i);5===e.state&&(e.on.call("end",t,t.__data__,e.index,e.group),c())}function c(){for(var r in e.state=6,e.timer.stop(),delete i[n],i)return;delete t.__transition}i[n]=e,e.timer=ri(o,0,e.time)}(t,e,{name:n,index:r,group:i,on:fi,tween:si,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:0})}function hi(t,n){var e=pi(t,n);if(e.state>0)throw new Error("too late; already scheduled");return e}function di(t,n){var e=pi(t,n);if(e.state>3)throw new Error("too late; already running");return e}function pi(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function gi(t,n){var e,r,i,o=t.__transition,a=!0;if(o){for(i in n=null==n?null:n+"",o)(e=o[i]).name===n?(r=e.state>2&&e.state<5,e.state=6,e.timer.stop(),e.on.call(r?"interrupt":"cancel",t,t.__data__,e.index,e.group),delete o[i]):a=!1;a&&delete t.__transition}}function yi(t,n){var e,r;return function(){var i=di(this,t),o=i.tween;if(o!==e)for(var a=0,u=(r=e=o).length;a<u;++a)if(r[a].name===n){(r=r.slice()).splice(a,1);break}i.tween=r}}function vi(t,n,e){var r,i;if("function"!=typeof e)throw new Error;return function(){var o=di(this,t),a=o.tween;if(a!==r){i=(r=a).slice();for(var u={name:n,value:e},c=0,f=i.length;c<f;++c)if(i[c].name===n){i[c]=u;break}c===f&&i.push(u)}o.tween=i}}function _i(t,n,e){var r=t._id;return t.each((function(){var t=di(this,r);(t.value||(t.value={}))[n]=e.apply(this,arguments)})),function(t){return pi(t,r).value[n]}}function bi(t,n){var e;return("number"==typeof n?_r:n instanceof de?sr:(e=de(n))?(n=e,sr):wr)(t,n)}function mi(t){return function(){this.removeAttribute(t)}}function xi(t){return function(){this.removeAttributeNS(t.space,t.local)}}function wi(t,n,e){var r,i,o=e+"";return function(){var a=this.getAttribute(t);return a===o?null:a===r?i:i=n(r=a,e)}}function Mi(t,n,e){var r,i,o=e+"";return function(){var a=this.getAttributeNS(t.space,t.local);return a===o?null:a===r?i:i=n(r=a,e)}}function Ai(t,n,e){var r,i,o;return function(){var a,u,c=e(this);if(null!=c)return(a=this.getAttribute(t))===(u=c+"")?null:a===r&&u===i?o:(i=u,o=n(r=a,c));this.removeAttribute(t)}}function Ti(t,n,e){var r,i,o;return function(){var a,u,c=e(this);if(null!=c)return(a=this.getAttributeNS(t.space,t.local))===(u=c+"")?null:a===r&&u===i?o:(i=u,o=n(r=a,c));this.removeAttributeNS(t.space,t.local)}}function Si(t,n){return function(e){this.setAttribute(t,n.call(this,e))}}function Ei(t,n){return function(e){this.setAttributeNS(t.space,t.local,n.call(this,e))}}function ki(t,n){var e,r;function i(){var i=n.apply(this,arguments);return i!==r&&(e=(r=i)&&Ei(t,i)),e}return i._value=n,i}function Ni(t,n){var e,r;function i(){var i=n.apply(this,arguments);return i!==r&&(e=(r=i)&&Si(t,i)),e}return i._value=n,i}function Ci(t,n){return function(){hi(this,t).delay=+n.apply(this,arguments)}}function Pi(t,n){return n=+n,function(){hi(this,t).delay=n}}function zi(t,n){return function(){di(this,t).duration=+n.apply(this,arguments)}}function Di(t,n){return n=+n,function(){di(this,t).duration=n}}function qi(t,n){if("function"!=typeof n)throw new Error;return function(){di(this,t).ease=n}}function Ri(t,n,e){var r,i,o=function(t){return(t+"").trim().split(/^|\s+/).every((function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?hi:di;return function(){var a=o(this,t),u=a.on;u!==r&&(i=(r=u).copy()).on(n,e),a.on=i}}var Fi=zn.prototype.constructor;function Oi(t){return function(){this.style.removeProperty(t)}}function Ii(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}function Ui(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&Ii(t,o,e)),r}return o._value=n,o}function Bi(t){return function(n){this.textContent=t.call(this,n)}}function Yi(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&Bi(r)),n}return r._value=t,r}var Li=0;function ji(t,n,e,r){this._groups=t,this._parents=n,this._name=e,this._id=r}function Hi(t){return zn().transition(t)}function Xi(){return++Li}var Gi=zn.prototype;ji.prototype=Hi.prototype={constructor:ji,select:function(t){var n=this._name,e=this._id;"function"!=typeof t&&(t=St(t));for(var r=this._groups,i=r.length,o=new Array(i),a=0;a<i;++a)for(var u,c,f=r[a],s=f.length,l=o[a]=new Array(s),h=0;h<s;++h)(u=f[h])&&(c=t.call(u,u.__data__,h,f))&&("__data__"in u&&(c.__data__=u.__data__),l[h]=c,li(l[h],n,e,h,l,pi(u,e)));return new ji(o,this._parents,n,e)},selectAll:function(t){var n=this._name,e=this._id;"function"!=typeof t&&(t=Nt(t));for(var r=this._groups,i=r.length,o=[],a=[],u=0;u<i;++u)for(var c,f=r[u],s=f.length,l=0;l<s;++l)if(c=f[l]){for(var h,d=t.call(c,c.__data__,l,f),p=pi(c,e),g=0,y=d.length;g<y;++g)(h=d[g])&&li(h,n,e,g,d,p);o.push(d),a.push(c)}return new ji(o,a,n,e)},filter:function(t){"function"!=typeof t&&(t=Ct(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i<e;++i)for(var o,a=n[i],u=a.length,c=r[i]=[],f=0;f<u;++f)(o=a[f])&&t.call(o,o.__data__,f,a)&&c.push(o);return new ji(r,this._parents,this._name,this._id)},merge:function(t){if(t._id!==this._id)throw new Error;for(var n=this._groups,e=t._groups,r=n.length,i=e.length,o=Math.min(r,i),a=new Array(r),u=0;u<o;++u)for(var c,f=n[u],s=e[u],l=f.length,h=a[u]=new Array(l),d=0;d<l;++d)(c=f[d]||s[d])&&(h[d]=c);for(;u<r;++u)a[u]=n[u];return new ji(a,this._parents,this._name,this._id)},selection:function(){return new Fi(this._groups,this._parents)},transition:function(){for(var t=this._name,n=this._id,e=Xi(),r=this._groups,i=r.length,o=0;o<i;++o)for(var a,u=r[o],c=u.length,f=0;f<c;++f)if(a=u[f]){var s=pi(a,n);li(a,t,e,f,u,{time:s.time+s.delay+s.duration,delay:0,duration:s.duration,ease:s.ease})}return new ji(r,this._parents,t,e)},call:Gi.call,nodes:Gi.nodes,node:Gi.node,size:Gi.size,empty:Gi.empty,each:Gi.each,on:function(t,n){var e=this._id;return arguments.length<2?pi(this.node(),e).on.on(t):this.each(Ri(e,t,n))},attr:function(t,n){var e=xt(t),r="transform"===e?Pr:bi;return this.attrTween(t,"function"==typeof n?(e.local?Ti:Ai)(e,r,_i(this,"attr."+t,n)):null==n?(e.local?xi:mi)(e):(e.local?Mi:wi)(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=xt(t);return this.tween(e,(r.local?ki:Ni)(r,n))},style:function(t,n,e){var r="transform"==(t+="")?Cr:bi;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=Jt(this,t),a=(this.style.removeProperty(t),Jt(this,t));return o===a?null:o===e&&a===r?i:i=n(e=o,r=a)}}(t,r)).on("end.style."+t,Oi(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var a=Jt(this,t),u=e(this),c=u+"";return null==u&&(this.style.removeProperty(t),c=u=Jt(this,t)),a===c?null:a===r&&c===i?o:(i=c,o=n(r=a,u))}}(t,r,_i(this,"style."+t,n))).each(function(t,n){var e,r,i,o,a="style."+n,u="end."+a;return function(){var c=di(this,t),f=c.on,s=null==c.value[a]?o||(o=Oi(n)):void 0;f===e&&i===s||(r=(e=f).copy()).on(u,i=s),c.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var a=Jt(this,t);return a===o?null:a===r?i:i=n(r=a,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,Ui(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(_i(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var n="text";if(arguments.length<1)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;return this.tween(n,Yi(t))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=pi(this.node(),e).tween,o=0,a=i.length;o<a;++o)if((r=i[o]).name===t)return r.value;return null}return this.each((null==n?yi:vi)(e,t,n))},delay:function(t){var n=this._id;return arguments.length?this.each(("function"==typeof t?Ci:Pi)(n,t)):pi(this.node(),n).delay},duration:function(t){var n=this._id;return arguments.length?this.each(("function"==typeof t?zi:Di)(n,t)):pi(this.node(),n).duration},ease:function(t){var n=this._id;return arguments.length?this.each(qi(n,t)):pi(this.node(),n).ease},easeVarying:function(t){if("function"!=typeof t)throw new Error;return this.each(function(t,n){return function(){var e=n.apply(this,arguments);if("function"!=typeof e)throw new Error;di(this,t).ease=e}}(this._id,t))},end:function(){var t,n,e=this,r=e._id,i=e.size();return new Promise((function(o,a){var u={value:a},c={value:function(){0==--i&&o()}};e.each((function(){var e=di(this,r),i=e.on;i!==t&&((n=(t=i).copy())._.cancel.push(u),n._.interrupt.push(u),n._.end.push(c)),e.on=n})),0===i&&o()}))},[Symbol.iterator]:Gi[Symbol.iterator]};function Vi(t){return((t*=2)<=1?t*t:--t*(2-t)+1)/2}function $i(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}var Wi=function t(n){function e(t){return Math.pow(t,n)}return n=+n,e.exponent=t,e}(3),Zi=function t(n){function e(t){return 1-Math.pow(1-t,n)}return n=+n,e.exponent=t,e}(3),Ki=function t(n){function e(t){return((t*=2)<=1?Math.pow(t,n):2-Math.pow(2-t,n))/2}return n=+n,e.exponent=t,e}(3),Qi=Math.PI,Ji=Qi/2;function to(t){return(1-Math.cos(Qi*t))/2}function no(t){return 1.0009775171065494*(Math.pow(2,-10*t)-.0009765625)}function eo(t){return((t*=2)<=1?no(1-t):2-no(t-1))/2}function ro(t){return((t*=2)<=1?1-Math.sqrt(1-t*t):Math.sqrt(1-(t-=2)*t)+1)/2}var io=4/11,oo=7.5625;function ao(t){return(t=+t)<io?oo*t*t:t<.7272727272727273?oo*(t-=.5454545454545454)*t+.75:t<.9090909090909091?oo*(t-=.8181818181818182)*t+.9375:oo*(t-=.9545454545454546)*t+.984375}var uo=1.70158,co=function t(n){function e(t){return(t=+t)*t*(n*(t-1)+t)}return n=+n,e.overshoot=t,e}(uo),fo=function t(n){function e(t){return--t*t*((t+1)*n+t)+1}return n=+n,e.overshoot=t,e}(uo),so=function t(n){function e(t){return((t*=2)<1?t*t*((n+1)*t-n):(t-=2)*t*((n+1)*t+n)+2)/2}return n=+n,e.overshoot=t,e}(uo),lo=2*Math.PI,ho=function t(n,e){var r=Math.asin(1/(n=Math.max(1,n)))*(e/=lo);function i(t){return n*no(- --t)*Math.sin((r-t)/e)}return i.amplitude=function(n){return t(n,e*lo)},i.period=function(e){return t(n,e)},i}(1,.3),po=function t(n,e){var r=Math.asin(1/(n=Math.max(1,n)))*(e/=lo);function i(t){return 1-n*no(t=+t)*Math.sin((t+r)/e)}return i.amplitude=function(n){return t(n,e*lo)},i.period=function(e){return t(n,e)},i}(1,.3),go=function t(n,e){var r=Math.asin(1/(n=Math.max(1,n)))*(e/=lo);function i(t){return((t=2*t-1)<0?n*no(-t)*Math.sin((r-t)/e):2-n*no(t)*Math.sin((r+t)/e))/2}return i.amplitude=function(n){return t(n,e*lo)},i.period=function(e){return t(n,e)},i}(1,.3),yo={time:null,delay:0,duration:250,ease:$i};function vo(t,n){for(var e;!(e=t.__transition)||!(e=e[n]);)if(!(t=t.parentNode))throw new Error(`transition ${n} not found`);return e}zn.prototype.interrupt=function(t){return this.each((function(){gi(this,t)}))},zn.prototype.transition=function(t){var n,e;t instanceof ji?(n=t._id,t=t._name):(n=Xi(),(e=yo).time=ti(),t=null==t?null:t+"");for(var r=this._groups,i=r.length,o=0;o<i;++o)for(var a,u=r[o],c=u.length,f=0;f<c;++f)(a=u[f])&&li(a,t,n,f,u,e||vo(a,n));return new ji(r,this._parents,t,n)};var _o=[null];var bo=t=>()=>t;function mo(t,{sourceEvent:n,target:e,selection:r,mode:i,dispatch:o}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},target:{value:e,enumerable:!0,configurable:!0},selection:{value:r,enumerable:!0,configurable:!0},mode:{value:i,enumerable:!0,configurable:!0},_:{value:o}})}function xo(t){t.stopImmediatePropagation()}function wo(t){t.preventDefault(),t.stopImmediatePropagation()}var Mo={name:"drag"},Ao={name:"space"},To={name:"handle"},So={name:"center"};const{abs:Eo,max:ko,min:No}=Math;function Co(t){return[+t[0],+t[1]]}function Po(t){return[Co(t[0]),Co(t[1])]}var zo={name:"x",handles:["w","e"].map(Bo),input:function(t,n){return null==t?null:[[+t[0],n[0][1]],[+t[1],n[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},Do={name:"y",handles:["n","s"].map(Bo),input:function(t,n){return null==t?null:[[n[0][0],+t[0]],[n[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},qo={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(Bo),input:function(t){return null==t?null:Po(t)},output:function(t){return t}},Ro={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Fo={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},Oo={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},Io={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},Uo={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function Bo(t){return{type:t}}function Yo(t){return!t.ctrlKey&&!t.button}function Lo(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function jo(){return navigator.maxTouchPoints||"ontouchstart"in this}function Ho(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function Xo(t){return t[0][0]===t[1][0]||t[0][1]===t[1][1]}function Go(t){var n,e=Lo,r=Yo,i=jo,o=!0,a=pt("start","brush","end"),u=6;function c(n){var e=n.property("__brush",g).selectAll(".overlay").data([Bo("overlay")]);e.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",Ro.overlay).merge(e).each((function(){var t=Ho(this).extent;Dn(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1])})),n.selectAll(".selection").data([Bo("selection")]).enter().append("rect").attr("class","selection").attr("cursor",Ro.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=n.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return"handle handle--"+t.type})).attr("cursor",(function(t){return Ro[t.type]})),n.each(f).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",h).filter(i).on("touchstart.brush",h).on("touchmove.brush",d).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function f(){var t=Dn(this),n=Ho(this).selection;n?(t.selectAll(".selection").style("display",null).attr("x",n[0][0]).attr("y",n[0][1]).attr("width",n[1][0]-n[0][0]).attr("height",n[1][1]-n[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return"e"===t.type[t.type.length-1]?n[1][0]-u/2:n[0][0]-u/2})).attr("y",(function(t){return"s"===t.type[0]?n[1][1]-u/2:n[0][1]-u/2})).attr("width",(function(t){return"n"===t.type||"s"===t.type?n[1][0]-n[0][0]+u:u})).attr("height",(function(t){return"e"===t.type||"w"===t.type?n[1][1]-n[0][1]+u:u}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function s(t,n,e){var r=t.__brush.emitter;return!r||e&&r.clean?new l(t,n,e):r}function l(t,n,e){this.that=t,this.args=n,this.state=t.__brush,this.active=0,this.clean=e}function h(e){if((!n||e.touches)&&r.apply(this,arguments)){var i,a,u,c,l,h,d,p,g,y,v,_=this,b=e.target.__data__.type,m="selection"===(o&&e.metaKey?b="overlay":b)?Mo:o&&e.altKey?So:To,x=t===Do?null:Io[b],w=t===zo?null:Uo[b],M=Ho(_),A=M.extent,T=M.selection,S=A[0][0],E=A[0][1],k=A[1][0],N=A[1][1],C=0,P=0,z=x&&w&&o&&e.shiftKey,D=Array.from(e.touches||[e],(t=>{const n=t.identifier;return(t=In(t,_)).point0=t.slice(),t.identifier=n,t}));if("overlay"===b){T&&(g=!0);const n=[D[0],D[1]||D[0]];M.selection=T=[[i=t===Do?S:No(n[0][0],n[1][0]),u=t===zo?E:No(n[0][1],n[1][1])],[l=t===Do?k:ko(n[0][0],n[1][0]),d=t===zo?N:ko(n[0][1],n[1][1])]],D.length>1&&U()}else i=T[0][0],u=T[0][1],l=T[1][0],d=T[1][1];a=i,c=u,h=l,p=d;var q=Dn(_).attr("pointer-events","none"),R=q.selectAll(".overlay").attr("cursor",Ro[b]);gi(_);var F=s(_,arguments,!0).beforestart();if(e.touches)F.moved=I,F.ended=B;else{var O=Dn(e.view).on("mousemove.brush",I,!0).on("mouseup.brush",B,!0);o&&O.on("keydown.brush",Y,!0).on("keyup.brush",L,!0),Yn(e.view)}f.call(_),F.start(e,m.name)}function I(t){for(const n of t.changedTouches||[t])for(const t of D)t.identifier===n.identifier&&(t.cur=In(n,_));if(z&&!y&&!v&&1===D.length){const t=D[0];Eo(t.cur[0]-t[0])>Eo(t.cur[1]-t[1])?v=!0:y=!0}for(const t of D)t.cur&&(t[0]=t.cur[0],t[1]=t.cur[1]);g=!0,wo(t),U(t)}function U(t){const n=D[0],e=n.point0;var r;switch(C=n[0]-e[0],P=n[1]-e[1],m){case Ao:case Mo:x&&(C=ko(S-i,No(k-l,C)),a=i+C,h=l+C),w&&(P=ko(E-u,No(N-d,P)),c=u+P,p=d+P);break;case To:D[1]?(x&&(a=ko(S,No(k,D[0][0])),h=ko(S,No(k,D[1][0])),x=1),w&&(c=ko(E,No(N,D[0][1])),p=ko(E,No(N,D[1][1])),w=1)):(x<0?(C=ko(S-i,No(k-i,C)),a=i+C,h=l):x>0&&(C=ko(S-l,No(k-l,C)),a=i,h=l+C),w<0?(P=ko(E-u,No(N-u,P)),c=u+P,p=d):w>0&&(P=ko(E-d,No(N-d,P)),c=u,p=d+P));break;case So:x&&(a=ko(S,No(k,i-C*x)),h=ko(S,No(k,l+C*x))),w&&(c=ko(E,No(N,u-P*w)),p=ko(E,No(N,d+P*w)))}h<a&&(x*=-1,r=i,i=l,l=r,r=a,a=h,h=r,b in Fo&&R.attr("cursor",Ro[b=Fo[b]])),p<c&&(w*=-1,r=u,u=d,d=r,r=c,c=p,p=r,b in Oo&&R.attr("cursor",Ro[b=Oo[b]])),M.selection&&(T=M.selection),y&&(a=T[0][0],h=T[1][0]),v&&(c=T[0][1],p=T[1][1]),T[0][0]===a&&T[0][1]===c&&T[1][0]===h&&T[1][1]===p||(M.selection=[[a,c],[h,p]],f.call(_),F.brush(t,m.name))}function B(t){if(xo(t),t.touches){if(t.touches.length)return;n&&clearTimeout(n),n=setTimeout((function(){n=null}),500)}else Ln(t.view,g),O.on("keydown.brush keyup.brush mousemove.brush mouseup.brush",null);q.attr("pointer-events","all"),R.attr("cursor",Ro.overlay),M.selection&&(T=M.selection),Xo(T)&&(M.selection=null,f.call(_)),F.end(t,m.name)}function Y(t){switch(t.keyCode){case 16:z=x&&w;break;case 18:m===To&&(x&&(l=h-C*x,i=a+C*x),w&&(d=p-P*w,u=c+P*w),m=So,U());break;case 32:m!==To&&m!==So||(x<0?l=h-C:x>0&&(i=a-C),w<0?d=p-P:w>0&&(u=c-P),m=Ao,R.attr("cursor",Ro.selection),U());break;default:return}wo(t)}function L(t){switch(t.keyCode){case 16:z&&(y=v=z=!1,U());break;case 18:m===So&&(x<0?l=h:x>0&&(i=a),w<0?d=p:w>0&&(u=c),m=To,U());break;case 32:m===Ao&&(t.altKey?(x&&(l=h-C*x,i=a+C*x),w&&(d=p-P*w,u=c+P*w),m=So):(x<0?l=h:x>0&&(i=a),w<0?d=p:w>0&&(u=c),m=To),R.attr("cursor",Ro[b]),U());break;default:return}wo(t)}}function d(t){s(this,arguments).moved(t)}function p(t){s(this,arguments).ended(t)}function g(){var n=this.__brush||{selection:null};return n.extent=Po(e.apply(this,arguments)),n.dim=t,n}return c.move=function(n,e){n.tween?n.on("start.brush",(function(t){s(this,arguments).beforestart().start(t)})).on("interrupt.brush end.brush",(function(t){s(this,arguments).end(t)})).tween("brush",(function(){var n=this,r=n.__brush,i=s(n,arguments),o=r.selection,a=t.input("function"==typeof e?e.apply(this,arguments):e,r.extent),u=Mr(o,a);function c(t){r.selection=1===t&&null===a?null:u(t),f.call(n),i.brush()}return null!==o&&null!==a?c:c(1)})):n.each((function(){var n=this,r=arguments,i=n.__brush,o=t.input("function"==typeof e?e.apply(n,r):e,i.extent),a=s(n,r).beforestart();gi(n),i.selection=null===o?null:o,f.call(n),a.start().brush().end()}))},c.clear=function(t){c.move(t,null)},l.prototype={beforestart:function(){return 1==++this.active&&(this.state.emitter=this,this.starting=!0),this},start:function(t,n){return this.starting?(this.starting=!1,this.emit("start",t,n)):this.emit("brush",t),this},brush:function(t,n){return this.emit("brush",t,n),this},end:function(t,n){return 0==--this.active&&(delete this.state.emitter,this.emit("end",t,n)),this},emit:function(n,e,r){var i=Dn(this.that).datum();a.call(n,this.that,new mo(n,{sourceEvent:e,target:c,selection:t.output(this.state.selection),mode:r,dispatch:a}),i)}},c.extent=function(t){return arguments.length?(e="function"==typeof t?t:bo(Po(t)),c):e},c.filter=function(t){return arguments.length?(r="function"==typeof t?t:bo(!!t),c):r},c.touchable=function(t){return arguments.length?(i="function"==typeof t?t:bo(!!t),c):i},c.handleSize=function(t){return arguments.length?(u=+t,c):u},c.keyModifiers=function(t){return arguments.length?(o=!!t,c):o},c.on=function(){var t=a.on.apply(a,arguments);return t===a?c:t},c}var Vo=Math.abs,$o=Math.cos,Wo=Math.sin,Zo=Math.PI,Ko=Zo/2,Qo=2*Zo,Jo=Math.max,ta=1e-12;function na(t,n){return Array.from({length:n-t},((n,e)=>t+e))}function ea(t){return function(n,e){return t(n.source.value+n.target.value,e.source.value+e.target.value)}}function ra(t,n){var e=0,r=null,i=null,o=null;function a(a){var u,c=a.length,f=new Array(c),s=na(0,c),l=new Array(c*c),h=new Array(c),d=0;a=Float64Array.from({length:c*c},n?(t,n)=>a[n%c][n/c|0]:(t,n)=>a[n/c|0][n%c]);for(let n=0;n<c;++n){let e=0;for(let r=0;r<c;++r)e+=a[n*c+r]+t*a[r*c+n];d+=f[n]=e}u=(d=Jo(0,Qo-e*c)/d)?e:Qo/c;{let n=0;r&&s.sort(((t,n)=>r(f[t],f[n])));for(const e of s){const r=n;if(t){const t=na(1+~c,c).filter((t=>t<0?a[~t*c+e]:a[e*c+t]));i&&t.sort(((t,n)=>i(t<0?-a[~t*c+e]:a[e*c+t],n<0?-a[~n*c+e]:a[e*c+n])));for(const r of t)if(r<0){(l[~r*c+e]||(l[~r*c+e]={source:null,target:null})).target={index:e,startAngle:n,endAngle:n+=a[~r*c+e]*d,value:a[~r*c+e]}}else{(l[e*c+r]||(l[e*c+r]={source:null,target:null})).source={index:e,startAngle:n,endAngle:n+=a[e*c+r]*d,value:a[e*c+r]}}h[e]={index:e,startAngle:r,endAngle:n,value:f[e]}}else{const t=na(0,c).filter((t=>a[e*c+t]||a[t*c+e]));i&&t.sort(((t,n)=>i(a[e*c+t],a[e*c+n])));for(const r of t){let t;if(e<r?(t=l[e*c+r]||(l[e*c+r]={source:null,target:null}),t.source={index:e,startAngle:n,endAngle:n+=a[e*c+r]*d,value:a[e*c+r]}):(t=l[r*c+e]||(l[r*c+e]={source:null,target:null}),t.target={index:e,startAngle:n,endAngle:n+=a[e*c+r]*d,value:a[e*c+r]},e===r&&(t.source=t.target)),t.source&&t.target&&t.source.value<t.target.value){const n=t.source;t.source=t.target,t.target=n}}h[e]={index:e,startAngle:r,endAngle:n,value:f[e]}}n+=u}}return(l=Object.values(l)).groups=h,o?l.sort(o):l}return a.padAngle=function(t){return arguments.length?(e=Jo(0,t),a):e},a.sortGroups=function(t){return arguments.length?(r=t,a):r},a.sortSubgroups=function(t){return arguments.length?(i=t,a):i},a.sortChords=function(t){return arguments.length?(null==t?o=null:(o=ea(t))._=t,a):o&&o._},a}const ia=Math.PI,oa=2*ia,aa=1e-6,ua=oa-aa;function ca(){this._x0=this._y0=this._x1=this._y1=null,this._=""}function fa(){return new ca}ca.prototype=fa.prototype={constructor:ca,moveTo:function(t,n){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+n)},closePath:function(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")},lineTo:function(t,n){this._+="L"+(this._x1=+t)+","+(this._y1=+n)},quadraticCurveTo:function(t,n,e,r){this._+="Q"+ +t+","+ +n+","+(this._x1=+e)+","+(this._y1=+r)},bezierCurveTo:function(t,n,e,r,i,o){this._+="C"+ +t+","+ +n+","+ +e+","+ +r+","+(this._x1=+i)+","+(this._y1=+o)},arcTo:function(t,n,e,r,i){t=+t,n=+n,e=+e,r=+r,i=+i;var o=this._x1,a=this._y1,u=e-t,c=r-n,f=o-t,s=a-n,l=f*f+s*s;if(i<0)throw new Error("negative radius: "+i);if(null===this._x1)this._+="M"+(this._x1=t)+","+(this._y1=n);else if(l>aa)if(Math.abs(s*u-c*f)>aa&&i){var h=e-o,d=r-a,p=u*u+c*c,g=h*h+d*d,y=Math.sqrt(p),v=Math.sqrt(l),_=i*Math.tan((ia-Math.acos((p+l-g)/(2*y*v)))/2),b=_/v,m=_/y;Math.abs(b-1)>aa&&(this._+="L"+(t+b*f)+","+(n+b*s)),this._+="A"+i+","+i+",0,0,"+ +(s*h>f*d)+","+(this._x1=t+m*u)+","+(this._y1=n+m*c)}else this._+="L"+(this._x1=t)+","+(this._y1=n);else;},arc:function(t,n,e,r,i,o){t=+t,n=+n,o=!!o;var a=(e=+e)*Math.cos(r),u=e*Math.sin(r),c=t+a,f=n+u,s=1^o,l=o?r-i:i-r;if(e<0)throw new Error("negative radius: "+e);null===this._x1?this._+="M"+c+","+f:(Math.abs(this._x1-c)>aa||Math.abs(this._y1-f)>aa)&&(this._+="L"+c+","+f),e&&(l<0&&(l=l%oa+oa),l>ua?this._+="A"+e+","+e+",0,1,"+s+","+(t-a)+","+(n-u)+"A"+e+","+e+",0,1,"+s+","+(this._x1=c)+","+(this._y1=f):l>aa&&(this._+="A"+e+","+e+",0,"+ +(l>=ia)+","+s+","+(this._x1=t+e*Math.cos(i))+","+(this._y1=n+e*Math.sin(i))))},rect:function(t,n,e,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+n)+"h"+ +e+"v"+ +r+"h"+-e+"Z"},toString:function(){return this._}};var sa=Array.prototype.slice;function la(t){return function(){return t}}function ha(t){return t.source}function da(t){return t.target}function pa(t){return t.radius}function ga(t){return t.startAngle}function ya(t){return t.endAngle}function va(){return 0}function _a(){return 10}function ba(t){var n=ha,e=da,r=pa,i=pa,o=ga,a=ya,u=va,c=null;function f(){var f,s=n.apply(this,arguments),l=e.apply(this,arguments),h=u.apply(this,arguments)/2,d=sa.call(arguments),p=+r.apply(this,(d[0]=s,d)),g=o.apply(this,d)-Ko,y=a.apply(this,d)-Ko,v=+i.apply(this,(d[0]=l,d)),_=o.apply(this,d)-Ko,b=a.apply(this,d)-Ko;if(c||(c=f=fa()),h>ta&&(Vo(y-g)>2*h+ta?y>g?(g+=h,y-=h):(g-=h,y+=h):g=y=(g+y)/2,Vo(b-_)>2*h+ta?b>_?(_+=h,b-=h):(_-=h,b+=h):_=b=(_+b)/2),c.moveTo(p*$o(g),p*Wo(g)),c.arc(0,0,p,g,y),g!==_||y!==b)if(t){var m=+t.apply(this,arguments),x=v-m,w=(_+b)/2;c.quadraticCurveTo(0,0,x*$o(_),x*Wo(_)),c.lineTo(v*$o(w),v*Wo(w)),c.lineTo(x*$o(b),x*Wo(b))}else c.quadraticCurveTo(0,0,v*$o(_),v*Wo(_)),c.arc(0,0,v,_,b);if(c.quadraticCurveTo(0,0,p*$o(g),p*Wo(g)),c.closePath(),f)return c=null,f+""||null}return t&&(f.headRadius=function(n){return arguments.length?(t="function"==typeof n?n:la(+n),f):t}),f.radius=function(t){return arguments.length?(r=i="function"==typeof t?t:la(+t),f):r},f.sourceRadius=function(t){return arguments.length?(r="function"==typeof t?t:la(+t),f):r},f.targetRadius=function(t){return arguments.length?(i="function"==typeof t?t:la(+t),f):i},f.startAngle=function(t){return arguments.length?(o="function"==typeof t?t:la(+t),f):o},f.endAngle=function(t){return arguments.length?(a="function"==typeof t?t:la(+t),f):a},f.padAngle=function(t){return arguments.length?(u="function"==typeof t?t:la(+t),f):u},f.source=function(t){return arguments.length?(n=t,f):n},f.target=function(t){return arguments.length?(e=t,f):e},f.context=function(t){return arguments.length?(c=null==t?null:t,f):c},f}var ma=Array.prototype.slice;function xa(t,n){return t-n}var wa=t=>()=>t;function Ma(t,n){for(var e,r=-1,i=n.length;++r<i;)if(e=Aa(t,n[r]))return e;return 0}function Aa(t,n){for(var e=n[0],r=n[1],i=-1,o=0,a=t.length,u=a-1;o<a;u=o++){var c=t[o],f=c[0],s=c[1],l=t[u],h=l[0],d=l[1];if(Ta(c,l,n))return 0;s>r!=d>r&&e<(h-f)*(r-s)/(d-s)+f&&(i=-i)}return i}function Ta(t,n,e){var r,i,o,a;return function(t,n,e){return(n[0]-t[0])*(e[1]-t[1])==(e[0]-t[0])*(n[1]-t[1])}(t,n,e)&&(i=t[r=+(t[0]===n[0])],o=e[r],a=n[r],i<=o&&o<=a||a<=o&&o<=i)}function Sa(){}var Ea=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function ka(){var t=1,n=1,e=I,r=u;function i(t){var n=e(t);if(Array.isArray(n))n=n.slice().sort(xa);else{var r=p(t),i=r[0],a=r[1];n=F(i,a,n),n=Z(Math.floor(i/n)*n,Math.floor(a/n)*n,n)}return n.map((function(n){return o(t,n)}))}function o(e,i){var o=[],u=[];return function(e,r,i){var o,u,c,f,s,l,h=new Array,d=new Array;o=u=-1,f=e[0]>=r,Ea[f<<1].forEach(p);for(;++o<t-1;)c=f,f=e[o+1]>=r,Ea[c|f<<1].forEach(p);Ea[f<<0].forEach(p);for(;++u<n-1;){for(o=-1,f=e[u*t+t]>=r,s=e[u*t]>=r,Ea[f<<1|s<<2].forEach(p);++o<t-1;)c=f,f=e[u*t+t+o+1]>=r,l=s,s=e[u*t+o+1]>=r,Ea[c|f<<1|s<<2|l<<3].forEach(p);Ea[f|s<<3].forEach(p)}o=-1,s=e[u*t]>=r,Ea[s<<2].forEach(p);for(;++o<t-1;)l=s,s=e[u*t+o+1]>=r,Ea[s<<2|l<<3].forEach(p);function p(t){var n,e,r=[t[0][0]+o,t[0][1]+u],c=[t[1][0]+o,t[1][1]+u],f=a(r),s=a(c);(n=d[f])?(e=h[s])?(delete d[n.end],delete h[e.start],n===e?(n.ring.push(c),i(n.ring)):h[n.start]=d[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete d[n.end],n.ring.push(c),d[n.end=s]=n):(n=h[s])?(e=d[f])?(delete h[n.start],delete d[e.end],n===e?(n.ring.push(c),i(n.ring)):h[e.start]=d[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete h[n.start],n.ring.unshift(r),h[n.start=f]=n):h[f]=d[s]={start:f,end:s,ring:[r,c]}}Ea[s<<3].forEach(p)}(e,i,(function(t){r(t,e,i),function(t){for(var n=0,e=t.length,r=t[e-1][1]*t[0][0]-t[e-1][0]*t[0][1];++n<e;)r+=t[n-1][1]*t[n][0]-t[n-1][0]*t[n][1];return r}(t)>0?o.push([t]):u.push(t)})),u.forEach((function(t){for(var n,e=0,r=o.length;e<r;++e)if(-1!==Ma((n=o[e])[0],t))return void n.push(t)})),{type:"MultiPolygon",value:i,coordinates:o}}function a(n){return 2*n[0]+n[1]*(t+1)*4}function u(e,r,i){e.forEach((function(e){var o,a=e[0],u=e[1],c=0|a,f=0|u,s=r[f*t+c];a>0&&a<t&&c===a&&(o=r[f*t+c-1],e[0]=a+(i-o)/(s-o)-.5),u>0&&u<n&&f===u&&(o=r[(f-1)*t+c],e[1]=u+(i-o)/(s-o)-.5)}))}return i.contour=o,i.size=function(e){if(!arguments.length)return[t,n];var r=Math.floor(e[0]),o=Math.floor(e[1]);if(!(r>=0&&o>=0))throw new Error("invalid size");return t=r,n=o,i},i.thresholds=function(t){return arguments.length?(e="function"==typeof t?t:Array.isArray(t)?wa(ma.call(t)):wa(t),i):e},i.smooth=function(t){return arguments.length?(r=t?u:Sa,i):r===u},i}function Na(t,n,e){for(var r=t.width,i=t.height,o=1+(e<<1),a=0;a<i;++a)for(var u=0,c=0;u<r+e;++u)u<r&&(c+=t.data[u+a*r]),u>=e&&(u>=o&&(c-=t.data[u-o+a*r]),n.data[u-e+a*r]=c/Math.min(u+1,r-1+o-u,o))}function Ca(t,n,e){for(var r=t.width,i=t.height,o=1+(e<<1),a=0;a<r;++a)for(var u=0,c=0;u<i+e;++u)u<i&&(c+=t.data[a+u*r]),u>=e&&(u>=o&&(c-=t.data[a+(u-o)*r]),n.data[a+(u-e)*r]=c/Math.min(u+1,i-1+o-u,o))}function Pa(t){return t[0]}function za(t){return t[1]}function Da(){return 1}const qa=Math.pow(2,-52),Ra=new Uint32Array(512);class Fa{static from(t,n=Ha,e=Xa){const r=t.length,i=new Float64Array(2*r);for(let o=0;o<r;o++){const r=t[o];i[2*o]=n(r),i[2*o+1]=e(r)}return new Fa(i)}constructor(t){const n=t.length>>1;if(n>0&&"number"!=typeof t[0])throw new Error("Expected coords to contain numbers.");this.coords=t;const e=Math.max(2*n-5,0);this._triangles=new Uint32Array(3*e),this._halfedges=new Int32Array(3*e),this._hashSize=Math.ceil(Math.sqrt(n)),this._hullPrev=new Uint32Array(n),this._hullNext=new Uint32Array(n),this._hullTri=new Uint32Array(n),this._hullHash=new Int32Array(this._hashSize).fill(-1),this._ids=new Uint32Array(n),this._dists=new Float64Array(n),this.update()}update(){const{coords:t,_hullPrev:n,_hullNext:e,_hullTri:r,_hullHash:i}=this,o=t.length>>1;let a=1/0,u=1/0,c=-1/0,f=-1/0;for(let n=0;n<o;n++){const e=t[2*n],r=t[2*n+1];e<a&&(a=e),r<u&&(u=r),e>c&&(c=e),r>f&&(f=r),this._ids[n]=n}const s=(a+c)/2,l=(u+f)/2;let h,d,p,g=1/0;for(let n=0;n<o;n++){const e=Oa(s,l,t[2*n],t[2*n+1]);e<g&&(h=n,g=e)}const y=t[2*h],v=t[2*h+1];g=1/0;for(let n=0;n<o;n++){if(n===h)continue;const e=Oa(y,v,t[2*n],t[2*n+1]);e<g&&e>0&&(d=n,g=e)}let _=t[2*d],b=t[2*d+1],m=1/0;for(let n=0;n<o;n++){if(n===h||n===d)continue;const e=Ya(y,v,_,b,t[2*n],t[2*n+1]);e<m&&(p=n,m=e)}let x=t[2*p],w=t[2*p+1];if(m===1/0){for(let n=0;n<o;n++)this._dists[n]=t[2*n]-t[0]||t[2*n+1]-t[1];La(this._ids,this._dists,0,o-1);const n=new Uint32Array(o);let e=0;for(let t=0,r=-1/0;t<o;t++){const i=this._ids[t];this._dists[i]>r&&(n[e++]=i,r=this._dists[i])}return this.hull=n.subarray(0,e),this.triangles=new Uint32Array(0),void(this.halfedges=new Uint32Array(0))}if(Ua(y,v,_,b,x,w)){const t=d,n=_,e=b;d=p,_=x,b=w,p=t,x=n,w=e}const M=function(t,n,e,r,i,o){const a=e-t,u=r-n,c=i-t,f=o-n,s=a*a+u*u,l=c*c+f*f,h=.5/(a*f-u*c);return{x:t+(f*s-u*l)*h,y:n+(a*l-c*s)*h}}(y,v,_,b,x,w);this._cx=M.x,this._cy=M.y;for(let n=0;n<o;n++)this._dists[n]=Oa(t[2*n],t[2*n+1],M.x,M.y);La(this._ids,this._dists,0,o-1),this._hullStart=h;let A=3;e[h]=n[p]=d,e[d]=n[h]=p,e[p]=n[d]=h,r[h]=0,r[d]=1,r[p]=2,i.fill(-1),i[this._hashKey(y,v)]=h,i[this._hashKey(_,b)]=d,i[this._hashKey(x,w)]=p,this.trianglesLen=0,this._addTriangle(h,d,p,-1,-1,-1);for(let o,a,u=0;u<this._ids.length;u++){const c=this._ids[u],f=t[2*c],s=t[2*c+1];if(u>0&&Math.abs(f-o)<=qa&&Math.abs(s-a)<=qa)continue;if(o=f,a=s,c===h||c===d||c===p)continue;let l=0;for(let t=0,n=this._hashKey(f,s);t<this._hashSize&&(l=i[(n+t)%this._hashSize],-1===l||l===e[l]);t++);l=n[l];let g,y=l;for(;g=e[y],!Ua(f,s,t[2*y],t[2*y+1],t[2*g],t[2*g+1]);)if(y=g,y===l){y=-1;break}if(-1===y)continue;let v=this._addTriangle(y,c,e[y],-1,-1,r[y]);r[c]=this._legalize(v+2),r[y]=v,A++;let _=e[y];for(;g=e[_],Ua(f,s,t[2*_],t[2*_+1],t[2*g],t[2*g+1]);)v=this._addTriangle(_,c,g,r[c],-1,r[_]),r[c]=this._legalize(v+2),e[_]=_,A--,_=g;if(y===l)for(;g=n[y],Ua(f,s,t[2*g],t[2*g+1],t[2*y],t[2*y+1]);)v=this._addTriangle(g,c,y,-1,r[y],r[g]),this._legalize(v+2),r[g]=v,e[y]=y,A--,y=g;this._hullStart=n[c]=y,e[y]=n[_]=c,e[c]=_,i[this._hashKey(f,s)]=c,i[this._hashKey(t[2*y],t[2*y+1])]=y}this.hull=new Uint32Array(A);for(let t=0,n=this._hullStart;t<A;t++)this.hull[t]=n,n=e[n];this.triangles=this._triangles.subarray(0,this.trianglesLen),this.halfedges=this._halfedges.subarray(0,this.trianglesLen)}_hashKey(t,n){return Math.floor(function(t,n){const e=t/(Math.abs(t)+Math.abs(n));return(n>0?3-e:1+e)/4}(t-this._cx,n-this._cy)*this._hashSize)%this._hashSize}_legalize(t){const{_triangles:n,_halfedges:e,coords:r}=this;let i=0,o=0;for(;;){const a=e[t],u=t-t%3;if(o=u+(t+2)%3,-1===a){if(0===i)break;t=Ra[--i];continue}const c=a-a%3,f=u+(t+1)%3,s=c+(a+2)%3,l=n[o],h=n[t],d=n[f],p=n[s];if(Ba(r[2*l],r[2*l+1],r[2*h],r[2*h+1],r[2*d],r[2*d+1],r[2*p],r[2*p+1])){n[t]=p,n[a]=l;const r=e[s];if(-1===r){let n=this._hullStart;do{if(this._hullTri[n]===s){this._hullTri[n]=t;break}n=this._hullPrev[n]}while(n!==this._hullStart)}this._link(t,r),this._link(a,e[o]),this._link(o,s);const u=c+(a+1)%3;i<Ra.length&&(Ra[i++]=u)}else{if(0===i)break;t=Ra[--i]}}return o}_link(t,n){this._halfedges[t]=n,-1!==n&&(this._halfedges[n]=t)}_addTriangle(t,n,e,r,i,o){const a=this.trianglesLen;return this._triangles[a]=t,this._triangles[a+1]=n,this._triangles[a+2]=e,this._link(a,r),this._link(a+1,i),this._link(a+2,o),this.trianglesLen+=3,a}}function Oa(t,n,e,r){const i=t-e,o=n-r;return i*i+o*o}function Ia(t,n,e,r,i,o){const a=(r-n)*(i-t),u=(e-t)*(o-n);return Math.abs(a-u)>=33306690738754716e-32*Math.abs(a+u)?a-u:0}function Ua(t,n,e,r,i,o){return(Ia(i,o,t,n,e,r)||Ia(t,n,e,r,i,o)||Ia(e,r,i,o,t,n))<0}function Ba(t,n,e,r,i,o,a,u){const c=t-a,f=n-u,s=e-a,l=r-u,h=i-a,d=o-u,p=s*s+l*l,g=h*h+d*d;return c*(l*g-p*d)-f*(s*g-p*h)+(c*c+f*f)*(s*d-l*h)<0}function Ya(t,n,e,r,i,o){const a=e-t,u=r-n,c=i-t,f=o-n,s=a*a+u*u,l=c*c+f*f,h=.5/(a*f-u*c),d=(f*s-u*l)*h,p=(a*l-c*s)*h;return d*d+p*p}function La(t,n,e,r){if(r-e<=20)for(let i=e+1;i<=r;i++){const r=t[i],o=n[r];let a=i-1;for(;a>=e&&n[t[a]]>o;)t[a+1]=t[a--];t[a+1]=r}else{let i=e+1,o=r;ja(t,e+r>>1,i),n[t[e]]>n[t[r]]&&ja(t,e,r),n[t[i]]>n[t[r]]&&ja(t,i,r),n[t[e]]>n[t[i]]&&ja(t,e,i);const a=t[i],u=n[a];for(;;){do{i++}while(n[t[i]]<u);do{o--}while(n[t[o]]>u);if(o<i)break;ja(t,i,o)}t[e+1]=t[o],t[o]=a,r-i+1>=o-e?(La(t,n,i,r),La(t,n,e,o-1)):(La(t,n,e,o-1),La(t,n,i,r))}}function ja(t,n,e){const r=t[n];t[n]=t[e],t[e]=r}function Ha(t){return t[0]}function Xa(t){return t[1]}const Ga=1e-6;class Va{constructor(){this._x0=this._y0=this._x1=this._y1=null,this._=""}moveTo(t,n){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}`}closePath(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")}lineTo(t,n){this._+=`L${this._x1=+t},${this._y1=+n}`}arc(t,n,e){const r=(t=+t)+(e=+e),i=n=+n;if(e<0)throw new Error("negative radius");null===this._x1?this._+=`M${r},${i}`:(Math.abs(this._x1-r)>Ga||Math.abs(this._y1-i)>Ga)&&(this._+="L"+r+","+i),e&&(this._+=`A${e},${e},0,1,1,${t-e},${n}A${e},${e},0,1,1,${this._x1=r},${this._y1=i}`)}rect(t,n,e,r){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${+e}v${+r}h${-e}Z`}value(){return this._||null}}class $a{constructor(){this._=[]}moveTo(t,n){this._.push([t,n])}closePath(){this._.push(this._[0].slice())}lineTo(t,n){this._.push([t,n])}value(){return this._.length?this._:null}}class Wa{constructor(t,[n,e,r,i]=[0,0,960,500]){if(!((r=+r)>=(n=+n)&&(i=+i)>=(e=+e)))throw new Error("invalid bounds");this.delaunay=t,this._circumcenters=new Float64Array(2*t.points.length),this.vectors=new Float64Array(2*t.points.length),this.xmax=r,this.xmin=n,this.ymax=i,this.ymin=e,this._init()}update(){return this.delaunay.update(),this._init(),this}_init(){const{delaunay:{points:t,hull:n,triangles:e},vectors:r}=this,i=this.circumcenters=this._circumcenters.subarray(0,e.length/3*2);for(let n,r,o=0,a=0,u=e.length;o<u;o+=3,a+=2){const u=2*e[o],c=2*e[o+1],f=2*e[o+2],s=t[u],l=t[u+1],h=t[c],d=t[c+1],p=t[f],g=t[f+1],y=h-s,v=d-l,_=p-s,b=g-l,m=y*y+v*v,x=_*_+b*b,w=2*(y*b-v*_);if(w)if(Math.abs(w)<1e-8)n=(s+p)/2,r=(l+g)/2;else{const t=1/w;n=s+(b*m-v*x)*t,r=l+(y*x-_*m)*t}else n=(s+p)/2-1e8*b,r=(l+g)/2+1e8*_;i[a]=n,i[a+1]=r}let o,a,u,c=n[n.length-1],f=4*c,s=t[2*c],l=t[2*c+1];r.fill(0);for(let e=0;e<n.length;++e)c=n[e],o=f,a=s,u=l,f=4*c,s=t[2*c],l=t[2*c+1],r[o+2]=r[f]=u-l,r[o+3]=r[f+1]=s-a}render(t){const n=null==t?t=new Va:void 0,{delaunay:{halfedges:e,inedges:r,hull:i},circumcenters:o,vectors:a}=this;if(i.length<=1)return null;for(let n=0,r=e.length;n<r;++n){const r=e[n];if(r<n)continue;const i=2*Math.floor(n/3),a=2*Math.floor(r/3),u=o[i],c=o[i+1],f=o[a],s=o[a+1];this._renderSegment(u,c,f,s,t)}let u,c=i[i.length-1];for(let n=0;n<i.length;++n){u=c,c=i[n];const e=2*Math.floor(r[c]/3),f=o[e],s=o[e+1],l=4*u,h=this._project(f,s,a[l+2],a[l+3]);h&&this._renderSegment(f,s,h[0],h[1],t)}return n&&n.value()}renderBounds(t){const n=null==t?t=new Va:void 0;return t.rect(this.xmin,this.ymin,this.xmax-this.xmin,this.ymax-this.ymin),n&&n.value()}renderCell(t,n){const e=null==n?n=new Va:void 0,r=this._clip(t);if(null===r||!r.length)return;n.moveTo(r[0],r[1]);let i=r.length;for(;r[0]===r[i-2]&&r[1]===r[i-1]&&i>1;)i-=2;for(let t=2;t<i;t+=2)r[t]===r[t-2]&&r[t+1]===r[t-1]||n.lineTo(r[t],r[t+1]);return n.closePath(),e&&e.value()}*cellPolygons(){const{delaunay:{points:t}}=this;for(let n=0,e=t.length/2;n<e;++n){const t=this.cellPolygon(n);t&&(t.index=n,yield t)}}cellPolygon(t){const n=new $a;return this.renderCell(t,n),n.value()}_renderSegment(t,n,e,r,i){let o;const a=this._regioncode(t,n),u=this._regioncode(e,r);0===a&&0===u?(i.moveTo(t,n),i.lineTo(e,r)):(o=this._clipSegment(t,n,e,r,a,u))&&(i.moveTo(o[0],o[1]),i.lineTo(o[2],o[3]))}contains(t,n,e){return(n=+n)==n&&(e=+e)==e&&this.delaunay._step(t,n,e)===t}*neighbors(t){const n=this._clip(t);if(n)for(const e of this.delaunay.neighbors(t)){const t=this._clip(e);if(t)t:for(let r=0,i=n.length;r<i;r+=2)for(let o=0,a=t.length;o<a;o+=2)if(n[r]==t[o]&&n[r+1]==t[o+1]&&n[(r+2)%i]==t[(o+a-2)%a]&&n[(r+3)%i]==t[(o+a-1)%a]){yield e;break t}}}_cell(t){const{circumcenters:n,delaunay:{inedges:e,halfedges:r,triangles:i}}=this,o=e[t];if(-1===o)return null;const a=[];let u=o;do{const e=Math.floor(u/3);if(a.push(n[2*e],n[2*e+1]),u=u%3==2?u-2:u+1,i[u]!==t)break;u=r[u]}while(u!==o&&-1!==u);return a}_clip(t){if(0===t&&1===this.delaunay.hull.length)return[this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax,this.xmin,this.ymin];const n=this._cell(t);if(null===n)return null;const{vectors:e}=this,r=4*t;return e[r]||e[r+1]?this._clipInfinite(t,n,e[r],e[r+1],e[r+2],e[r+3]):this._clipFinite(t,n)}_clipFinite(t,n){const e=n.length;let r,i,o,a,u,c=null,f=n[e-2],s=n[e-1],l=this._regioncode(f,s);for(let h=0;h<e;h+=2)if(r=f,i=s,f=n[h],s=n[h+1],o=l,l=this._regioncode(f,s),0===o&&0===l)a=u,u=0,c?c.push(f,s):c=[f,s];else{let n,e,h,d,p;if(0===o){if(null===(n=this._clipSegment(r,i,f,s,o,l)))continue;[e,h,d,p]=n}else{if(null===(n=this._clipSegment(f,s,r,i,l,o)))continue;[d,p,e,h]=n,a=u,u=this._edgecode(e,h),a&&u&&this._edge(t,a,u,c,c.length),c?c.push(e,h):c=[e,h]}a=u,u=this._edgecode(d,p),a&&u&&this._edge(t,a,u,c,c.length),c?c.push(d,p):c=[d,p]}if(c)a=u,u=this._edgecode(c[0],c[1]),a&&u&&this._edge(t,a,u,c,c.length);else if(this.contains(t,(this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2))return[this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax,this.xmin,this.ymin];return c}_clipSegment(t,n,e,r,i,o){for(;;){if(0===i&&0===o)return[t,n,e,r];if(i&o)return null;let a,u,c=i||o;8&c?(a=t+(e-t)*(this.ymax-n)/(r-n),u=this.ymax):4&c?(a=t+(e-t)*(this.ymin-n)/(r-n),u=this.ymin):2&c?(u=n+(r-n)*(this.xmax-t)/(e-t),a=this.xmax):(u=n+(r-n)*(this.xmin-t)/(e-t),a=this.xmin),i?(t=a,n=u,i=this._regioncode(t,n)):(e=a,r=u,o=this._regioncode(e,r))}}_clipInfinite(t,n,e,r,i,o){let a,u=Array.from(n);if((a=this._project(u[0],u[1],e,r))&&u.unshift(a[0],a[1]),(a=this._project(u[u.length-2],u[u.length-1],i,o))&&u.push(a[0],a[1]),u=this._clipFinite(t,u))for(let n,e=0,r=u.length,i=this._edgecode(u[r-2],u[r-1]);e<r;e+=2)n=i,i=this._edgecode(u[e],u[e+1]),n&&i&&(e=this._edge(t,n,i,u,e),r=u.length);else this.contains(t,(this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2)&&(u=[this.xmin,this.ymin,this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax]);return u}_edge(t,n,e,r,i){for(;n!==e;){let e,o;switch(n){case 5:n=4;continue;case 4:n=6,e=this.xmax,o=this.ymin;break;case 6:n=2;continue;case 2:n=10,e=this.xmax,o=this.ymax;break;case 10:n=8;continue;case 8:n=9,e=this.xmin,o=this.ymax;break;case 9:n=1;continue;case 1:n=5,e=this.xmin,o=this.ymin}r[i]===e&&r[i+1]===o||!this.contains(t,e,o)||(r.splice(i,0,e,o),i+=2)}if(r.length>4)for(let t=0;t<r.length;t+=2){const n=(t+2)%r.length,e=(t+4)%r.length;(r[t]===r[n]&&r[n]===r[e]||r[t+1]===r[n+1]&&r[n+1]===r[e+1])&&(r.splice(n,2),t-=2)}return i}_project(t,n,e,r){let i,o,a,u=1/0;if(r<0){if(n<=this.ymin)return null;(i=(this.ymin-n)/r)<u&&(a=this.ymin,o=t+(u=i)*e)}else if(r>0){if(n>=this.ymax)return null;(i=(this.ymax-n)/r)<u&&(a=this.ymax,o=t+(u=i)*e)}if(e>0){if(t>=this.xmax)return null;(i=(this.xmax-t)/e)<u&&(o=this.xmax,a=n+(u=i)*r)}else if(e<0){if(t<=this.xmin)return null;(i=(this.xmin-t)/e)<u&&(o=this.xmin,a=n+(u=i)*r)}return[o,a]}_edgecode(t,n){return(t===this.xmin?1:t===this.xmax?2:0)|(n===this.ymin?4:n===this.ymax?8:0)}_regioncode(t,n){return(t<this.xmin?1:t>this.xmax?2:0)|(n<this.ymin?4:n>this.ymax?8:0)}}const Za=2*Math.PI,Ka=Math.pow;function Qa(t){return t[0]}function Ja(t){return t[1]}function tu(t,n,e){return[t+Math.sin(t+n)*e,n+Math.cos(t-n)*e]}class nu{static from(t,n=Qa,e=Ja,r){return new nu("length"in t?function(t,n,e,r){const i=t.length,o=new Float64Array(2*i);for(let a=0;a<i;++a){const i=t[a];o[2*a]=n.call(r,i,a,t),o[2*a+1]=e.call(r,i,a,t)}return o}(t,n,e,r):Float64Array.from(function*(t,n,e,r){let i=0;for(const o of t)yield n.call(r,o,i,t),yield e.call(r,o,i,t),++i}(t,n,e,r)))}constructor(t){this._delaunator=new Fa(t),this.inedges=new Int32Array(t.length/2),this._hullIndex=new Int32Array(t.length/2),this.points=this._delaunator.coords,this._init()}update(){return this._delaunator.update(),this._init(),this}_init(){const t=this._delaunator,n=this.points;if(t.hull&&t.hull.length>2&&function(t){const{triangles:n,coords:e}=t;for(let t=0;t<n.length;t+=3){const r=2*n[t],i=2*n[t+1],o=2*n[t+2];if((e[o]-e[r])*(e[i+1]-e[r+1])-(e[i]-e[r])*(e[o+1]-e[r+1])>1e-10)return!1}return!0}(t)){this.collinear=Int32Array.from({length:n.length/2},((t,n)=>n)).sort(((t,e)=>n[2*t]-n[2*e]||n[2*t+1]-n[2*e+1]));const t=this.collinear[0],e=this.collinear[this.collinear.length-1],r=[n[2*t],n[2*t+1],n[2*e],n[2*e+1]],i=1e-8*Math.hypot(r[3]-r[1],r[2]-r[0]);for(let t=0,e=n.length/2;t<e;++t){const e=tu(n[2*t],n[2*t+1],i);n[2*t]=e[0],n[2*t+1]=e[1]}this._delaunator=new Fa(n)}else delete this.collinear;const e=this.halfedges=this._delaunator.halfedges,r=this.hull=this._delaunator.hull,i=this.triangles=this._delaunator.triangles,o=this.inedges.fill(-1),a=this._hullIndex.fill(-1);for(let t=0,n=e.length;t<n;++t){const n=i[t%3==2?t-2:t+1];-1!==e[t]&&-1!==o[n]||(o[n]=t)}for(let t=0,n=r.length;t<n;++t)a[r[t]]=t;r.length<=2&&r.length>0&&(this.triangles=new Int32Array(3).fill(-1),this.halfedges=new Int32Array(3).fill(-1),this.triangles[0]=r[0],this.triangles[1]=r[1],this.triangles[2]=r[1],o[r[0]]=1,2===r.length&&(o[r[1]]=0))}voronoi(t){return new Wa(this,t)}*neighbors(t){const{inedges:n,hull:e,_hullIndex:r,halfedges:i,triangles:o,collinear:a}=this;if(a){const n=a.indexOf(t);return n>0&&(yield a[n-1]),void(n<a.length-1&&(yield a[n+1]))}const u=n[t];if(-1===u)return;let c=u,f=-1;do{if(yield f=o[c],c=c%3==2?c-2:c+1,o[c]!==t)return;if(c=i[c],-1===c){const n=e[(r[t]+1)%e.length];return void(n!==f&&(yield n))}}while(c!==u)}find(t,n,e=0){if((t=+t)!=t||(n=+n)!=n)return-1;const r=e;let i;for(;(i=this._step(e,t,n))>=0&&i!==e&&i!==r;)e=i;return i}_step(t,n,e){const{inedges:r,hull:i,_hullIndex:o,halfedges:a,triangles:u,points:c}=this;if(-1===r[t]||!c.length)return(t+1)%(c.length>>1);let f=t,s=Ka(n-c[2*t],2)+Ka(e-c[2*t+1],2);const l=r[t];let h=l;do{let r=u[h];const l=Ka(n-c[2*r],2)+Ka(e-c[2*r+1],2);if(l<s&&(s=l,f=r),h=h%3==2?h-2:h+1,u[h]!==t)break;if(h=a[h],-1===h){if(h=i[(o[t]+1)%i.length],h!==r&&Ka(n-c[2*h],2)+Ka(e-c[2*h+1],2)<s)return h;break}}while(h!==l);return f}render(t){const n=null==t?t=new Va:void 0,{points:e,halfedges:r,triangles:i}=this;for(let n=0,o=r.length;n<o;++n){const o=r[n];if(o<n)continue;const a=2*i[n],u=2*i[o];t.moveTo(e[a],e[a+1]),t.lineTo(e[u],e[u+1])}return this.renderHull(t),n&&n.value()}renderPoints(t,n=2){const e=null==t?t=new Va:void 0,{points:r}=this;for(let e=0,i=r.length;e<i;e+=2){const i=r[e],o=r[e+1];t.moveTo(i+n,o),t.arc(i,o,n,0,Za)}return e&&e.value()}renderHull(t){const n=null==t?t=new Va:void 0,{hull:e,points:r}=this,i=2*e[0],o=e.length;t.moveTo(r[i],r[i+1]);for(let n=1;n<o;++n){const i=2*e[n];t.lineTo(r[i],r[i+1])}return t.closePath(),n&&n.value()}hullPolygon(){const t=new $a;return this.renderHull(t),t.value()}renderTriangle(t,n){const e=null==n?n=new Va:void 0,{points:r,triangles:i}=this,o=2*i[t*=3],a=2*i[t+1],u=2*i[t+2];return n.moveTo(r[o],r[o+1]),n.lineTo(r[a],r[a+1]),n.lineTo(r[u],r[u+1]),n.closePath(),e&&e.value()}*trianglePolygons(){const{triangles:t}=this;for(let n=0,e=t.length/3;n<e;++n)yield this.trianglePolygon(n)}trianglePolygon(t){const n=new $a;return this.renderTriangle(t,n),n.value()}}var eu={},ru={};function iu(t){return new Function("d","return {"+t.map((function(t,n){return JSON.stringify(t)+": d["+n+'] || ""'})).join(",")+"}")}function ou(t){var n=Object.create(null),e=[];return t.forEach((function(t){for(var r in t)r in n||e.push(n[r]=r)})),e}function au(t,n){var e=t+"",r=e.length;return r<n?new Array(n-r+1).join(0)+e:e}function uu(t){var n=t.getUTCHours(),e=t.getUTCMinutes(),r=t.getUTCSeconds(),i=t.getUTCMilliseconds();return isNaN(t)?"Invalid Date":function(t){return t<0?"-"+au(-t,6):t>9999?"+"+au(t,6):au(t,4)}(t.getUTCFullYear())+"-"+au(t.getUTCMonth()+1,2)+"-"+au(t.getUTCDate(),2)+(i?"T"+au(n,2)+":"+au(e,2)+":"+au(r,2)+"."+au(i,3)+"Z":r?"T"+au(n,2)+":"+au(e,2)+":"+au(r,2)+"Z":e||n?"T"+au(n,2)+":"+au(e,2)+"Z":"")}function cu(t){var n=new RegExp('["'+t+"\n\r]"),e=t.charCodeAt(0);function r(t,n){var r,i=[],o=t.length,a=0,u=0,c=o<=0,f=!1;function s(){if(c)return ru;if(f)return f=!1,eu;var n,r,i=a;if(34===t.charCodeAt(i)){for(;a++<o&&34!==t.charCodeAt(a)||34===t.charCodeAt(++a););return(n=a)>=o?c=!0:10===(r=t.charCodeAt(a++))?f=!0:13===r&&(f=!0,10===t.charCodeAt(a)&&++a),t.slice(i+1,n-1).replace(/""/g,'"')}for(;a<o;){if(10===(r=t.charCodeAt(n=a++)))f=!0;else if(13===r)f=!0,10===t.charCodeAt(a)&&++a;else if(r!==e)continue;return t.slice(i,n)}return c=!0,t.slice(i,o)}for(10===t.charCodeAt(o-1)&&--o,13===t.charCodeAt(o-1)&&--o;(r=s())!==ru;){for(var l=[];r!==eu&&r!==ru;)l.push(r),r=s();n&&null==(l=n(l,u++))||i.push(l)}return i}function i(n,e){return n.map((function(n){return e.map((function(t){return a(n[t])})).join(t)}))}function o(n){return n.map(a).join(t)}function a(t){return null==t?"":t instanceof Date?uu(t):n.test(t+="")?'"'+t.replace(/"/g,'""')+'"':t}return{parse:function(t,n){var e,i,o=r(t,(function(t,r){if(e)return e(t,r-1);i=t,e=n?function(t,n){var e=iu(t);return function(r,i){return n(e(r),i,t)}}(t,n):iu(t)}));return o.columns=i||[],o},parseRows:r,format:function(n,e){return null==e&&(e=ou(n)),[e.map(a).join(t)].concat(i(n,e)).join("\n")},formatBody:function(t,n){return null==n&&(n=ou(t)),i(t,n).join("\n")},formatRows:function(t){return t.map(o).join("\n")},formatRow:o,formatValue:a}}var fu=cu(","),su=fu.parse,lu=fu.parseRows,hu=fu.format,du=fu.formatBody,pu=fu.formatRows,gu=fu.formatRow,yu=fu.formatValue,vu=cu("\t"),_u=vu.parse,bu=vu.parseRows,mu=vu.format,xu=vu.formatBody,wu=vu.formatRows,Mu=vu.formatRow,Au=vu.formatValue;const Tu=new Date("2019-01-01T00:00").getHours()||new Date("2019-07-01T00:00").getHours();function Su(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.blob()}function Eu(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.arrayBuffer()}function ku(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.text()}function Nu(t,n){return fetch(t,n).then(ku)}function Cu(t){return function(n,e,r){return 2===arguments.length&&"function"==typeof e&&(r=e,e=void 0),Nu(n,e).then((function(n){return t(n,r)}))}}var Pu=Cu(su),zu=Cu(_u);function Du(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);if(204!==t.status&&205!==t.status)return t.json()}function qu(t){return(n,e)=>Nu(n,e).then((n=>(new DOMParser).parseFromString(n,t)))}var Ru=qu("application/xml"),Fu=qu("text/html"),Ou=qu("image/svg+xml");function Iu(t,n,e,r){if(isNaN(n)||isNaN(e))return t;var i,o,a,u,c,f,s,l,h,d=t._root,p={data:r},g=t._x0,y=t._y0,v=t._x1,_=t._y1;if(!d)return t._root=p,t;for(;d.length;)if((f=n>=(o=(g+v)/2))?g=o:v=o,(s=e>=(a=(y+_)/2))?y=a:_=a,i=d,!(d=d[l=s<<1|f]))return i[l]=p,t;if(u=+t._x.call(null,d.data),c=+t._y.call(null,d.data),n===u&&e===c)return p.next=d,i?i[l]=p:t._root=p,t;do{i=i?i[l]=new Array(4):t._root=new Array(4),(f=n>=(o=(g+v)/2))?g=o:v=o,(s=e>=(a=(y+_)/2))?y=a:_=a}while((l=s<<1|f)==(h=(c>=a)<<1|u>=o));return i[h]=d,i[l]=p,t}function Uu(t,n,e,r,i){this.node=t,this.x0=n,this.y0=e,this.x1=r,this.y1=i}function Bu(t){return t[0]}function Yu(t){return t[1]}function Lu(t,n,e){var r=new ju(null==n?Bu:n,null==e?Yu:e,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function ju(t,n,e,r,i,o){this._x=t,this._y=n,this._x0=e,this._y0=r,this._x1=i,this._y1=o,this._root=void 0}function Hu(t){for(var n={data:t.data},e=n;t=t.next;)e=e.next={data:t.data};return n}var Xu=Lu.prototype=ju.prototype;function Gu(t){return function(){return t}}function Vu(t){return 1e-6*(t()-.5)}function $u(t){return t.x+t.vx}function Wu(t){return t.y+t.vy}function Zu(t){return t.index}function Ku(t,n){var e=t.get(n);if(!e)throw new Error("node not found: "+n);return e}Xu.copy=function(){var t,n,e=new ju(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return e;if(!r.length)return e._root=Hu(r),e;for(t=[{source:r,target:e._root=new Array(4)}];r=t.pop();)for(var i=0;i<4;++i)(n=r.source[i])&&(n.length?t.push({source:n,target:r.target[i]=new Array(4)}):r.target[i]=Hu(n));return e},Xu.add=function(t){const n=+this._x.call(null,t),e=+this._y.call(null,t);return Iu(this.cover(n,e),n,e,t)},Xu.addAll=function(t){var n,e,r,i,o=t.length,a=new Array(o),u=new Array(o),c=1/0,f=1/0,s=-1/0,l=-1/0;for(e=0;e<o;++e)isNaN(r=+this._x.call(null,n=t[e]))||isNaN(i=+this._y.call(null,n))||(a[e]=r,u[e]=i,r<c&&(c=r),r>s&&(s=r),i<f&&(f=i),i>l&&(l=i));if(c>s||f>l)return this;for(this.cover(c,f).cover(s,l),e=0;e<o;++e)Iu(this,a[e],u[e],t[e]);return this},Xu.cover=function(t,n){if(isNaN(t=+t)||isNaN(n=+n))return this;var e=this._x0,r=this._y0,i=this._x1,o=this._y1;if(isNaN(e))i=(e=Math.floor(t))+1,o=(r=Math.floor(n))+1;else{for(var a,u,c=i-e||1,f=this._root;e>t||t>=i||r>n||n>=o;)switch(u=(n<r)<<1|t<e,(a=new Array(4))[u]=f,f=a,c*=2,u){case 0:i=e+c,o=r+c;break;case 1:e=i-c,o=r+c;break;case 2:i=e+c,r=o-c;break;case 3:e=i-c,r=o-c}this._root&&this._root.length&&(this._root=f)}return this._x0=e,this._y0=r,this._x1=i,this._y1=o,this},Xu.data=function(){var t=[];return this.visit((function(n){if(!n.length)do{t.push(n.data)}while(n=n.next)})),t},Xu.extent=function(t){return arguments.length?this.cover(+t[0][0],+t[0][1]).cover(+t[1][0],+t[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},Xu.find=function(t,n,e){var r,i,o,a,u,c,f,s=this._x0,l=this._y0,h=this._x1,d=this._y1,p=[],g=this._root;for(g&&p.push(new Uu(g,s,l,h,d)),null==e?e=1/0:(s=t-e,l=n-e,h=t+e,d=n+e,e*=e);c=p.pop();)if(!(!(g=c.node)||(i=c.x0)>h||(o=c.y0)>d||(a=c.x1)<s||(u=c.y1)<l))if(g.length){var y=(i+a)/2,v=(o+u)/2;p.push(new Uu(g[3],y,v,a,u),new Uu(g[2],i,v,y,u),new Uu(g[1],y,o,a,v),new Uu(g[0],i,o,y,v)),(f=(n>=v)<<1|t>=y)&&(c=p[p.length-1],p[p.length-1]=p[p.length-1-f],p[p.length-1-f]=c)}else{var _=t-+this._x.call(null,g.data),b=n-+this._y.call(null,g.data),m=_*_+b*b;if(m<e){var x=Math.sqrt(e=m);s=t-x,l=n-x,h=t+x,d=n+x,r=g.data}}return r},Xu.remove=function(t){if(isNaN(o=+this._x.call(null,t))||isNaN(a=+this._y.call(null,t)))return this;var n,e,r,i,o,a,u,c,f,s,l,h,d=this._root,p=this._x0,g=this._y0,y=this._x1,v=this._y1;if(!d)return this;if(d.length)for(;;){if((f=o>=(u=(p+y)/2))?p=u:y=u,(s=a>=(c=(g+v)/2))?g=c:v=c,n=d,!(d=d[l=s<<1|f]))return this;if(!d.length)break;(n[l+1&3]||n[l+2&3]||n[l+3&3])&&(e=n,h=l)}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):n?(i?n[l]=i:delete n[l],(d=n[0]||n[1]||n[2]||n[3])&&d===(n[3]||n[2]||n[1]||n[0])&&!d.length&&(e?e[h]=d:this._root=d),this):(this._root=i,this)},Xu.removeAll=function(t){for(var n=0,e=t.length;n<e;++n)this.remove(t[n]);return this},Xu.root=function(){return this._root},Xu.size=function(){var t=0;return this.visit((function(n){if(!n.length)do{++t}while(n=n.next)})),t},Xu.visit=function(t){var n,e,r,i,o,a,u=[],c=this._root;for(c&&u.push(new Uu(c,this._x0,this._y0,this._x1,this._y1));n=u.pop();)if(!t(c=n.node,r=n.x0,i=n.y0,o=n.x1,a=n.y1)&&c.length){var f=(r+o)/2,s=(i+a)/2;(e=c[3])&&u.push(new Uu(e,f,s,o,a)),(e=c[2])&&u.push(new Uu(e,r,s,f,a)),(e=c[1])&&u.push(new Uu(e,f,i,o,s)),(e=c[0])&&u.push(new Uu(e,r,i,f,s))}return this},Xu.visitAfter=function(t){var n,e=[],r=[];for(this._root&&e.push(new Uu(this._root,this._x0,this._y0,this._x1,this._y1));n=e.pop();){var i=n.node;if(i.length){var o,a=n.x0,u=n.y0,c=n.x1,f=n.y1,s=(a+c)/2,l=(u+f)/2;(o=i[0])&&e.push(new Uu(o,a,u,s,l)),(o=i[1])&&e.push(new Uu(o,s,u,c,l)),(o=i[2])&&e.push(new Uu(o,a,l,s,f)),(o=i[3])&&e.push(new Uu(o,s,l,c,f))}r.push(n)}for(;n=r.pop();)t(n.node,n.x0,n.y0,n.x1,n.y1);return this},Xu.x=function(t){return arguments.length?(this._x=t,this):this._x},Xu.y=function(t){return arguments.length?(this._y=t,this):this._y};const Qu=4294967296;function Ju(t){return t.x}function tc(t){return t.y}var nc=Math.PI*(3-Math.sqrt(5));function ec(t,n){if((e=(t=n?t.toExponential(n-1):t.toExponential()).indexOf("e"))<0)return null;var e,r=t.slice(0,e);return[r.length>1?r[0]+r.slice(2):r,+t.slice(e+1)]}function rc(t){return(t=ec(Math.abs(t)))?t[1]:NaN}var ic,oc=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function ac(t){if(!(n=oc.exec(t)))throw new Error("invalid format: "+t);var n;return new uc({fill:n[1],align:n[2],sign:n[3],symbol:n[4],zero:n[5],width:n[6],comma:n[7],precision:n[8]&&n[8].slice(1),trim:n[9],type:n[10]})}function uc(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}function cc(t,n){var e=ec(t,n);if(!e)return t+"";var r=e[0],i=e[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}ac.prototype=uc.prototype,uc.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var fc={"%":(t,n)=>(100*t).toFixed(n),b:t=>Math.round(t).toString(2),c:t=>t+"",d:function(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)},e:(t,n)=>t.toExponential(n),f:(t,n)=>t.toFixed(n),g:(t,n)=>t.toPrecision(n),o:t=>Math.round(t).toString(8),p:(t,n)=>cc(100*t,n),r:cc,s:function(t,n){var e=ec(t,n);if(!e)return t+"";var r=e[0],i=e[1],o=i-(ic=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,a=r.length;return o===a?r:o>a?r+new Array(o-a+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+ec(t,Math.max(0,n+o-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function sc(t){return t}var lc,hc=Array.prototype.map,dc=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function pc(t){var n,e,r=void 0===t.grouping||void 0===t.thousands?sc:(n=hc.call(t.grouping,Number),e=t.thousands+"",function(t,r){for(var i=t.length,o=[],a=0,u=n[0],c=0;i>0&&u>0&&(c+u+1>r&&(u=Math.max(1,r-c)),o.push(t.substring(i-=u,i+u)),!((c+=u+1)>r));)u=n[a=(a+1)%n.length];return o.reverse().join(e)}),i=void 0===t.currency?"":t.currency[0]+"",o=void 0===t.currency?"":t.currency[1]+"",a=void 0===t.decimal?".":t.decimal+"",u=void 0===t.numerals?sc:function(t){return function(n){return n.replace(/[0-9]/g,(function(n){return t[+n]}))}}(hc.call(t.numerals,String)),c=void 0===t.percent?"%":t.percent+"",f=void 0===t.minus?"−":t.minus+"",s=void 0===t.nan?"NaN":t.nan+"";function l(t){var n=(t=ac(t)).fill,e=t.align,l=t.sign,h=t.symbol,d=t.zero,p=t.width,g=t.comma,y=t.precision,v=t.trim,_=t.type;"n"===_?(g=!0,_="g"):fc[_]||(void 0===y&&(y=12),v=!0,_="g"),(d||"0"===n&&"="===e)&&(d=!0,n="0",e="=");var b="$"===h?i:"#"===h&&/[boxX]/.test(_)?"0"+_.toLowerCase():"",m="$"===h?o:/[%p]/.test(_)?c:"",x=fc[_],w=/[defgprs%]/.test(_);function M(t){var i,o,c,h=b,M=m;if("c"===_)M=x(t)+M,t="";else{var A=(t=+t)<0||1/t<0;if(t=isNaN(t)?s:x(Math.abs(t),y),v&&(t=function(t){t:for(var n,e=t.length,r=1,i=-1;r<e;++r)switch(t[r]){case".":i=n=r;break;case"0":0===i&&(i=r),n=r;break;default:if(!+t[r])break t;i>0&&(i=0)}return i>0?t.slice(0,i)+t.slice(n+1):t}(t)),A&&0==+t&&"+"!==l&&(A=!1),h=(A?"("===l?l:f:"-"===l||"("===l?"":l)+h,M=("s"===_?dc[8+ic/3]:"")+M+(A&&"("===l?")":""),w)for(i=-1,o=t.length;++i<o;)if(48>(c=t.charCodeAt(i))||c>57){M=(46===c?a+t.slice(i+1):t.slice(i))+M,t=t.slice(0,i);break}}g&&!d&&(t=r(t,1/0));var T=h.length+t.length+M.length,S=T<p?new Array(p-T+1).join(n):"";switch(g&&d&&(t=r(S+t,S.length?p-M.length:1/0),S=""),e){case"<":t=h+t+M+S;break;case"=":t=h+S+t+M;break;case"^":t=S.slice(0,T=S.length>>1)+h+t+M+S.slice(T);break;default:t=S+h+t+M}return u(t)}return y=void 0===y?6:/[gprs]/.test(_)?Math.max(1,Math.min(21,y)):Math.max(0,Math.min(20,y)),M.toString=function(){return t+""},M}return{format:l,formatPrefix:function(t,n){var e=l(((t=ac(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(rc(n)/3))),i=Math.pow(10,-r),o=dc[8+r/3];return function(t){return e(i*t)+o}}}}function gc(n){return lc=pc(n),t.format=lc.format,t.formatPrefix=lc.formatPrefix,lc}function yc(t){return Math.max(0,-rc(Math.abs(t)))}function vc(t,n){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(rc(n)/3)))-rc(Math.abs(t)))}function _c(t,n){return t=Math.abs(t),n=Math.abs(n)-t,Math.max(0,rc(n)-rc(t))+1}t.format=void 0,t.formatPrefix=void 0,gc({thousands:",",grouping:[3],currency:["$",""]});var bc=1e-6,mc=1e-12,xc=Math.PI,wc=xc/2,Mc=xc/4,Ac=2*xc,Tc=180/xc,Sc=xc/180,Ec=Math.abs,kc=Math.atan,Nc=Math.atan2,Cc=Math.cos,Pc=Math.ceil,zc=Math.exp,Dc=Math.hypot,qc=Math.log,Rc=Math.pow,Fc=Math.sin,Oc=Math.sign||function(t){return t>0?1:t<0?-1:0},Ic=Math.sqrt,Uc=Math.tan;function Bc(t){return t>1?0:t<-1?xc:Math.acos(t)}function Yc(t){return t>1?wc:t<-1?-wc:Math.asin(t)}function Lc(t){return(t=Fc(t/2))*t}function jc(){}function Hc(t,n){t&&Gc.hasOwnProperty(t.type)&&Gc[t.type](t,n)}var Xc={Feature:function(t,n){Hc(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r<i;)Hc(e[r].geometry,n)}},Gc={Sphere:function(t,n){n.sphere()},Point:function(t,n){t=t.coordinates,n.point(t[0],t[1],t[2])},MultiPoint:function(t,n){for(var e=t.coordinates,r=-1,i=e.length;++r<i;)t=e[r],n.point(t[0],t[1],t[2])},LineString:function(t,n){Vc(t.coordinates,n,0)},MultiLineString:function(t,n){for(var e=t.coordinates,r=-1,i=e.length;++r<i;)Vc(e[r],n,0)},Polygon:function(t,n){$c(t.coordinates,n)},MultiPolygon:function(t,n){for(var e=t.coordinates,r=-1,i=e.length;++r<i;)$c(e[r],n)},GeometryCollection:function(t,n){for(var e=t.geometries,r=-1,i=e.length;++r<i;)Hc(e[r],n)}};function Vc(t,n,e){var r,i=-1,o=t.length-e;for(n.lineStart();++i<o;)r=t[i],n.point(r[0],r[1],r[2]);n.lineEnd()}function $c(t,n){var e=-1,r=t.length;for(n.polygonStart();++e<r;)Vc(t[e],n,1);n.polygonEnd()}function Wc(t,n){t&&Xc.hasOwnProperty(t.type)?Xc[t.type](t,n):Hc(t,n)}var Zc,Kc,Qc,Jc,tf,nf,ef,rf,of,af,uf,cf,ff,sf,lf,hf,df=new g,pf=new g,gf={point:jc,lineStart:jc,lineEnd:jc,polygonStart:function(){df=new g,gf.lineStart=yf,gf.lineEnd=vf},polygonEnd:function(){var t=+df;pf.add(t<0?Ac+t:t),this.lineStart=this.lineEnd=this.point=jc},sphere:function(){pf.add(Ac)}};function yf(){gf.point=_f}function vf(){bf(Zc,Kc)}function _f(t,n){gf.point=bf,Zc=t,Kc=n,Qc=t*=Sc,Jc=Cc(n=(n*=Sc)/2+Mc),tf=Fc(n)}function bf(t,n){var e=(t*=Sc)-Qc,r=e>=0?1:-1,i=r*e,o=Cc(n=(n*=Sc)/2+Mc),a=Fc(n),u=tf*a,c=Jc*o+u*Cc(i),f=u*r*Fc(i);df.add(Nc(f,c)),Qc=t,Jc=o,tf=a}function mf(t){return[Nc(t[1],t[0]),Yc(t[2])]}function xf(t){var n=t[0],e=t[1],r=Cc(e);return[r*Cc(n),r*Fc(n),Fc(e)]}function wf(t,n){return t[0]*n[0]+t[1]*n[1]+t[2]*n[2]}function Mf(t,n){return[t[1]*n[2]-t[2]*n[1],t[2]*n[0]-t[0]*n[2],t[0]*n[1]-t[1]*n[0]]}function Af(t,n){t[0]+=n[0],t[1]+=n[1],t[2]+=n[2]}function Tf(t,n){return[t[0]*n,t[1]*n,t[2]*n]}function Sf(t){var n=Ic(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=n,t[1]/=n,t[2]/=n}var Ef,kf,Nf,Cf,Pf,zf,Df,qf,Rf,Ff,Of,If,Uf,Bf,Yf,Lf,jf={point:Hf,lineStart:Gf,lineEnd:Vf,polygonStart:function(){jf.point=$f,jf.lineStart=Wf,jf.lineEnd=Zf,sf=new g,gf.polygonStart()},polygonEnd:function(){gf.polygonEnd(),jf.point=Hf,jf.lineStart=Gf,jf.lineEnd=Vf,df<0?(nf=-(rf=180),ef=-(of=90)):sf>bc?of=90:sf<-1e-6&&(ef=-90),hf[0]=nf,hf[1]=rf},sphere:function(){nf=-(rf=180),ef=-(of=90)}};function Hf(t,n){lf.push(hf=[nf=t,rf=t]),n<ef&&(ef=n),n>of&&(of=n)}function Xf(t,n){var e=xf([t*Sc,n*Sc]);if(ff){var r=Mf(ff,e),i=Mf([r[1],-r[0],0],r);Sf(i),i=mf(i);var o,a=t-af,u=a>0?1:-1,c=i[0]*Tc*u,f=Ec(a)>180;f^(u*af<c&&c<u*t)?(o=i[1]*Tc)>of&&(of=o):f^(u*af<(c=(c+360)%360-180)&&c<u*t)?(o=-i[1]*Tc)<ef&&(ef=o):(n<ef&&(ef=n),n>of&&(of=n)),f?t<af?Kf(nf,t)>Kf(nf,rf)&&(rf=t):Kf(t,rf)>Kf(nf,rf)&&(nf=t):rf>=nf?(t<nf&&(nf=t),t>rf&&(rf=t)):t>af?Kf(nf,t)>Kf(nf,rf)&&(rf=t):Kf(t,rf)>Kf(nf,rf)&&(nf=t)}else lf.push(hf=[nf=t,rf=t]);n<ef&&(ef=n),n>of&&(of=n),ff=e,af=t}function Gf(){jf.point=Xf}function Vf(){hf[0]=nf,hf[1]=rf,jf.point=Hf,ff=null}function $f(t,n){if(ff){var e=t-af;sf.add(Ec(e)>180?e+(e>0?360:-360):e)}else uf=t,cf=n;gf.point(t,n),Xf(t,n)}function Wf(){gf.lineStart()}function Zf(){$f(uf,cf),gf.lineEnd(),Ec(sf)>bc&&(nf=-(rf=180)),hf[0]=nf,hf[1]=rf,ff=null}function Kf(t,n){return(n-=t)<0?n+360:n}function Qf(t,n){return t[0]-n[0]}function Jf(t,n){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:n<t[0]||t[1]<n}var ts={sphere:jc,point:ns,lineStart:rs,lineEnd:as,polygonStart:function(){ts.lineStart=us,ts.lineEnd=cs},polygonEnd:function(){ts.lineStart=rs,ts.lineEnd=as}};function ns(t,n){t*=Sc;var e=Cc(n*=Sc);es(e*Cc(t),e*Fc(t),Fc(n))}function es(t,n,e){++Ef,Nf+=(t-Nf)/Ef,Cf+=(n-Cf)/Ef,Pf+=(e-Pf)/Ef}function rs(){ts.point=is}function is(t,n){t*=Sc;var e=Cc(n*=Sc);Bf=e*Cc(t),Yf=e*Fc(t),Lf=Fc(n),ts.point=os,es(Bf,Yf,Lf)}function os(t,n){t*=Sc;var e=Cc(n*=Sc),r=e*Cc(t),i=e*Fc(t),o=Fc(n),a=Nc(Ic((a=Yf*o-Lf*i)*a+(a=Lf*r-Bf*o)*a+(a=Bf*i-Yf*r)*a),Bf*r+Yf*i+Lf*o);kf+=a,zf+=a*(Bf+(Bf=r)),Df+=a*(Yf+(Yf=i)),qf+=a*(Lf+(Lf=o)),es(Bf,Yf,Lf)}function as(){ts.point=ns}function us(){ts.point=fs}function cs(){ss(If,Uf),ts.point=ns}function fs(t,n){If=t,Uf=n,t*=Sc,n*=Sc,ts.point=ss;var e=Cc(n);Bf=e*Cc(t),Yf=e*Fc(t),Lf=Fc(n),es(Bf,Yf,Lf)}function ss(t,n){t*=Sc;var e=Cc(n*=Sc),r=e*Cc(t),i=e*Fc(t),o=Fc(n),a=Yf*o-Lf*i,u=Lf*r-Bf*o,c=Bf*i-Yf*r,f=Dc(a,u,c),s=Yc(f),l=f&&-s/f;Rf.add(l*a),Ff.add(l*u),Of.add(l*c),kf+=s,zf+=s*(Bf+(Bf=r)),Df+=s*(Yf+(Yf=i)),qf+=s*(Lf+(Lf=o)),es(Bf,Yf,Lf)}function ls(t){return function(){return t}}function hs(t,n){function e(e,r){return e=t(e,r),n(e[0],e[1])}return t.invert&&n.invert&&(e.invert=function(e,r){return(e=n.invert(e,r))&&t.invert(e[0],e[1])}),e}function ds(t,n){return[Ec(t)>xc?t+Math.round(-t/Ac)*Ac:t,n]}function ps(t,n,e){return(t%=Ac)?n||e?hs(ys(t),vs(n,e)):ys(t):n||e?vs(n,e):ds}function gs(t){return function(n,e){return[(n+=t)>xc?n-Ac:n<-xc?n+Ac:n,e]}}function ys(t){var n=gs(t);return n.invert=gs(-t),n}function vs(t,n){var e=Cc(t),r=Fc(t),i=Cc(n),o=Fc(n);function a(t,n){var a=Cc(n),u=Cc(t)*a,c=Fc(t)*a,f=Fc(n),s=f*e+u*r;return[Nc(c*i-s*o,u*e-f*r),Yc(s*i+c*o)]}return a.invert=function(t,n){var a=Cc(n),u=Cc(t)*a,c=Fc(t)*a,f=Fc(n),s=f*i-c*o;return[Nc(c*i+f*o,u*e+s*r),Yc(s*e-u*r)]},a}function _s(t){function n(n){return(n=t(n[0]*Sc,n[1]*Sc))[0]*=Tc,n[1]*=Tc,n}return t=ps(t[0]*Sc,t[1]*Sc,t.length>2?t[2]*Sc:0),n.invert=function(n){return(n=t.invert(n[0]*Sc,n[1]*Sc))[0]*=Tc,n[1]*=Tc,n},n}function bs(t,n,e,r,i,o){if(e){var a=Cc(n),u=Fc(n),c=r*e;null==i?(i=n+r*Ac,o=n-c/2):(i=ms(a,i),o=ms(a,o),(r>0?i<o:i>o)&&(i+=r*Ac));for(var f,s=i;r>0?s>o:s<o;s-=c)f=mf([a,-u*Cc(s),-u*Fc(s)]),t.point(f[0],f[1])}}function ms(t,n){(n=xf(n))[0]-=t,Sf(n);var e=Bc(-n[1]);return((-n[2]<0?-e:e)+Ac-bc)%Ac}function xs(){var t,n=[];return{point:function(n,e,r){t.push([n,e,r])},lineStart:function(){n.push(t=[])},lineEnd:jc,rejoin:function(){n.length>1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function ws(t,n){return Ec(t[0]-n[0])<bc&&Ec(t[1]-n[1])<bc}function Ms(t,n,e,r){this.x=t,this.z=n,this.o=e,this.e=r,this.v=!1,this.n=this.p=null}function As(t,n,e,r,i){var o,a,u=[],c=[];if(t.forEach((function(t){if(!((n=t.length-1)<=0)){var n,e,r=t[0],a=t[n];if(ws(r,a)){if(!r[2]&&!a[2]){for(i.lineStart(),o=0;o<n;++o)i.point((r=t[o])[0],r[1]);return void i.lineEnd()}a[0]+=2e-6}u.push(e=new Ms(r,t,null,!0)),c.push(e.o=new Ms(r,null,e,!1)),u.push(e=new Ms(a,t,null,!1)),c.push(e.o=new Ms(a,null,e,!0))}})),u.length){for(c.sort(n),Ts(u),Ts(c),o=0,a=c.length;o<a;++o)c[o].e=e=!e;for(var f,s,l=u[0];;){for(var h=l,d=!0;h.v;)if((h=h.n)===l)return;f=h.z,i.lineStart();do{if(h.v=h.o.v=!0,h.e){if(d)for(o=0,a=f.length;o<a;++o)i.point((s=f[o])[0],s[1]);else r(h.x,h.n.x,1,i);h=h.n}else{if(d)for(f=h.p.z,o=f.length-1;o>=0;--o)i.point((s=f[o])[0],s[1]);else r(h.x,h.p.x,-1,i);h=h.p}f=(h=h.o).z,d=!d}while(!h.v);i.lineEnd()}}}function Ts(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r<n;)i.n=e=t[r],e.p=i,i=e;i.n=e=t[0],e.p=i}}function Ss(t){return Ec(t[0])<=xc?t[0]:Oc(t[0])*((Ec(t[0])+xc)%Ac-xc)}function Es(t,n){var e=Ss(n),r=n[1],i=Fc(r),o=[Fc(e),-Cc(e),0],a=0,u=0,c=new g;1===i?r=wc+bc:-1===i&&(r=-wc-bc);for(var f=0,s=t.length;f<s;++f)if(h=(l=t[f]).length)for(var l,h,d=l[h-1],p=Ss(d),y=d[1]/2+Mc,v=Fc(y),_=Cc(y),b=0;b<h;++b,p=x,v=M,_=A,d=m){var m=l[b],x=Ss(m),w=m[1]/2+Mc,M=Fc(w),A=Cc(w),T=x-p,S=T>=0?1:-1,E=S*T,k=E>xc,N=v*M;if(c.add(Nc(N*S*Fc(E),_*A+N*Cc(E))),a+=k?T+S*Ac:T,k^p>=e^x>=e){var C=Mf(xf(d),xf(m));Sf(C);var P=Mf(o,C);Sf(P);var z=(k^T>=0?-1:1)*Yc(P[2]);(r>z||r===z&&(C[0]||C[1]))&&(u+=k^T>=0?1:-1)}}return(a<-1e-6||a<bc&&c<-1e-12)^1&u}function ks(t,n,e,r){return function(i){var o,a,u,c=n(i),f=xs(),s=n(f),l=!1,h={point:d,lineStart:g,lineEnd:y,polygonStart:function(){h.point=v,h.lineStart=_,h.lineEnd=b,a=[],o=[]},polygonEnd:function(){h.point=d,h.lineStart=g,h.lineEnd=y,a=V(a);var t=Es(o,r);a.length?(l||(i.polygonStart(),l=!0),As(a,Cs,t,e,i)):t&&(l||(i.polygonStart(),l=!0),i.lineStart(),e(null,null,1,i),i.lineEnd()),l&&(i.polygonEnd(),l=!1),a=o=null},sphere:function(){i.polygonStart(),i.lineStart(),e(null,null,1,i),i.lineEnd(),i.polygonEnd()}};function d(n,e){t(n,e)&&i.point(n,e)}function p(t,n){c.point(t,n)}function g(){h.point=p,c.lineStart()}function y(){h.point=d,c.lineEnd()}function v(t,n){u.push([t,n]),s.point(t,n)}function _(){s.lineStart(),u=[]}function b(){v(u[0][0],u[0][1]),s.lineEnd();var t,n,e,r,c=s.clean(),h=f.result(),d=h.length;if(u.pop(),o.push(u),u=null,d)if(1&c){if((n=(e=h[0]).length-1)>0){for(l||(i.polygonStart(),l=!0),i.lineStart(),t=0;t<n;++t)i.point((r=e[t])[0],r[1]);i.lineEnd()}}else d>1&&2&c&&h.push(h.pop().concat(h.shift())),a.push(h.filter(Ns))}return h}}function Ns(t){return t.length>1}function Cs(t,n){return((t=t.x)[0]<0?t[1]-wc-bc:wc-t[1])-((n=n.x)[0]<0?n[1]-wc-bc:wc-n[1])}ds.invert=ds;var Ps=ks((function(){return!0}),(function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,a){var u=o>0?xc:-xc,c=Ec(o-e);Ec(c-xc)<bc?(t.point(e,r=(r+a)/2>0?wc:-wc),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),t.point(o,r),n=0):i!==u&&c>=xc&&(Ec(e-i)<bc&&(e-=i*bc),Ec(o-u)<bc&&(o-=u*bc),r=function(t,n,e,r){var i,o,a=Fc(t-e);return Ec(a)>bc?kc((Fc(n)*(o=Cc(r))*Fc(e)-Fc(r)*(i=Cc(n))*Fc(t))/(i*o*a)):(n+r)/2}(e,r,o,a),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),n=0),t.point(e=o,r=a),i=u},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}}),(function(t,n,e,r){var i;if(null==t)i=e*wc,r.point(-xc,i),r.point(0,i),r.point(xc,i),r.point(xc,0),r.point(xc,-i),r.point(0,-i),r.point(-xc,-i),r.point(-xc,0),r.point(-xc,i);else if(Ec(t[0]-n[0])>bc){var o=t[0]<n[0]?xc:-xc;i=e*o/2,r.point(-o,i),r.point(0,i),r.point(o,i)}else r.point(n[0],n[1])}),[-xc,-wc]);function zs(t){var n=Cc(t),e=6*Sc,r=n>0,i=Ec(n)>bc;function o(t,e){return Cc(t)*Cc(e)>n}function a(t,e,r){var i=[1,0,0],o=Mf(xf(t),xf(e)),a=wf(o,o),u=o[0],c=a-u*u;if(!c)return!r&&t;var f=n*a/c,s=-n*u/c,l=Mf(i,o),h=Tf(i,f);Af(h,Tf(o,s));var d=l,p=wf(h,d),g=wf(d,d),y=p*p-g*(wf(h,h)-1);if(!(y<0)){var v=Ic(y),_=Tf(d,(-p-v)/g);if(Af(_,h),_=mf(_),!r)return _;var b,m=t[0],x=e[0],w=t[1],M=e[1];x<m&&(b=m,m=x,x=b);var A=x-m,T=Ec(A-xc)<bc;if(!T&&M<w&&(b=w,w=M,M=b),T||A<bc?T?w+M>0^_[1]<(Ec(_[0]-m)<bc?w:M):w<=_[1]&&_[1]<=M:A>xc^(m<=_[0]&&_[0]<=x)){var S=Tf(d,(-p+v)/g);return Af(S,h),[_,mf(S)]}}}function u(n,e){var i=r?t:xc-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return ks(o,(function(t){var n,e,c,f,s;return{lineStart:function(){f=c=!1,s=1},point:function(l,h){var d,p=[l,h],g=o(l,h),y=r?g?0:u(l,h):g?u(l+(l<0?xc:-xc),h):0;if(!n&&(f=c=g)&&t.lineStart(),g!==c&&(!(d=a(n,p))||ws(n,d)||ws(p,d))&&(p[2]=1),g!==c)s=0,g?(t.lineStart(),d=a(p,n),t.point(d[0],d[1])):(d=a(n,p),t.point(d[0],d[1],2),t.lineEnd()),n=d;else if(i&&n&&r^g){var v;y&e||!(v=a(p,n,!0))||(s=0,r?(t.lineStart(),t.point(v[0][0],v[0][1]),t.point(v[1][0],v[1][1]),t.lineEnd()):(t.point(v[1][0],v[1][1]),t.lineEnd(),t.lineStart(),t.point(v[0][0],v[0][1],3)))}!g||n&&ws(n,p)||t.point(p[0],p[1]),n=p,c=g,e=y},lineEnd:function(){c&&t.lineEnd(),n=null},clean:function(){return s|(f&&c)<<1}}}),(function(n,r,i,o){bs(o,t,e,i,n,r)}),r?[0,-t]:[-xc,t-xc])}var Ds,qs,Rs,Fs,Os=1e9,Is=-Os;function Us(t,n,e,r){function i(i,o){return t<=i&&i<=e&&n<=o&&o<=r}function o(i,o,u,f){var s=0,l=0;if(null==i||(s=a(i,u))!==(l=a(o,u))||c(i,o)<0^u>0)do{f.point(0===s||3===s?t:e,s>1?r:n)}while((s=(s+u+4)%4)!==l);else f.point(o[0],o[1])}function a(r,i){return Ec(r[0]-t)<bc?i>0?0:3:Ec(r[0]-e)<bc?i>0?2:1:Ec(r[1]-n)<bc?i>0?1:0:i>0?3:2}function u(t,n){return c(t.x,n.x)}function c(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var c,f,s,l,h,d,p,g,y,v,_,b=a,m=xs(),x={point:w,lineStart:function(){x.point=M,f&&f.push(s=[]);v=!0,y=!1,p=g=NaN},lineEnd:function(){c&&(M(l,h),d&&y&&m.rejoin(),c.push(m.result()));x.point=w,y&&b.lineEnd()},polygonStart:function(){b=m,c=[],f=[],_=!0},polygonEnd:function(){var n=function(){for(var n=0,e=0,i=f.length;e<i;++e)for(var o,a,u=f[e],c=1,s=u.length,l=u[0],h=l[0],d=l[1];c<s;++c)o=h,a=d,h=(l=u[c])[0],d=l[1],a<=r?d>r&&(h-o)*(r-a)>(d-a)*(t-o)&&++n:d<=r&&(h-o)*(r-a)<(d-a)*(t-o)&&--n;return n}(),e=_&&n,i=(c=V(c)).length;(e||i)&&(a.polygonStart(),e&&(a.lineStart(),o(null,null,1,a),a.lineEnd()),i&&As(c,u,n,o,a),a.polygonEnd());b=a,c=f=s=null}};function w(t,n){i(t,n)&&b.point(t,n)}function M(o,a){var u=i(o,a);if(f&&s.push([o,a]),v)l=o,h=a,d=u,v=!1,u&&(b.lineStart(),b.point(o,a));else if(u&&y)b.point(o,a);else{var c=[p=Math.max(Is,Math.min(Os,p)),g=Math.max(Is,Math.min(Os,g))],m=[o=Math.max(Is,Math.min(Os,o)),a=Math.max(Is,Math.min(Os,a))];!function(t,n,e,r,i,o){var a,u=t[0],c=t[1],f=0,s=1,l=n[0]-u,h=n[1]-c;if(a=e-u,l||!(a>0)){if(a/=l,l<0){if(a<f)return;a<s&&(s=a)}else if(l>0){if(a>s)return;a>f&&(f=a)}if(a=i-u,l||!(a<0)){if(a/=l,l<0){if(a>s)return;a>f&&(f=a)}else if(l>0){if(a<f)return;a<s&&(s=a)}if(a=r-c,h||!(a>0)){if(a/=h,h<0){if(a<f)return;a<s&&(s=a)}else if(h>0){if(a>s)return;a>f&&(f=a)}if(a=o-c,h||!(a<0)){if(a/=h,h<0){if(a>s)return;a>f&&(f=a)}else if(h>0){if(a<f)return;a<s&&(s=a)}return f>0&&(t[0]=u+f*l,t[1]=c+f*h),s<1&&(n[0]=u+s*l,n[1]=c+s*h),!0}}}}}(c,m,t,n,e,r)?u&&(b.lineStart(),b.point(o,a),_=!1):(y||(b.lineStart(),b.point(c[0],c[1])),b.point(m[0],m[1]),u||b.lineEnd(),_=!1)}p=o,g=a,y=u}return x}}var Bs={sphere:jc,point:jc,lineStart:function(){Bs.point=Ls,Bs.lineEnd=Ys},lineEnd:jc,polygonStart:jc,polygonEnd:jc};function Ys(){Bs.point=Bs.lineEnd=jc}function Ls(t,n){qs=t*=Sc,Rs=Fc(n*=Sc),Fs=Cc(n),Bs.point=js}function js(t,n){t*=Sc;var e=Fc(n*=Sc),r=Cc(n),i=Ec(t-qs),o=Cc(i),a=r*Fc(i),u=Fs*e-Rs*r*o,c=Rs*e+Fs*r*o;Ds.add(Nc(Ic(a*a+u*u),c)),qs=t,Rs=e,Fs=r}function Hs(t){return Ds=new g,Wc(t,Bs),+Ds}var Xs=[null,null],Gs={type:"LineString",coordinates:Xs};function Vs(t,n){return Xs[0]=t,Xs[1]=n,Hs(Gs)}var $s={Feature:function(t,n){return Zs(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r<i;)if(Zs(e[r].geometry,n))return!0;return!1}},Ws={Sphere:function(){return!0},Point:function(t,n){return Ks(t.coordinates,n)},MultiPoint:function(t,n){for(var e=t.coordinates,r=-1,i=e.length;++r<i;)if(Ks(e[r],n))return!0;return!1},LineString:function(t,n){return Qs(t.coordinates,n)},MultiLineString:function(t,n){for(var e=t.coordinates,r=-1,i=e.length;++r<i;)if(Qs(e[r],n))return!0;return!1},Polygon:function(t,n){return Js(t.coordinates,n)},MultiPolygon:function(t,n){for(var e=t.coordinates,r=-1,i=e.length;++r<i;)if(Js(e[r],n))return!0;return!1},GeometryCollection:function(t,n){for(var e=t.geometries,r=-1,i=e.length;++r<i;)if(Zs(e[r],n))return!0;return!1}};function Zs(t,n){return!(!t||!Ws.hasOwnProperty(t.type))&&Ws[t.type](t,n)}function Ks(t,n){return 0===Vs(t,n)}function Qs(t,n){for(var e,r,i,o=0,a=t.length;o<a;o++){if(0===(r=Vs(t[o],n)))return!0;if(o>0&&(i=Vs(t[o],t[o-1]))>0&&e<=i&&r<=i&&(e+r-i)*(1-Math.pow((e-r)/i,2))<mc*i)return!0;e=r}return!1}function Js(t,n){return!!Es(t.map(tl),nl(n))}function tl(t){return(t=t.map(nl)).pop(),t}function nl(t){return[t[0]*Sc,t[1]*Sc]}function el(t,n,e){var r=Z(t,n-bc,e).concat(n);return function(t){return r.map((function(n){return[t,n]}))}}function rl(t,n,e){var r=Z(t,n-bc,e).concat(n);return function(t){return r.map((function(n){return[n,t]}))}}function il(){var t,n,e,r,i,o,a,u,c,f,s,l,h=10,d=h,p=90,g=360,y=2.5;function v(){return{type:"MultiLineString",coordinates:_()}}function _(){return Z(Pc(r/p)*p,e,p).map(s).concat(Z(Pc(u/g)*g,a,g).map(l)).concat(Z(Pc(n/h)*h,t,h).filter((function(t){return Ec(t%p)>bc})).map(c)).concat(Z(Pc(o/d)*d,i,d).filter((function(t){return Ec(t%g)>bc})).map(f))}return v.lines=function(){return _().map((function(t){return{type:"LineString",coordinates:t}}))},v.outline=function(){return{type:"Polygon",coordinates:[s(r).concat(l(a).slice(1),s(e).reverse().slice(1),l(u).reverse().slice(1))]}},v.extent=function(t){return arguments.length?v.extentMajor(t).extentMinor(t):v.extentMinor()},v.extentMajor=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],u=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),u>a&&(t=u,u=a,a=t),v.precision(y)):[[r,u],[e,a]]},v.extentMinor=function(e){return arguments.length?(n=+e[0][0],t=+e[1][0],o=+e[0][1],i=+e[1][1],n>t&&(e=n,n=t,t=e),o>i&&(e=o,o=i,i=e),v.precision(y)):[[n,o],[t,i]]},v.step=function(t){return arguments.length?v.stepMajor(t).stepMinor(t):v.stepMinor()},v.stepMajor=function(t){return arguments.length?(p=+t[0],g=+t[1],v):[p,g]},v.stepMinor=function(t){return arguments.length?(h=+t[0],d=+t[1],v):[h,d]},v.precision=function(h){return arguments.length?(y=+h,c=el(o,i,90),f=rl(n,t,y),s=el(u,a,90),l=rl(r,e,y),v):y},v.extentMajor([[-180,-89.999999],[180,89.999999]]).extentMinor([[-180,-80.000001],[180,80.000001]])}var ol,al,ul,cl,fl=t=>t,sl=new g,ll=new g,hl={point:jc,lineStart:jc,lineEnd:jc,polygonStart:function(){hl.lineStart=dl,hl.lineEnd=yl},polygonEnd:function(){hl.lineStart=hl.lineEnd=hl.point=jc,sl.add(Ec(ll)),ll=new g},result:function(){var t=sl/2;return sl=new g,t}};function dl(){hl.point=pl}function pl(t,n){hl.point=gl,ol=ul=t,al=cl=n}function gl(t,n){ll.add(cl*t-ul*n),ul=t,cl=n}function yl(){gl(ol,al)}var vl=1/0,_l=vl,bl=-vl,ml=bl,xl={point:function(t,n){t<vl&&(vl=t);t>bl&&(bl=t);n<_l&&(_l=n);n>ml&&(ml=n)},lineStart:jc,lineEnd:jc,polygonStart:jc,polygonEnd:jc,result:function(){var t=[[vl,_l],[bl,ml]];return bl=ml=-(_l=vl=1/0),t}};var wl,Ml,Al,Tl,Sl=0,El=0,kl=0,Nl=0,Cl=0,Pl=0,zl=0,Dl=0,ql=0,Rl={point:Fl,lineStart:Ol,lineEnd:Bl,polygonStart:function(){Rl.lineStart=Yl,Rl.lineEnd=Ll},polygonEnd:function(){Rl.point=Fl,Rl.lineStart=Ol,Rl.lineEnd=Bl},result:function(){var t=ql?[zl/ql,Dl/ql]:Pl?[Nl/Pl,Cl/Pl]:kl?[Sl/kl,El/kl]:[NaN,NaN];return Sl=El=kl=Nl=Cl=Pl=zl=Dl=ql=0,t}};function Fl(t,n){Sl+=t,El+=n,++kl}function Ol(){Rl.point=Il}function Il(t,n){Rl.point=Ul,Fl(Al=t,Tl=n)}function Ul(t,n){var e=t-Al,r=n-Tl,i=Ic(e*e+r*r);Nl+=i*(Al+t)/2,Cl+=i*(Tl+n)/2,Pl+=i,Fl(Al=t,Tl=n)}function Bl(){Rl.point=Fl}function Yl(){Rl.point=jl}function Ll(){Hl(wl,Ml)}function jl(t,n){Rl.point=Hl,Fl(wl=Al=t,Ml=Tl=n)}function Hl(t,n){var e=t-Al,r=n-Tl,i=Ic(e*e+r*r);Nl+=i*(Al+t)/2,Cl+=i*(Tl+n)/2,Pl+=i,zl+=(i=Tl*t-Al*n)*(Al+t),Dl+=i*(Tl+n),ql+=3*i,Fl(Al=t,Tl=n)}function Xl(t){this._context=t}Xl.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,Ac)}},result:jc};var Gl,Vl,$l,Wl,Zl,Kl=new g,Ql={point:jc,lineStart:function(){Ql.point=Jl},lineEnd:function(){Gl&&th(Vl,$l),Ql.point=jc},polygonStart:function(){Gl=!0},polygonEnd:function(){Gl=null},result:function(){var t=+Kl;return Kl=new g,t}};function Jl(t,n){Ql.point=th,Vl=Wl=t,$l=Zl=n}function th(t,n){Wl-=t,Zl-=n,Kl.add(Ic(Wl*Wl+Zl*Zl)),Wl=t,Zl=n}function nh(){this._string=[]}function eh(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function rh(t){return function(n){var e=new ih;for(var r in t)e[r]=t[r];return e.stream=n,e}}function ih(){}function oh(t,n,e){var r=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=r&&t.clipExtent(null),Wc(e,t.stream(xl)),n(xl.result()),null!=r&&t.clipExtent(r),t}function ah(t,n,e){return oh(t,(function(e){var r=n[1][0]-n[0][0],i=n[1][1]-n[0][1],o=Math.min(r/(e[1][0]-e[0][0]),i/(e[1][1]-e[0][1])),a=+n[0][0]+(r-o*(e[1][0]+e[0][0]))/2,u=+n[0][1]+(i-o*(e[1][1]+e[0][1]))/2;t.scale(150*o).translate([a,u])}),e)}function uh(t,n,e){return ah(t,[[0,0],n],e)}function ch(t,n,e){return oh(t,(function(e){var r=+n,i=r/(e[1][0]-e[0][0]),o=(r-i*(e[1][0]+e[0][0]))/2,a=-i*e[0][1];t.scale(150*i).translate([o,a])}),e)}function fh(t,n,e){return oh(t,(function(e){var r=+n,i=r/(e[1][1]-e[0][1]),o=-i*e[0][0],a=(r-i*(e[1][1]+e[0][1]))/2;t.scale(150*i).translate([o,a])}),e)}nh.prototype={_radius:4.5,_circle:eh(4.5),pointRadius:function(t){return(t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._string.push("M",t,",",n),this._point=1;break;case 1:this._string.push("L",t,",",n);break;default:null==this._circle&&(this._circle=eh(this._radius)),this._string.push("M",t,",",n,this._circle)}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}},ih.prototype={constructor:ih,point:function(t,n){this.stream.point(t,n)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};var sh=Cc(30*Sc);function lh(t,n){return+n?function(t,n){function e(r,i,o,a,u,c,f,s,l,h,d,p,g,y){var v=f-r,_=s-i,b=v*v+_*_;if(b>4*n&&g--){var m=a+h,x=u+d,w=c+p,M=Ic(m*m+x*x+w*w),A=Yc(w/=M),T=Ec(Ec(w)-1)<bc||Ec(o-l)<bc?(o+l)/2:Nc(x,m),S=t(T,A),E=S[0],k=S[1],N=E-r,C=k-i,P=_*N-v*C;(P*P/b>n||Ec((v*N+_*C)/b-.5)>.3||a*h+u*d+c*p<sh)&&(e(r,i,o,a,u,c,E,k,T,m/=M,x/=M,w,g,y),y.point(E,k),e(E,k,T,m,x,w,f,s,l,h,d,p,g,y))}}return function(n){var r,i,o,a,u,c,f,s,l,h,d,p,g={point:y,lineStart:v,lineEnd:b,polygonStart:function(){n.polygonStart(),g.lineStart=m},polygonEnd:function(){n.polygonEnd(),g.lineStart=v}};function y(e,r){e=t(e,r),n.point(e[0],e[1])}function v(){s=NaN,g.point=_,n.lineStart()}function _(r,i){var o=xf([r,i]),a=t(r,i);e(s,l,f,h,d,p,s=a[0],l=a[1],f=r,h=o[0],d=o[1],p=o[2],16,n),n.point(s,l)}function b(){g.point=y,n.lineEnd()}function m(){v(),g.point=x,g.lineEnd=w}function x(t,n){_(r=t,n),i=s,o=l,a=h,u=d,c=p,g.point=_}function w(){e(s,l,f,h,d,p,i,o,r,a,u,c,16,n),g.lineEnd=b,b()}return g}}(t,n):function(t){return rh({point:function(n,e){n=t(n,e),this.stream.point(n[0],n[1])}})}(t)}var hh=rh({point:function(t,n){this.stream.point(t*Sc,n*Sc)}});function dh(t,n,e,r,i,o){if(!o)return function(t,n,e,r,i){function o(o,a){return[n+t*(o*=r),e-t*(a*=i)]}return o.invert=function(o,a){return[(o-n)/t*r,(e-a)/t*i]},o}(t,n,e,r,i);var a=Cc(o),u=Fc(o),c=a*t,f=u*t,s=a/t,l=u/t,h=(u*e-a*n)/t,d=(u*n+a*e)/t;function p(t,o){return[c*(t*=r)-f*(o*=i)+n,e-f*t-c*o]}return p.invert=function(t,n){return[r*(s*t-l*n+h),i*(d-l*t-s*n)]},p}function ph(t){return gh((function(){return t}))()}function gh(t){var n,e,r,i,o,a,u,c,f,s,l=150,h=480,d=250,p=0,g=0,y=0,v=0,_=0,b=0,m=1,x=1,w=null,M=Ps,A=null,T=fl,S=.5;function E(t){return c(t[0]*Sc,t[1]*Sc)}function k(t){return(t=c.invert(t[0],t[1]))&&[t[0]*Tc,t[1]*Tc]}function N(){var t=dh(l,0,0,m,x,b).apply(null,n(p,g)),r=dh(l,h-t[0],d-t[1],m,x,b);return e=ps(y,v,_),u=hs(n,r),c=hs(e,u),a=lh(u,S),C()}function C(){return f=s=null,E}return E.stream=function(t){return f&&s===t?f:f=hh(function(t){return rh({point:function(n,e){var r=t(n,e);return this.stream.point(r[0],r[1])}})}(e)(M(a(T(s=t)))))},E.preclip=function(t){return arguments.length?(M=t,w=void 0,C()):M},E.postclip=function(t){return arguments.length?(T=t,A=r=i=o=null,C()):T},E.clipAngle=function(t){return arguments.length?(M=+t?zs(w=t*Sc):(w=null,Ps),C()):w*Tc},E.clipExtent=function(t){return arguments.length?(T=null==t?(A=r=i=o=null,fl):Us(A=+t[0][0],r=+t[0][1],i=+t[1][0],o=+t[1][1]),C()):null==A?null:[[A,r],[i,o]]},E.scale=function(t){return arguments.length?(l=+t,N()):l},E.translate=function(t){return arguments.length?(h=+t[0],d=+t[1],N()):[h,d]},E.center=function(t){return arguments.length?(p=t[0]%360*Sc,g=t[1]%360*Sc,N()):[p*Tc,g*Tc]},E.rotate=function(t){return arguments.length?(y=t[0]%360*Sc,v=t[1]%360*Sc,_=t.length>2?t[2]%360*Sc:0,N()):[y*Tc,v*Tc,_*Tc]},E.angle=function(t){return arguments.length?(b=t%360*Sc,N()):b*Tc},E.reflectX=function(t){return arguments.length?(m=t?-1:1,N()):m<0},E.reflectY=function(t){return arguments.length?(x=t?-1:1,N()):x<0},E.precision=function(t){return arguments.length?(a=lh(u,S=t*t),C()):Ic(S)},E.fitExtent=function(t,n){return ah(E,t,n)},E.fitSize=function(t,n){return uh(E,t,n)},E.fitWidth=function(t,n){return ch(E,t,n)},E.fitHeight=function(t,n){return fh(E,t,n)},function(){return n=t.apply(this,arguments),E.invert=n.invert&&k,N()}}function yh(t){var n=0,e=xc/3,r=gh(t),i=r(n,e);return i.parallels=function(t){return arguments.length?r(n=t[0]*Sc,e=t[1]*Sc):[n*Tc,e*Tc]},i}function vh(t,n){var e=Fc(t),r=(e+Fc(n))/2;if(Ec(r)<bc)return function(t){var n=Cc(t);function e(t,e){return[t*n,Fc(e)/n]}return e.invert=function(t,e){return[t/n,Yc(e*n)]},e}(t);var i=1+e*(2*r-e),o=Ic(i)/r;function a(t,n){var e=Ic(i-2*r*Fc(n))/r;return[e*Fc(t*=r),o-e*Cc(t)]}return a.invert=function(t,n){var e=o-n,a=Nc(t,Ec(e))*Oc(e);return e*r<0&&(a-=xc*Oc(t)*Oc(e)),[a/r,Yc((i-(t*t+e*e)*r*r)/(2*r))]},a}function _h(){return yh(vh).scale(155.424).center([0,33.6442])}function bh(){return _h().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function mh(t){return function(n,e){var r=Cc(n),i=Cc(e),o=t(r*i);return o===1/0?[2,0]:[o*i*Fc(n),o*Fc(e)]}}function xh(t){return function(n,e){var r=Ic(n*n+e*e),i=t(r),o=Fc(i),a=Cc(i);return[Nc(n*o,r*a),Yc(r&&e*o/r)]}}var wh=mh((function(t){return Ic(2/(1+t))}));wh.invert=xh((function(t){return 2*Yc(t/2)}));var Mh=mh((function(t){return(t=Bc(t))&&t/Fc(t)}));function Ah(t,n){return[t,qc(Uc((wc+n)/2))]}function Th(t){var n,e,r,i=ph(t),o=i.center,a=i.scale,u=i.translate,c=i.clipExtent,f=null;function s(){var o=xc*a(),u=i(_s(i.rotate()).invert([0,0]));return c(null==f?[[u[0]-o,u[1]-o],[u[0]+o,u[1]+o]]:t===Ah?[[Math.max(u[0]-o,f),n],[Math.min(u[0]+o,e),r]]:[[f,Math.max(u[1]-o,n)],[e,Math.min(u[1]+o,r)]])}return i.scale=function(t){return arguments.length?(a(t),s()):a()},i.translate=function(t){return arguments.length?(u(t),s()):u()},i.center=function(t){return arguments.length?(o(t),s()):o()},i.clipExtent=function(t){return arguments.length?(null==t?f=n=e=r=null:(f=+t[0][0],n=+t[0][1],e=+t[1][0],r=+t[1][1]),s()):null==f?null:[[f,n],[e,r]]},s()}function Sh(t){return Uc((wc+t)/2)}function Eh(t,n){var e=Cc(t),r=t===n?Fc(t):qc(e/Cc(n))/qc(Sh(n)/Sh(t)),i=e*Rc(Sh(t),r)/r;if(!r)return Ah;function o(t,n){i>0?n<-wc+bc&&(n=-wc+bc):n>wc-bc&&(n=wc-bc);var e=i/Rc(Sh(n),r);return[e*Fc(r*t),i-e*Cc(r*t)]}return o.invert=function(t,n){var e=i-n,o=Oc(r)*Ic(t*t+e*e),a=Nc(t,Ec(e))*Oc(e);return e*r<0&&(a-=xc*Oc(t)*Oc(e)),[a/r,2*kc(Rc(i/o,1/r))-wc]},o}function kh(t,n){return[t,n]}function Nh(t,n){var e=Cc(t),r=t===n?Fc(t):(e-Cc(n))/(n-t),i=e/r+t;if(Ec(r)<bc)return kh;function o(t,n){var e=i-n,o=r*t;return[e*Fc(o),i-e*Cc(o)]}return o.invert=function(t,n){var e=i-n,o=Nc(t,Ec(e))*Oc(e);return e*r<0&&(o-=xc*Oc(t)*Oc(e)),[o/r,i-Oc(r)*Ic(t*t+e*e)]},o}Mh.invert=xh((function(t){return t})),Ah.invert=function(t,n){return[t,2*kc(zc(n))-wc]},kh.invert=kh;var Ch=1.340264,Ph=-.081106,zh=893e-6,Dh=.003796,qh=Ic(3)/2;function Rh(t,n){var e=Yc(qh*Fc(n)),r=e*e,i=r*r*r;return[t*Cc(e)/(qh*(Ch+3*Ph*r+i*(7*zh+9*Dh*r))),e*(Ch+Ph*r+i*(zh+Dh*r))]}function Fh(t,n){var e=Cc(n),r=Cc(t)*e;return[e*Fc(t)/r,Fc(n)/r]}function Oh(t,n){var e=n*n,r=e*e;return[t*(.8707-.131979*e+r*(r*(.003971*e-.001529*r)-.013791)),n*(1.007226+e*(.015085+r*(.028874*e-.044475-.005916*r)))]}function Ih(t,n){return[Cc(n)*Fc(t),Fc(n)]}function Uh(t,n){var e=Cc(n),r=1+Cc(t)*e;return[e*Fc(t)/r,Fc(n)/r]}function Bh(t,n){return[qc(Uc((wc+n)/2)),-t]}function Yh(t,n){return t.parent===n.parent?1:2}function Lh(t,n){return t+n.x}function jh(t,n){return Math.max(t,n.y)}function Hh(t){var n=0,e=t.children,r=e&&e.length;if(r)for(;--r>=0;)n+=e[r].value;else n=1;t.value=n}function Xh(t,n){t instanceof Map?(t=[void 0,t],void 0===n&&(n=Vh)):void 0===n&&(n=Gh);for(var e,r,i,o,a,u=new Zh(t),c=[u];e=c.pop();)if((i=n(e.data))&&(a=(i=Array.from(i)).length))for(e.children=i,o=a-1;o>=0;--o)c.push(r=i[o]=new Zh(i[o])),r.parent=e,r.depth=e.depth+1;return u.eachBefore(Wh)}function Gh(t){return t.children}function Vh(t){return Array.isArray(t)?t[1]:null}function $h(t){void 0!==t.data.value&&(t.value=t.data.value),t.data=t.data.data}function Wh(t){var n=0;do{t.height=n}while((t=t.parent)&&t.height<++n)}function Zh(t){this.data=t,this.depth=this.height=0,this.parent=null}function Kh(t){for(var n,e,r=0,i=(t=function(t){for(var n,e,r=t.length;r;)e=Math.random()*r--|0,n=t[r],t[r]=t[e],t[e]=n;return t}(Array.from(t))).length,o=[];r<i;)n=t[r],e&&td(e,n)?++r:(e=ed(o=Qh(o,n)),r=0);return e}function Qh(t,n){var e,r;if(nd(n,t))return[n];for(e=0;e<t.length;++e)if(Jh(n,t[e])&&nd(rd(t[e],n),t))return[t[e],n];for(e=0;e<t.length-1;++e)for(r=e+1;r<t.length;++r)if(Jh(rd(t[e],t[r]),n)&&Jh(rd(t[e],n),t[r])&&Jh(rd(t[r],n),t[e])&&nd(id(t[e],t[r],n),t))return[t[e],t[r],n];throw new Error}function Jh(t,n){var e=t.r-n.r,r=n.x-t.x,i=n.y-t.y;return e<0||e*e<r*r+i*i}function td(t,n){var e=t.r-n.r+1e-9*Math.max(t.r,n.r,1),r=n.x-t.x,i=n.y-t.y;return e>0&&e*e>r*r+i*i}function nd(t,n){for(var e=0;e<n.length;++e)if(!td(t,n[e]))return!1;return!0}function ed(t){switch(t.length){case 1:return function(t){return{x:t.x,y:t.y,r:t.r}}(t[0]);case 2:return rd(t[0],t[1]);case 3:return id(t[0],t[1],t[2])}}function rd(t,n){var e=t.x,r=t.y,i=t.r,o=n.x,a=n.y,u=n.r,c=o-e,f=a-r,s=u-i,l=Math.sqrt(c*c+f*f);return{x:(e+o+c/l*s)/2,y:(r+a+f/l*s)/2,r:(l+i+u)/2}}function id(t,n,e){var r=t.x,i=t.y,o=t.r,a=n.x,u=n.y,c=n.r,f=e.x,s=e.y,l=e.r,h=r-a,d=r-f,p=i-u,g=i-s,y=c-o,v=l-o,_=r*r+i*i-o*o,b=_-a*a-u*u+c*c,m=_-f*f-s*s+l*l,x=d*p-h*g,w=(p*m-g*b)/(2*x)-r,M=(g*y-p*v)/x,A=(d*b-h*m)/(2*x)-i,T=(h*v-d*y)/x,S=M*M+T*T-1,E=2*(o+w*M+A*T),k=w*w+A*A-o*o,N=-(S?(E+Math.sqrt(E*E-4*S*k))/(2*S):k/E);return{x:r+w+M*N,y:i+A+T*N,r:N}}function od(t,n,e){var r,i,o,a,u=t.x-n.x,c=t.y-n.y,f=u*u+c*c;f?(i=n.r+e.r,i*=i,a=t.r+e.r,i>(a*=a)?(r=(f+a-i)/(2*f),o=Math.sqrt(Math.max(0,a/f-r*r)),e.x=t.x-r*u-o*c,e.y=t.y-r*c+o*u):(r=(f+i-a)/(2*f),o=Math.sqrt(Math.max(0,i/f-r*r)),e.x=n.x+r*u-o*c,e.y=n.y+r*c+o*u)):(e.x=n.x+e.r,e.y=n.y)}function ad(t,n){var e=t.r+n.r-1e-6,r=n.x-t.x,i=n.y-t.y;return e>0&&e*e>r*r+i*i}function ud(t){var n=t._,e=t.next._,r=n.r+e.r,i=(n.x*e.r+e.x*n.r)/r,o=(n.y*e.r+e.y*n.r)/r;return i*i+o*o}function cd(t){this._=t,this.next=null,this.previous=null}function fd(t){if(!(i=(t=function(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}(t)).length))return 0;var n,e,r,i,o,a,u,c,f,s,l;if((n=t[0]).x=0,n.y=0,!(i>1))return n.r;if(e=t[1],n.x=-e.r,e.x=n.r,e.y=0,!(i>2))return n.r+e.r;od(e,n,r=t[2]),n=new cd(n),e=new cd(e),r=new cd(r),n.next=r.previous=e,e.next=n.previous=r,r.next=e.previous=n;t:for(u=3;u<i;++u){od(n._,e._,r=t[u]),r=new cd(r),c=e.next,f=n.previous,s=e._.r,l=n._.r;do{if(s<=l){if(ad(c._,r._)){e=c,n.next=e,e.previous=n,--u;continue t}s+=c._.r,c=c.next}else{if(ad(f._,r._)){(n=f).next=e,e.previous=n,--u;continue t}l+=f._.r,f=f.previous}}while(c!==f.next);for(r.previous=n,r.next=e,n.next=e.previous=e=r,o=ud(n);(r=r.next)!==e;)(a=ud(r))<o&&(n=r,o=a);e=n.next}for(n=[e._],r=e;(r=r.next)!==e;)n.push(r._);for(r=Kh(n),u=0;u<i;++u)(n=t[u]).x-=r.x,n.y-=r.y;return r.r}function sd(t){return null==t?null:ld(t)}function ld(t){if("function"!=typeof t)throw new Error;return t}function hd(){return 0}function dd(t){return function(){return t}}function pd(t){return Math.sqrt(t.value)}function gd(t){return function(n){n.children||(n.r=Math.max(0,+t(n)||0))}}function yd(t,n){return function(e){if(r=e.children){var r,i,o,a=r.length,u=t(e)*n||0;if(u)for(i=0;i<a;++i)r[i].r+=u;if(o=fd(r),u)for(i=0;i<a;++i)r[i].r-=u;e.r=o+u}}}function vd(t){return function(n){var e=n.parent;n.r*=t,e&&(n.x=e.x+t*n.x,n.y=e.y+t*n.y)}}function _d(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}function bd(t,n,e,r,i){for(var o,a=t.children,u=-1,c=a.length,f=t.value&&(r-n)/t.value;++u<c;)(o=a[u]).y0=e,o.y1=i,o.x0=n,o.x1=n+=o.value*f}Rh.invert=function(t,n){for(var e,r=n,i=r*r,o=i*i*i,a=0;a<12&&(o=(i=(r-=e=(r*(Ch+Ph*i+o*(zh+Dh*i))-n)/(Ch+3*Ph*i+o*(7*zh+9*Dh*i)))*r)*i*i,!(Ec(e)<mc));++a);return[qh*t*(Ch+3*Ph*i+o*(7*zh+9*Dh*i))/Cc(r),Yc(Fc(r)/qh)]},Fh.invert=xh(kc),Oh.invert=function(t,n){var e,r=n,i=25;do{var o=r*r,a=o*o;r-=e=(r*(1.007226+o*(.015085+a*(.028874*o-.044475-.005916*a)))-n)/(1.007226+o*(.045255+a*(.259866*o-.311325-.005916*11*a)))}while(Ec(e)>bc&&--i>0);return[t/(.8707+(o=r*r)*(o*(o*o*o*(.003971-.001529*o)-.013791)-.131979)),r]},Ih.invert=xh(Yc),Uh.invert=xh((function(t){return 2*kc(t)})),Bh.invert=function(t,n){return[-n,2*kc(zc(t))-wc]},Zh.prototype=Xh.prototype={constructor:Zh,count:function(){return this.eachAfter(Hh)},each:function(t,n){let e=-1;for(const r of this)t.call(n,r,++e,this);return this},eachAfter:function(t,n){for(var e,r,i,o=this,a=[o],u=[],c=-1;o=a.pop();)if(u.push(o),e=o.children)for(r=0,i=e.length;r<i;++r)a.push(e[r]);for(;o=u.pop();)t.call(n,o,++c,this);return this},eachBefore:function(t,n){for(var e,r,i=this,o=[i],a=-1;i=o.pop();)if(t.call(n,i,++a,this),e=i.children)for(r=e.length-1;r>=0;--r)o.push(e[r]);return this},find:function(t,n){let e=-1;for(const r of this)if(t.call(n,r,++e,this))return r},sum:function(t){return this.eachAfter((function(n){for(var e=+t(n.data)||0,r=n.children,i=r&&r.length;--i>=0;)e+=r[i].value;n.value=e}))},sort:function(t){return this.eachBefore((function(n){n.children&&n.children.sort(t)}))},path:function(t){for(var n=this,e=function(t,n){if(t===n)return t;var e=t.ancestors(),r=n.ancestors(),i=null;t=e.pop(),n=r.pop();for(;t===n;)i=t,t=e.pop(),n=r.pop();return i}(n,t),r=[n];n!==e;)n=n.parent,r.push(n);for(var i=r.length;t!==e;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,n=[t];t=t.parent;)n.push(t);return n},descendants:function(){return Array.from(this)},leaves:function(){var t=[];return this.eachBefore((function(n){n.children||t.push(n)})),t},links:function(){var t=this,n=[];return t.each((function(e){e!==t&&n.push({source:e.parent,target:e})})),n},copy:function(){return Xh(this).eachBefore($h)},[Symbol.iterator]:function*(){var t,n,e,r,i=this,o=[i];do{for(t=o.reverse(),o=[];i=t.pop();)if(yield i,n=i.children)for(e=0,r=n.length;e<r;++e)o.push(n[e])}while(o.length)}};var md={depth:-1},xd={};function wd(t){return t.id}function Md(t){return t.parentId}function Ad(t,n){return t.parent===n.parent?1:2}function Td(t){var n=t.children;return n?n[0]:t.t}function Sd(t){var n=t.children;return n?n[n.length-1]:t.t}function Ed(t,n,e){var r=e/(n.i-t.i);n.c-=r,n.s+=e,t.c+=r,n.z+=e,n.m+=e}function kd(t,n,e){return t.a.parent===n.parent?t.a:e}function Nd(t,n){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=n}function Cd(t,n,e,r,i){for(var o,a=t.children,u=-1,c=a.length,f=t.value&&(i-e)/t.value;++u<c;)(o=a[u]).x0=n,o.x1=r,o.y0=e,o.y1=e+=o.value*f}Nd.prototype=Object.create(Zh.prototype);var Pd=(1+Math.sqrt(5))/2;function zd(t,n,e,r,i,o){for(var a,u,c,f,s,l,h,d,p,g,y,v=[],_=n.children,b=0,m=0,x=_.length,w=n.value;b<x;){c=i-e,f=o-r;do{s=_[m++].value}while(!s&&m<x);for(l=h=s,y=s*s*(g=Math.max(f/c,c/f)/(w*t)),p=Math.max(h/y,y/l);m<x;++m){if(s+=u=_[m].value,u<l&&(l=u),u>h&&(h=u),y=s*s*g,(d=Math.max(h/y,y/l))>p){s-=u;break}p=d}v.push(a={value:s,dice:c<f,children:_.slice(b,m)}),a.dice?bd(a,e,r,i,w?r+=f*s/w:o):Cd(a,e,r,w?e+=c*s/w:i,o),w-=s,b=m}return v}var Dd=function t(n){function e(t,e,r,i,o){zd(n,t,e,r,i,o)}return e.ratio=function(n){return t((n=+n)>1?n:1)},e}(Pd);var qd=function t(n){function e(t,e,r,i,o){if((a=t._squarify)&&a.ratio===n)for(var a,u,c,f,s,l=-1,h=a.length,d=t.value;++l<h;){for(c=(u=a[l]).children,f=u.value=0,s=c.length;f<s;++f)u.value+=c[f].value;u.dice?bd(u,e,r,i,d?r+=(o-r)*u.value/d:o):Cd(u,e,r,d?e+=(i-e)*u.value/d:i,o),d-=u.value}else t._squarify=a=zd(n,t,e,r,i,o),a.ratio=n}return e.ratio=function(n){return t((n=+n)>1?n:1)},e}(Pd);function Rd(t,n,e){return(n[0]-t[0])*(e[1]-t[1])-(n[1]-t[1])*(e[0]-t[0])}function Fd(t,n){return t[0]-n[0]||t[1]-n[1]}function Od(t){const n=t.length,e=[0,1];let r,i=2;for(r=2;r<n;++r){for(;i>1&&Rd(t[e[i-2]],t[e[i-1]],t[r])<=0;)--i;e[i++]=r}return e.slice(0,i)}var Id=Math.random,Ud=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,1===arguments.length?(e=t,t=0):e-=t,function(){return n()*e+t}}return e.source=t,e}(Id),Bd=function t(n){function e(t,e){return arguments.length<2&&(e=t,t=0),t=Math.floor(t),e=Math.floor(e)-t,function(){return Math.floor(n()*e+t)}}return e.source=t,e}(Id),Yd=function t(n){function e(t,e){var r,i;return t=null==t?0:+t,e=null==e?1:+e,function(){var o;if(null!=r)o=r,r=null;else do{r=2*n()-1,o=2*n()-1,i=r*r+o*o}while(!i||i>1);return t+e*o*Math.sqrt(-2*Math.log(i)/i)}}return e.source=t,e}(Id),Ld=function t(n){var e=Yd.source(n);function r(){var t=e.apply(this,arguments);return function(){return Math.exp(t())}}return r.source=t,r}(Id),jd=function t(n){function e(t){return(t=+t)<=0?()=>0:function(){for(var e=0,r=t;r>1;--r)e+=n();return e+r*n()}}return e.source=t,e}(Id),Hd=function t(n){var e=jd.source(n);function r(t){if(0==(t=+t))return n;var r=e(t);return function(){return r()/t}}return r.source=t,r}(Id),Xd=function t(n){function e(t){return function(){return-Math.log1p(-n())/t}}return e.source=t,e}(Id),Gd=function t(n){function e(t){if((t=+t)<0)throw new RangeError("invalid alpha");return t=1/-t,function(){return Math.pow(1-n(),t)}}return e.source=t,e}(Id),Vd=function t(n){function e(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return function(){return Math.floor(n()+t)}}return e.source=t,e}(Id),$d=function t(n){function e(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return 0===t?()=>1/0:1===t?()=>1:(t=Math.log1p(-t),function(){return 1+Math.floor(Math.log1p(-n())/t)})}return e.source=t,e}(Id),Wd=function t(n){var e=Yd.source(n)();function r(t,r){if((t=+t)<0)throw new RangeError("invalid k");if(0===t)return()=>0;if(r=null==r?1:+r,1===t)return()=>-Math.log1p(-n())*r;var i=(t<1?t+1:t)-1/3,o=1/(3*Math.sqrt(i)),a=t<1?()=>Math.pow(n(),1/t):()=>1;return function(){do{do{var t=e(),u=1+o*t}while(u<=0);u*=u*u;var c=1-n()}while(c>=1-.0331*t*t*t*t&&Math.log(c)>=.5*t*t+i*(1-u+Math.log(u)));return i*u*a()*r}}return r.source=t,r}(Id),Zd=function t(n){var e=Wd.source(n);function r(t,n){var r=e(t),i=e(n);return function(){var t=r();return 0===t?0:t/(t+i())}}return r.source=t,r}(Id),Kd=function t(n){var e=$d.source(n),r=Zd.source(n);function i(t,n){return t=+t,(n=+n)>=1?()=>t:n<=0?()=>0:function(){for(var i=0,o=t,a=n;o*a>16&&o*(1-a)>16;){var u=Math.floor((o+1)*a),c=r(u,o-u+1)();c<=a?(i+=u,o-=u,a=(a-c)/(1-c)):(o=u-1,a/=c)}for(var f=a<.5,s=e(f?a:1-a),l=s(),h=0;l<=o;++h)l+=s();return i+(f?h:o-h)}}return i.source=t,i}(Id),Qd=function t(n){function e(t,e,r){var i;return 0==(t=+t)?i=t=>-Math.log(t):(t=1/t,i=n=>Math.pow(n,t)),e=null==e?0:+e,r=null==r?1:+r,function(){return e+r*i(-Math.log1p(-n()))}}return e.source=t,e}(Id),Jd=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,function(){return t+e*Math.tan(Math.PI*n())}}return e.source=t,e}(Id),tp=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,function(){var r=n();return t+e*Math.log(r/(1-r))}}return e.source=t,e}(Id),np=function t(n){var e=Wd.source(n),r=Kd.source(n);function i(t){return function(){for(var i=0,o=t;o>16;){var a=Math.floor(.875*o),u=e(a)();if(u>o)return i+r(a-1,o/u)();i+=a,o-=u}for(var c=-Math.log1p(-n()),f=0;c<=o;++f)c-=Math.log1p(-n());return i+f}}return i.source=t,i}(Id);const ep=1/4294967296;function rp(t,n){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(n).domain(t)}return this}function ip(t,n){switch(arguments.length){case 0:break;case 1:"function"==typeof t?this.interpolator(t):this.range(t);break;default:this.domain(t),"function"==typeof n?this.interpolator(n):this.range(n)}return this}const op=Symbol("implicit");function ap(){var t=new Map,n=[],e=[],r=op;function i(i){var o=i+"",a=t.get(o);if(!a){if(r!==op)return r;t.set(o,a=n.push(i))}return e[(a-1)%e.length]}return i.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new Map;for(const r of e){const e=r+"";t.has(e)||t.set(e,n.push(r))}return i},i.range=function(t){return arguments.length?(e=Array.from(t),i):e.slice()},i.unknown=function(t){return arguments.length?(r=t,i):r},i.copy=function(){return ap(n,e).unknown(r)},rp.apply(i,arguments),i}function up(){var t,n,e=ap().unknown(void 0),r=e.domain,i=e.range,o=0,a=1,u=!1,c=0,f=0,s=.5;function l(){var e=r().length,l=a<o,h=l?a:o,d=l?o:a;t=(d-h)/Math.max(1,e-c+2*f),u&&(t=Math.floor(t)),h+=(d-h-t*(e-c))*s,n=t*(1-c),u&&(h=Math.round(h),n=Math.round(n));var p=Z(e).map((function(n){return h+t*n}));return i(l?p.reverse():p)}return delete e.unknown,e.domain=function(t){return arguments.length?(r(t),l()):r()},e.range=function(t){return arguments.length?([o,a]=t,o=+o,a=+a,l()):[o,a]},e.rangeRound=function(t){return[o,a]=t,o=+o,a=+a,u=!0,l()},e.bandwidth=function(){return n},e.step=function(){return t},e.round=function(t){return arguments.length?(u=!!t,l()):u},e.padding=function(t){return arguments.length?(c=Math.min(1,f=+t),l()):c},e.paddingInner=function(t){return arguments.length?(c=Math.min(1,t),l()):c},e.paddingOuter=function(t){return arguments.length?(f=+t,l()):f},e.align=function(t){return arguments.length?(s=Math.max(0,Math.min(1,t)),l()):s},e.copy=function(){return up(r(),[o,a]).round(u).paddingInner(c).paddingOuter(f).align(s)},rp.apply(l(),arguments)}function cp(t){var n=t.copy;return t.padding=t.paddingOuter,delete t.paddingInner,delete t.paddingOuter,t.copy=function(){return cp(n())},t}function fp(t){return+t}var sp=[0,1];function lp(t){return t}function hp(t,n){return(n-=t=+t)?function(e){return(e-t)/n}:function(t){return function(){return t}}(isNaN(n)?NaN:.5)}function dp(t,n,e){var r=t[0],i=t[1],o=n[0],a=n[1];return i<r?(r=hp(i,r),o=e(a,o)):(r=hp(r,i),o=e(o,a)),function(t){return o(r(t))}}function pp(t,n,e){var r=Math.min(t.length,n.length)-1,i=new Array(r),a=new Array(r),u=-1;for(t[r]<t[0]&&(t=t.slice().reverse(),n=n.slice().reverse());++u<r;)i[u]=hp(t[u],t[u+1]),a[u]=e(n[u],n[u+1]);return function(n){var e=o(t,n,1,r)-1;return a[e](i[e](n))}}function gp(t,n){return n.domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown())}function yp(){var t,n,e,r,i,o,a=sp,u=sp,c=Mr,f=lp;function s(){var t=Math.min(a.length,u.length);return f!==lp&&(f=function(t,n){var e;return t>n&&(e=t,t=n,n=e),function(e){return Math.max(t,Math.min(n,e))}}(a[0],a[t-1])),r=t>2?pp:dp,i=o=null,l}function l(n){return null==n||isNaN(n=+n)?e:(i||(i=r(a.map(t),u,c)))(t(f(n)))}return l.invert=function(e){return f(n((o||(o=r(u,a.map(t),_r)))(e)))},l.domain=function(t){return arguments.length?(a=Array.from(t,fp),s()):a.slice()},l.range=function(t){return arguments.length?(u=Array.from(t),s()):u.slice()},l.rangeRound=function(t){return u=Array.from(t),c=Ar,s()},l.clamp=function(t){return arguments.length?(f=!!t||lp,s()):f!==lp},l.interpolate=function(t){return arguments.length?(c=t,s()):c},l.unknown=function(t){return arguments.length?(e=t,l):e},function(e,r){return t=e,n=r,s()}}function vp(){return yp()(lp,lp)}function _p(n,e,r,i){var o,a=F(n,e,r);switch((i=ac(null==i?",f":i)).type){case"s":var u=Math.max(Math.abs(n),Math.abs(e));return null!=i.precision||isNaN(o=vc(a,u))||(i.precision=o),t.formatPrefix(i,u);case"":case"e":case"g":case"p":case"r":null!=i.precision||isNaN(o=_c(a,Math.max(Math.abs(n),Math.abs(e))))||(i.precision=o-("e"===i.type));break;case"f":case"%":null!=i.precision||isNaN(o=yc(a))||(i.precision=o-2*("%"===i.type))}return t.format(i)}function bp(t){var n=t.domain;return t.ticks=function(t){var e=n();return q(e[0],e[e.length-1],null==t?10:t)},t.tickFormat=function(t,e){var r=n();return _p(r[0],r[r.length-1],null==t?10:t,e)},t.nice=function(e){null==e&&(e=10);var r,i,o=n(),a=0,u=o.length-1,c=o[a],f=o[u],s=10;for(f<c&&(i=c,c=f,f=i,i=a,a=u,u=i);s-- >0;){if((i=R(c,f,e))===r)return o[a]=c,o[u]=f,n(o);if(i>0)c=Math.floor(c/i)*i,f=Math.ceil(f/i)*i;else{if(!(i<0))break;c=Math.ceil(c*i)/i,f=Math.floor(f*i)/i}r=i}return t},t}function mp(t,n){var e,r=0,i=(t=t.slice()).length-1,o=t[r],a=t[i];return a<o&&(e=r,r=i,i=e,e=o,o=a,a=e),t[r]=n.floor(o),t[i]=n.ceil(a),t}function xp(t){return Math.log(t)}function wp(t){return Math.exp(t)}function Mp(t){return-Math.log(-t)}function Ap(t){return-Math.exp(-t)}function Tp(t){return isFinite(t)?+("1e"+t):t<0?0:t}function Sp(t){return function(n){return-t(-n)}}function Ep(n){var e,r,i=n(xp,wp),o=i.domain,a=10;function u(){return e=function(t){return t===Math.E?Math.log:10===t&&Math.log10||2===t&&Math.log2||(t=Math.log(t),function(n){return Math.log(n)/t})}(a),r=function(t){return 10===t?Tp:t===Math.E?Math.exp:function(n){return Math.pow(t,n)}}(a),o()[0]<0?(e=Sp(e),r=Sp(r),n(Mp,Ap)):n(xp,wp),i}return i.base=function(t){return arguments.length?(a=+t,u()):a},i.domain=function(t){return arguments.length?(o(t),u()):o()},i.ticks=function(t){var n,i=o(),u=i[0],c=i[i.length-1];(n=c<u)&&(h=u,u=c,c=h);var f,s,l,h=e(u),d=e(c),p=null==t?10:+t,g=[];if(!(a%1)&&d-h<p){if(h=Math.floor(h),d=Math.ceil(d),u>0){for(;h<=d;++h)for(s=1,f=r(h);s<a;++s)if(!((l=f*s)<u)){if(l>c)break;g.push(l)}}else for(;h<=d;++h)for(s=a-1,f=r(h);s>=1;--s)if(!((l=f*s)<u)){if(l>c)break;g.push(l)}2*g.length<p&&(g=q(u,c,p))}else g=q(h,d,Math.min(d-h,p)).map(r);return n?g.reverse():g},i.tickFormat=function(n,o){if(null==o&&(o=10===a?".0e":","),"function"!=typeof o&&(o=t.format(o)),n===1/0)return o;null==n&&(n=10);var u=Math.max(1,a*n/i.ticks().length);return function(t){var n=t/r(Math.round(e(t)));return n*a<a-.5&&(n*=a),n<=u?o(t):""}},i.nice=function(){return o(mp(o(),{floor:function(t){return r(Math.floor(e(t)))},ceil:function(t){return r(Math.ceil(e(t)))}}))},i}function kp(t){return function(n){return Math.sign(n)*Math.log1p(Math.abs(n/t))}}function Np(t){return function(n){return Math.sign(n)*Math.expm1(Math.abs(n))*t}}function Cp(t){var n=1,e=t(kp(n),Np(n));return e.constant=function(e){return arguments.length?t(kp(n=+e),Np(n)):n},bp(e)}function Pp(t){return function(n){return n<0?-Math.pow(-n,t):Math.pow(n,t)}}function zp(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function Dp(t){return t<0?-t*t:t*t}function qp(t){var n=t(lp,lp),e=1;function r(){return 1===e?t(lp,lp):.5===e?t(zp,Dp):t(Pp(e),Pp(1/e))}return n.exponent=function(t){return arguments.length?(e=+t,r()):e},bp(n)}function Rp(){var t=qp(yp());return t.copy=function(){return gp(t,Rp()).exponent(t.exponent())},rp.apply(t,arguments),t}function Fp(t){return Math.sign(t)*t*t}function Op(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}var Ip=new Date,Up=new Date;function Bp(t,n,e,r){function i(n){return t(n=0===arguments.length?new Date:new Date(+n)),n}return i.floor=function(n){return t(n=new Date(+n)),n},i.ceil=function(e){return t(e=new Date(e-1)),n(e,1),t(e),e},i.round=function(t){var n=i(t),e=i.ceil(t);return t-n<e-t?n:e},i.offset=function(t,e){return n(t=new Date(+t),null==e?1:Math.floor(e)),t},i.range=function(e,r,o){var a,u=[];if(e=i.ceil(e),o=null==o?1:Math.floor(o),!(e<r&&o>0))return u;do{u.push(a=new Date(+e)),n(e,o),t(e)}while(a<e&&e<r);return u},i.filter=function(e){return Bp((function(n){if(n>=n)for(;t(n),!e(n);)n.setTime(n-1)}),(function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;n(t,-1),!e(t););else for(;--r>=0;)for(;n(t,1),!e(t););}))},e&&(i.count=function(n,r){return Ip.setTime(+n),Up.setTime(+r),t(Ip),t(Up),Math.floor(e(Ip,Up))},i.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?function(n){return r(n)%t==0}:function(n){return i.count(0,n)%t==0}):i:null}),i}var Yp=Bp((function(){}),(function(t,n){t.setTime(+t+n)}),(function(t,n){return n-t}));Yp.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?Bp((function(n){n.setTime(Math.floor(n/t)*t)}),(function(n,e){n.setTime(+n+e*t)}),(function(n,e){return(e-n)/t})):Yp:null};var Lp=Yp.range;const jp=1e3,Hp=6e4,Xp=36e5,Gp=864e5,Vp=6048e5,$p=2592e6,Wp=31536e6;var Zp=Bp((function(t){t.setTime(t-t.getMilliseconds())}),(function(t,n){t.setTime(+t+n*jp)}),(function(t,n){return(n-t)/jp}),(function(t){return t.getUTCSeconds()})),Kp=Zp.range,Qp=Bp((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*jp)}),(function(t,n){t.setTime(+t+n*Hp)}),(function(t,n){return(n-t)/Hp}),(function(t){return t.getMinutes()})),Jp=Qp.range,tg=Bp((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*jp-t.getMinutes()*Hp)}),(function(t,n){t.setTime(+t+n*Xp)}),(function(t,n){return(n-t)/Xp}),(function(t){return t.getHours()})),ng=tg.range,eg=Bp((t=>t.setHours(0,0,0,0)),((t,n)=>t.setDate(t.getDate()+n)),((t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Hp)/Gp),(t=>t.getDate()-1)),rg=eg.range;function ig(t){return Bp((function(n){n.setDate(n.getDate()-(n.getDay()+7-t)%7),n.setHours(0,0,0,0)}),(function(t,n){t.setDate(t.getDate()+7*n)}),(function(t,n){return(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Hp)/Vp}))}var og=ig(0),ag=ig(1),ug=ig(2),cg=ig(3),fg=ig(4),sg=ig(5),lg=ig(6),hg=og.range,dg=ag.range,pg=ug.range,gg=cg.range,yg=fg.range,vg=sg.range,_g=lg.range,bg=Bp((function(t){t.setDate(1),t.setHours(0,0,0,0)}),(function(t,n){t.setMonth(t.getMonth()+n)}),(function(t,n){return n.getMonth()-t.getMonth()+12*(n.getFullYear()-t.getFullYear())}),(function(t){return t.getMonth()})),mg=bg.range,xg=Bp((function(t){t.setMonth(0,1),t.setHours(0,0,0,0)}),(function(t,n){t.setFullYear(t.getFullYear()+n)}),(function(t,n){return n.getFullYear()-t.getFullYear()}),(function(t){return t.getFullYear()}));xg.every=function(t){return isFinite(t=Math.floor(t))&&t>0?Bp((function(n){n.setFullYear(Math.floor(n.getFullYear()/t)*t),n.setMonth(0,1),n.setHours(0,0,0,0)}),(function(n,e){n.setFullYear(n.getFullYear()+e*t)})):null};var wg=xg.range,Mg=Bp((function(t){t.setUTCSeconds(0,0)}),(function(t,n){t.setTime(+t+n*Hp)}),(function(t,n){return(n-t)/Hp}),(function(t){return t.getUTCMinutes()})),Ag=Mg.range,Tg=Bp((function(t){t.setUTCMinutes(0,0,0)}),(function(t,n){t.setTime(+t+n*Xp)}),(function(t,n){return(n-t)/Xp}),(function(t){return t.getUTCHours()})),Sg=Tg.range,Eg=Bp((function(t){t.setUTCHours(0,0,0,0)}),(function(t,n){t.setUTCDate(t.getUTCDate()+n)}),(function(t,n){return(n-t)/Gp}),(function(t){return t.getUTCDate()-1})),kg=Eg.range;function Ng(t){return Bp((function(n){n.setUTCDate(n.getUTCDate()-(n.getUTCDay()+7-t)%7),n.setUTCHours(0,0,0,0)}),(function(t,n){t.setUTCDate(t.getUTCDate()+7*n)}),(function(t,n){return(n-t)/Vp}))}var Cg=Ng(0),Pg=Ng(1),zg=Ng(2),Dg=Ng(3),qg=Ng(4),Rg=Ng(5),Fg=Ng(6),Og=Cg.range,Ig=Pg.range,Ug=zg.range,Bg=Dg.range,Yg=qg.range,Lg=Rg.range,jg=Fg.range,Hg=Bp((function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0)}),(function(t,n){t.setUTCMonth(t.getUTCMonth()+n)}),(function(t,n){return n.getUTCMonth()-t.getUTCMonth()+12*(n.getUTCFullYear()-t.getUTCFullYear())}),(function(t){return t.getUTCMonth()})),Xg=Hg.range,Gg=Bp((function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),(function(t,n){t.setUTCFullYear(t.getUTCFullYear()+n)}),(function(t,n){return n.getUTCFullYear()-t.getUTCFullYear()}),(function(t){return t.getUTCFullYear()}));Gg.every=function(t){return isFinite(t=Math.floor(t))&&t>0?Bp((function(n){n.setUTCFullYear(Math.floor(n.getUTCFullYear()/t)*t),n.setUTCMonth(0,1),n.setUTCHours(0,0,0,0)}),(function(n,e){n.setUTCFullYear(n.getUTCFullYear()+e*t)})):null};var Vg=Gg.range;function $g(t,n,r,i,o,a){const u=[[Zp,1,jp],[Zp,5,5e3],[Zp,15,15e3],[Zp,30,3e4],[a,1,Hp],[a,5,3e5],[a,15,9e5],[a,30,18e5],[o,1,Xp],[o,3,108e5],[o,6,216e5],[o,12,432e5],[i,1,Gp],[i,2,1728e5],[r,1,Vp],[n,1,$p],[n,3,7776e6],[t,1,Wp]];function c(n,r,i){const o=Math.abs(r-n)/i,a=e((([,,t])=>t)).right(u,o);if(a===u.length)return t.every(F(n/Wp,r/Wp,i));if(0===a)return Yp.every(Math.max(F(n,r,i),1));const[c,f]=u[o/u[a-1][2]<u[a][2]/o?a-1:a];return c.every(f)}return[function(t,n,e){const r=n<t;r&&([t,n]=[n,t]);const i=e&&"function"==typeof e.range?e:c(t,n,e),o=i?i.range(t,+n+1):[];return r?o.reverse():o},c]}const[Wg,Zg]=$g(Gg,Hg,Cg,Eg,Tg,Mg),[Kg,Qg]=$g(xg,bg,og,eg,tg,Qp);function Jg(t){if(0<=t.y&&t.y<100){var n=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return n.setFullYear(t.y),n}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function ty(t){if(0<=t.y&&t.y<100){var n=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return n.setUTCFullYear(t.y),n}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function ny(t,n,e){return{y:t,m:n,d:e,H:0,M:0,S:0,L:0}}function ey(t){var n=t.dateTime,e=t.date,r=t.time,i=t.periods,o=t.days,a=t.shortDays,u=t.months,c=t.shortMonths,f=sy(i),s=ly(i),l=sy(o),h=ly(o),d=sy(a),p=ly(a),g=sy(u),y=ly(u),v=sy(c),_=ly(c),b={a:function(t){return a[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return u[t.getMonth()]},c:null,d:zy,e:zy,f:Oy,g:$y,G:Zy,H:Dy,I:qy,j:Ry,L:Fy,m:Iy,M:Uy,p:function(t){return i[+(t.getHours()>=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:bv,s:mv,S:By,u:Yy,U:Ly,V:Hy,w:Xy,W:Gy,x:null,X:null,y:Vy,Y:Wy,Z:Ky,"%":_v},m={a:function(t){return a[t.getUTCDay()]},A:function(t){return o[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return u[t.getUTCMonth()]},c:null,d:Qy,e:Qy,f:rv,g:pv,G:yv,H:Jy,I:tv,j:nv,L:ev,m:iv,M:ov,p:function(t){return i[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:bv,s:mv,S:av,u:uv,U:cv,V:sv,w:lv,W:hv,x:null,X:null,y:dv,Y:gv,Z:vv,"%":_v},x={a:function(t,n,e){var r=d.exec(n.slice(e));return r?(t.w=p.get(r[0].toLowerCase()),e+r[0].length):-1},A:function(t,n,e){var r=l.exec(n.slice(e));return r?(t.w=h.get(r[0].toLowerCase()),e+r[0].length):-1},b:function(t,n,e){var r=v.exec(n.slice(e));return r?(t.m=_.get(r[0].toLowerCase()),e+r[0].length):-1},B:function(t,n,e){var r=g.exec(n.slice(e));return r?(t.m=y.get(r[0].toLowerCase()),e+r[0].length):-1},c:function(t,e,r){return A(t,n,e,r)},d:wy,e:wy,f:ky,g:_y,G:vy,H:Ay,I:Ay,j:My,L:Ey,m:xy,M:Ty,p:function(t,n,e){var r=f.exec(n.slice(e));return r?(t.p=s.get(r[0].toLowerCase()),e+r[0].length):-1},q:my,Q:Cy,s:Py,S:Sy,u:dy,U:py,V:gy,w:hy,W:yy,x:function(t,n,r){return A(t,e,n,r)},X:function(t,n,e){return A(t,r,n,e)},y:_y,Y:vy,Z:by,"%":Ny};function w(t,n){return function(e){var r,i,o,a=[],u=-1,c=0,f=t.length;for(e instanceof Date||(e=new Date(+e));++u<f;)37===t.charCodeAt(u)&&(a.push(t.slice(c,u)),null!=(i=iy[r=t.charAt(++u)])?r=t.charAt(++u):i="e"===r?" ":"0",(o=n[r])&&(r=o(e,i)),a.push(r),c=u+1);return a.push(t.slice(c,u)),a.join("")}}function M(t,n){return function(e){var r,i,o=ny(1900,void 0,1);if(A(o,t,e+="",0)!=e.length)return null;if("Q"in o)return new Date(o.Q);if("s"in o)return new Date(1e3*o.s+("L"in o?o.L:0));if(n&&!("Z"in o)&&(o.Z=0),"p"in o&&(o.H=o.H%12+12*o.p),void 0===o.m&&(o.m="q"in o?o.q:0),"V"in o){if(o.V<1||o.V>53)return null;"w"in o||(o.w=1),"Z"in o?(i=(r=ty(ny(o.y,0,1))).getUTCDay(),r=i>4||0===i?Pg.ceil(r):Pg(r),r=Eg.offset(r,7*(o.V-1)),o.y=r.getUTCFullYear(),o.m=r.getUTCMonth(),o.d=r.getUTCDate()+(o.w+6)%7):(i=(r=Jg(ny(o.y,0,1))).getDay(),r=i>4||0===i?ag.ceil(r):ag(r),r=eg.offset(r,7*(o.V-1)),o.y=r.getFullYear(),o.m=r.getMonth(),o.d=r.getDate()+(o.w+6)%7)}else("W"in o||"U"in o)&&("w"in o||(o.w="u"in o?o.u%7:"W"in o?1:0),i="Z"in o?ty(ny(o.y,0,1)).getUTCDay():Jg(ny(o.y,0,1)).getDay(),o.m=0,o.d="W"in o?(o.w+6)%7+7*o.W-(i+5)%7:o.w+7*o.U-(i+6)%7);return"Z"in o?(o.H+=o.Z/100|0,o.M+=o.Z%100,ty(o)):Jg(o)}}function A(t,n,e,r){for(var i,o,a=0,u=n.length,c=e.length;a<u;){if(r>=c)return-1;if(37===(i=n.charCodeAt(a++))){if(i=n.charAt(a++),!(o=x[i in iy?n.charAt(a++):i])||(r=o(t,e,r))<0)return-1}else if(i!=e.charCodeAt(r++))return-1}return r}return b.x=w(e,b),b.X=w(r,b),b.c=w(n,b),m.x=w(e,m),m.X=w(r,m),m.c=w(n,m),{format:function(t){var n=w(t+="",b);return n.toString=function(){return t},n},parse:function(t){var n=M(t+="",!1);return n.toString=function(){return t},n},utcFormat:function(t){var n=w(t+="",m);return n.toString=function(){return t},n},utcParse:function(t){var n=M(t+="",!0);return n.toString=function(){return t},n}}}var ry,iy={"-":"",_:" ",0:"0"},oy=/^\s*\d+/,ay=/^%/,uy=/[\\^$*+?|[\]().{}]/g;function cy(t,n,e){var r=t<0?"-":"",i=(r?-t:t)+"",o=i.length;return r+(o<e?new Array(e-o+1).join(n)+i:i)}function fy(t){return t.replace(uy,"\\$&")}function sy(t){return new RegExp("^(?:"+t.map(fy).join("|")+")","i")}function ly(t){return new Map(t.map(((t,n)=>[t.toLowerCase(),n])))}function hy(t,n,e){var r=oy.exec(n.slice(e,e+1));return r?(t.w=+r[0],e+r[0].length):-1}function dy(t,n,e){var r=oy.exec(n.slice(e,e+1));return r?(t.u=+r[0],e+r[0].length):-1}function py(t,n,e){var r=oy.exec(n.slice(e,e+2));return r?(t.U=+r[0],e+r[0].length):-1}function gy(t,n,e){var r=oy.exec(n.slice(e,e+2));return r?(t.V=+r[0],e+r[0].length):-1}function yy(t,n,e){var r=oy.exec(n.slice(e,e+2));return r?(t.W=+r[0],e+r[0].length):-1}function vy(t,n,e){var r=oy.exec(n.slice(e,e+4));return r?(t.y=+r[0],e+r[0].length):-1}function _y(t,n,e){var r=oy.exec(n.slice(e,e+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),e+r[0].length):-1}function by(t,n,e){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(n.slice(e,e+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),e+r[0].length):-1}function my(t,n,e){var r=oy.exec(n.slice(e,e+1));return r?(t.q=3*r[0]-3,e+r[0].length):-1}function xy(t,n,e){var r=oy.exec(n.slice(e,e+2));return r?(t.m=r[0]-1,e+r[0].length):-1}function wy(t,n,e){var r=oy.exec(n.slice(e,e+2));return r?(t.d=+r[0],e+r[0].length):-1}function My(t,n,e){var r=oy.exec(n.slice(e,e+3));return r?(t.m=0,t.d=+r[0],e+r[0].length):-1}function Ay(t,n,e){var r=oy.exec(n.slice(e,e+2));return r?(t.H=+r[0],e+r[0].length):-1}function Ty(t,n,e){var r=oy.exec(n.slice(e,e+2));return r?(t.M=+r[0],e+r[0].length):-1}function Sy(t,n,e){var r=oy.exec(n.slice(e,e+2));return r?(t.S=+r[0],e+r[0].length):-1}function Ey(t,n,e){var r=oy.exec(n.slice(e,e+3));return r?(t.L=+r[0],e+r[0].length):-1}function ky(t,n,e){var r=oy.exec(n.slice(e,e+6));return r?(t.L=Math.floor(r[0]/1e3),e+r[0].length):-1}function Ny(t,n,e){var r=ay.exec(n.slice(e,e+1));return r?e+r[0].length:-1}function Cy(t,n,e){var r=oy.exec(n.slice(e));return r?(t.Q=+r[0],e+r[0].length):-1}function Py(t,n,e){var r=oy.exec(n.slice(e));return r?(t.s=+r[0],e+r[0].length):-1}function zy(t,n){return cy(t.getDate(),n,2)}function Dy(t,n){return cy(t.getHours(),n,2)}function qy(t,n){return cy(t.getHours()%12||12,n,2)}function Ry(t,n){return cy(1+eg.count(xg(t),t),n,3)}function Fy(t,n){return cy(t.getMilliseconds(),n,3)}function Oy(t,n){return Fy(t,n)+"000"}function Iy(t,n){return cy(t.getMonth()+1,n,2)}function Uy(t,n){return cy(t.getMinutes(),n,2)}function By(t,n){return cy(t.getSeconds(),n,2)}function Yy(t){var n=t.getDay();return 0===n?7:n}function Ly(t,n){return cy(og.count(xg(t)-1,t),n,2)}function jy(t){var n=t.getDay();return n>=4||0===n?fg(t):fg.ceil(t)}function Hy(t,n){return t=jy(t),cy(fg.count(xg(t),t)+(4===xg(t).getDay()),n,2)}function Xy(t){return t.getDay()}function Gy(t,n){return cy(ag.count(xg(t)-1,t),n,2)}function Vy(t,n){return cy(t.getFullYear()%100,n,2)}function $y(t,n){return cy((t=jy(t)).getFullYear()%100,n,2)}function Wy(t,n){return cy(t.getFullYear()%1e4,n,4)}function Zy(t,n){var e=t.getDay();return cy((t=e>=4||0===e?fg(t):fg.ceil(t)).getFullYear()%1e4,n,4)}function Ky(t){var n=t.getTimezoneOffset();return(n>0?"-":(n*=-1,"+"))+cy(n/60|0,"0",2)+cy(n%60,"0",2)}function Qy(t,n){return cy(t.getUTCDate(),n,2)}function Jy(t,n){return cy(t.getUTCHours(),n,2)}function tv(t,n){return cy(t.getUTCHours()%12||12,n,2)}function nv(t,n){return cy(1+Eg.count(Gg(t),t),n,3)}function ev(t,n){return cy(t.getUTCMilliseconds(),n,3)}function rv(t,n){return ev(t,n)+"000"}function iv(t,n){return cy(t.getUTCMonth()+1,n,2)}function ov(t,n){return cy(t.getUTCMinutes(),n,2)}function av(t,n){return cy(t.getUTCSeconds(),n,2)}function uv(t){var n=t.getUTCDay();return 0===n?7:n}function cv(t,n){return cy(Cg.count(Gg(t)-1,t),n,2)}function fv(t){var n=t.getUTCDay();return n>=4||0===n?qg(t):qg.ceil(t)}function sv(t,n){return t=fv(t),cy(qg.count(Gg(t),t)+(4===Gg(t).getUTCDay()),n,2)}function lv(t){return t.getUTCDay()}function hv(t,n){return cy(Pg.count(Gg(t)-1,t),n,2)}function dv(t,n){return cy(t.getUTCFullYear()%100,n,2)}function pv(t,n){return cy((t=fv(t)).getUTCFullYear()%100,n,2)}function gv(t,n){return cy(t.getUTCFullYear()%1e4,n,4)}function yv(t,n){var e=t.getUTCDay();return cy((t=e>=4||0===e?qg(t):qg.ceil(t)).getUTCFullYear()%1e4,n,4)}function vv(){return"+0000"}function _v(){return"%"}function bv(t){return+t}function mv(t){return Math.floor(+t/1e3)}function xv(n){return ry=ey(n),t.timeFormat=ry.format,t.timeParse=ry.parse,t.utcFormat=ry.utcFormat,t.utcParse=ry.utcParse,ry}t.timeFormat=void 0,t.timeParse=void 0,t.utcFormat=void 0,t.utcParse=void 0,xv({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});var wv="%Y-%m-%dT%H:%M:%S.%LZ";var Mv=Date.prototype.toISOString?function(t){return t.toISOString()}:t.utcFormat(wv);var Av=+new Date("2000-01-01T00:00:00.000Z")?function(t){var n=new Date(t);return isNaN(n)?null:n}:t.utcParse(wv);function Tv(t){return new Date(t)}function Sv(t){return t instanceof Date?+t:+new Date(+t)}function Ev(t,n,e,r,i,o,a,u,c,f){var s=vp(),l=s.invert,h=s.domain,d=f(".%L"),p=f(":%S"),g=f("%I:%M"),y=f("%I %p"),v=f("%a %d"),_=f("%b %d"),b=f("%B"),m=f("%Y");function x(t){return(c(t)<t?d:u(t)<t?p:a(t)<t?g:o(t)<t?y:r(t)<t?i(t)<t?v:_:e(t)<t?b:m)(t)}return s.invert=function(t){return new Date(l(t))},s.domain=function(t){return arguments.length?h(Array.from(t,Sv)):h().map(Tv)},s.ticks=function(n){var e=h();return t(e[0],e[e.length-1],null==n?10:n)},s.tickFormat=function(t,n){return null==n?x:f(n)},s.nice=function(t){var e=h();return t&&"function"==typeof t.range||(t=n(e[0],e[e.length-1],null==t?10:t)),t?h(mp(e,t)):s},s.copy=function(){return gp(s,Ev(t,n,e,r,i,o,a,u,c,f))},s}function kv(){var t,n,e,r,i,o=0,a=1,u=lp,c=!1;function f(n){return null==n||isNaN(n=+n)?i:u(0===e?.5:(n=(r(n)-t)*e,c?Math.max(0,Math.min(1,n)):n))}function s(t){return function(n){var e,r;return arguments.length?([e,r]=n,u=t(e,r),f):[u(0),u(1)]}}return f.domain=function(i){return arguments.length?([o,a]=i,t=r(o=+o),n=r(a=+a),e=t===n?0:1/(n-t),f):[o,a]},f.clamp=function(t){return arguments.length?(c=!!t,f):c},f.interpolator=function(t){return arguments.length?(u=t,f):u},f.range=s(Mr),f.rangeRound=s(Ar),f.unknown=function(t){return arguments.length?(i=t,f):i},function(i){return r=i,t=i(o),n=i(a),e=t===n?0:1/(n-t),f}}function Nv(t,n){return n.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function Cv(){var t=qp(kv());return t.copy=function(){return Nv(t,Cv()).exponent(t.exponent())},ip.apply(t,arguments)}function Pv(){var t,n,e,r,i,o,a,u=0,c=.5,f=1,s=1,l=lp,h=!1;function d(t){return isNaN(t=+t)?a:(t=.5+((t=+o(t))-n)*(s*t<s*n?r:i),l(h?Math.max(0,Math.min(1,t)):t))}function p(t){return function(n){var e,r,i;return arguments.length?([e,r,i]=n,l=jr(t,[e,r,i]),d):[l(0),l(.5),l(1)]}}return d.domain=function(a){return arguments.length?([u,c,f]=a,t=o(u=+u),n=o(c=+c),e=o(f=+f),r=t===n?0:.5/(n-t),i=n===e?0:.5/(e-n),s=n<t?-1:1,d):[u,c,f]},d.clamp=function(t){return arguments.length?(h=!!t,d):h},d.interpolator=function(t){return arguments.length?(l=t,d):l},d.range=p(Mr),d.rangeRound=p(Ar),d.unknown=function(t){return arguments.length?(a=t,d):a},function(a){return o=a,t=a(u),n=a(c),e=a(f),r=t===n?0:.5/(n-t),i=n===e?0:.5/(e-n),s=n<t?-1:1,d}}function zv(){var t=qp(Pv());return t.copy=function(){return Nv(t,zv()).exponent(t.exponent())},ip.apply(t,arguments)}function Dv(t){for(var n=t.length/6|0,e=new Array(n),r=0;r<n;)e[r]="#"+t.slice(6*r,6*++r);return e}var qv=Dv("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"),Rv=Dv("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"),Fv=Dv("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),Ov=Dv("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"),Iv=Dv("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"),Uv=Dv("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"),Bv=Dv("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"),Yv=Dv("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"),Lv=Dv("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"),jv=Dv("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab"),Hv=t=>hr(t[t.length-1]),Xv=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(Dv),Gv=Hv(Xv),Vv=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(Dv),$v=Hv(Vv),Wv=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(Dv),Zv=Hv(Wv),Kv=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(Dv),Qv=Hv(Kv),Jv=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(Dv),t_=Hv(Jv),n_=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(Dv),e_=Hv(n_),r_=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(Dv),i_=Hv(r_),o_=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(Dv),a_=Hv(o_),u_=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(Dv),c_=Hv(u_),f_=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(Dv),s_=Hv(f_),l_=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(Dv),h_=Hv(l_),d_=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(Dv),p_=Hv(d_),g_=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(Dv),y_=Hv(g_),v_=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(Dv),__=Hv(v_),b_=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(Dv),m_=Hv(b_),x_=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(Dv),w_=Hv(x_),M_=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(Dv),A_=Hv(M_),T_=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(Dv),S_=Hv(T_),E_=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(Dv),k_=Hv(E_),N_=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(Dv),C_=Hv(N_),P_=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(Dv),z_=Hv(P_),D_=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(Dv),q_=Hv(D_),R_=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(Dv),F_=Hv(R_),O_=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(Dv),I_=Hv(O_),U_=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(Dv),B_=Hv(U_),Y_=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(Dv),L_=Hv(Y_),j_=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(Dv),H_=Hv(j_);var X_=Lr(tr(300,.5,0),tr(-240,.5,1)),G_=Lr(tr(-100,.75,.35),tr(80,1.5,.8)),V_=Lr(tr(260,.75,.35),tr(80,1.5,.8)),$_=tr();var W_=ve(),Z_=Math.PI/3,K_=2*Math.PI/3;function Q_(t){var n=t.length;return function(e){return t[Math.max(0,Math.min(n-1,Math.floor(e*n)))]}}var J_=Q_(Dv("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")),tb=Q_(Dv("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),nb=Q_(Dv("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),eb=Q_(Dv("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function rb(t){return function(){return t}}var ib=Math.abs,ob=Math.atan2,ab=Math.cos,ub=Math.max,cb=Math.min,fb=Math.sin,sb=Math.sqrt,lb=1e-12,hb=Math.PI,db=hb/2,pb=2*hb;function gb(t){return t>1?0:t<-1?hb:Math.acos(t)}function yb(t){return t>=1?db:t<=-1?-db:Math.asin(t)}function vb(t){return t.innerRadius}function _b(t){return t.outerRadius}function bb(t){return t.startAngle}function mb(t){return t.endAngle}function xb(t){return t&&t.padAngle}function wb(t,n,e,r,i,o,a,u){var c=e-t,f=r-n,s=a-i,l=u-o,h=l*c-s*f;if(!(h*h<lb))return[t+(h=(s*(n-o)-l*(t-i))/h)*c,n+h*f]}function Mb(t,n,e,r,i,o,a){var u=t-e,c=n-r,f=(a?o:-o)/sb(u*u+c*c),s=f*c,l=-f*u,h=t+s,d=n+l,p=e+s,g=r+l,y=(h+p)/2,v=(d+g)/2,_=p-h,b=g-d,m=_*_+b*b,x=i-o,w=h*g-p*d,M=(b<0?-1:1)*sb(ub(0,x*x*m-w*w)),A=(w*b-_*M)/m,T=(-w*_-b*M)/m,S=(w*b+_*M)/m,E=(-w*_+b*M)/m,k=A-y,N=T-v,C=S-y,P=E-v;return k*k+N*N>C*C+P*P&&(A=S,T=E),{cx:A,cy:T,x01:-s,y01:-l,x11:A*(i/x-1),y11:T*(i/x-1)}}var Ab=Array.prototype.slice;function Tb(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function Sb(t){this._context=t}function Eb(t){return new Sb(t)}function kb(t){return t[0]}function Nb(t){return t[1]}function Cb(t,n){var e=rb(!0),r=null,i=Eb,o=null;function a(a){var u,c,f,s=(a=Tb(a)).length,l=!1;for(null==r&&(o=i(f=fa())),u=0;u<=s;++u)!(u<s&&e(c=a[u],u,a))===l&&((l=!l)?o.lineStart():o.lineEnd()),l&&o.point(+t(c,u,a),+n(c,u,a));if(f)return o=null,f+""||null}return t="function"==typeof t?t:void 0===t?kb:rb(t),n="function"==typeof n?n:void 0===n?Nb:rb(n),a.x=function(n){return arguments.length?(t="function"==typeof n?n:rb(+n),a):t},a.y=function(t){return arguments.length?(n="function"==typeof t?t:rb(+t),a):n},a.defined=function(t){return arguments.length?(e="function"==typeof t?t:rb(!!t),a):e},a.curve=function(t){return arguments.length?(i=t,null!=r&&(o=i(r)),a):i},a.context=function(t){return arguments.length?(null==t?r=o=null:o=i(r=t),a):r},a}function Pb(t,n,e){var r=null,i=rb(!0),o=null,a=Eb,u=null;function c(c){var f,s,l,h,d,p=(c=Tb(c)).length,g=!1,y=new Array(p),v=new Array(p);for(null==o&&(u=a(d=fa())),f=0;f<=p;++f){if(!(f<p&&i(h=c[f],f,c))===g)if(g=!g)s=f,u.areaStart(),u.lineStart();else{for(u.lineEnd(),u.lineStart(),l=f-1;l>=s;--l)u.point(y[l],v[l]);u.lineEnd(),u.areaEnd()}g&&(y[f]=+t(h,f,c),v[f]=+n(h,f,c),u.point(r?+r(h,f,c):y[f],e?+e(h,f,c):v[f]))}if(d)return u=null,d+""||null}function f(){return Cb().defined(i).curve(a).context(o)}return t="function"==typeof t?t:void 0===t?kb:rb(+t),n="function"==typeof n?n:rb(void 0===n?0:+n),e="function"==typeof e?e:void 0===e?Nb:rb(+e),c.x=function(n){return arguments.length?(t="function"==typeof n?n:rb(+n),r=null,c):t},c.x0=function(n){return arguments.length?(t="function"==typeof n?n:rb(+n),c):t},c.x1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:rb(+t),c):r},c.y=function(t){return arguments.length?(n="function"==typeof t?t:rb(+t),e=null,c):n},c.y0=function(t){return arguments.length?(n="function"==typeof t?t:rb(+t),c):n},c.y1=function(t){return arguments.length?(e=null==t?null:"function"==typeof t?t:rb(+t),c):e},c.lineX0=c.lineY0=function(){return f().x(t).y(n)},c.lineY1=function(){return f().x(t).y(e)},c.lineX1=function(){return f().x(r).y(n)},c.defined=function(t){return arguments.length?(i="function"==typeof t?t:rb(!!t),c):i},c.curve=function(t){return arguments.length?(a=t,null!=o&&(u=a(o)),c):a},c.context=function(t){return arguments.length?(null==t?o=u=null:u=a(o=t),c):o},c}function zb(t,n){return n<t?-1:n>t?1:n>=t?0:NaN}function Db(t){return t}Sb.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._context.lineTo(t,n)}}};var qb=Fb(Eb);function Rb(t){this._curve=t}function Fb(t){function n(n){return new Rb(t(n))}return n._curve=t,n}function Ob(t){var n=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?n(Fb(t)):n()._curve},t}function Ib(){return Ob(Cb().curve(qb))}function Ub(){var t=Pb().curve(qb),n=t.curve,e=t.lineX0,r=t.lineX1,i=t.lineY0,o=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return Ob(e())},delete t.lineX0,t.lineEndAngle=function(){return Ob(r())},delete t.lineX1,t.lineInnerRadius=function(){return Ob(i())},delete t.lineY0,t.lineOuterRadius=function(){return Ob(o())},delete t.lineY1,t.curve=function(t){return arguments.length?n(Fb(t)):n()._curve},t}function Bb(t,n){return[(n=+n)*Math.cos(t-=Math.PI/2),n*Math.sin(t)]}function Yb(t){return t.source}function Lb(t){return t.target}function jb(t){var n=Yb,e=Lb,r=kb,i=Nb,o=null;function a(){var a,u=Ab.call(arguments),c=n.apply(this,u),f=e.apply(this,u);if(o||(o=a=fa()),t(o,+r.apply(this,(u[0]=c,u)),+i.apply(this,u),+r.apply(this,(u[0]=f,u)),+i.apply(this,u)),a)return o=null,a+""||null}return a.source=function(t){return arguments.length?(n=t,a):n},a.target=function(t){return arguments.length?(e=t,a):e},a.x=function(t){return arguments.length?(r="function"==typeof t?t:rb(+t),a):r},a.y=function(t){return arguments.length?(i="function"==typeof t?t:rb(+t),a):i},a.context=function(t){return arguments.length?(o=null==t?null:t,a):o},a}function Hb(t,n,e,r,i){t.moveTo(n,e),t.bezierCurveTo(n=(n+r)/2,e,n,i,r,i)}function Xb(t,n,e,r,i){t.moveTo(n,e),t.bezierCurveTo(n,e=(e+i)/2,r,e,r,i)}function Gb(t,n,e,r,i){var o=Bb(n,e),a=Bb(n,e=(e+i)/2),u=Bb(r,e),c=Bb(r,i);t.moveTo(o[0],o[1]),t.bezierCurveTo(a[0],a[1],u[0],u[1],c[0],c[1])}Rb.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,n){this._curve.point(n*Math.sin(t),n*-Math.cos(t))}};var Vb={draw:function(t,n){var e=Math.sqrt(n/hb);t.moveTo(e,0),t.arc(0,0,e,0,pb)}},$b={draw:function(t,n){var e=Math.sqrt(n/5)/2;t.moveTo(-3*e,-e),t.lineTo(-e,-e),t.lineTo(-e,-3*e),t.lineTo(e,-3*e),t.lineTo(e,-e),t.lineTo(3*e,-e),t.lineTo(3*e,e),t.lineTo(e,e),t.lineTo(e,3*e),t.lineTo(-e,3*e),t.lineTo(-e,e),t.lineTo(-3*e,e),t.closePath()}},Wb=Math.sqrt(1/3),Zb=2*Wb,Kb={draw:function(t,n){var e=Math.sqrt(n/Zb),r=e*Wb;t.moveTo(0,-e),t.lineTo(r,0),t.lineTo(0,e),t.lineTo(-r,0),t.closePath()}},Qb=Math.sin(hb/10)/Math.sin(7*hb/10),Jb=Math.sin(pb/10)*Qb,tm=-Math.cos(pb/10)*Qb,nm={draw:function(t,n){var e=Math.sqrt(.8908130915292852*n),r=Jb*e,i=tm*e;t.moveTo(0,-e),t.lineTo(r,i);for(var o=1;o<5;++o){var a=pb*o/5,u=Math.cos(a),c=Math.sin(a);t.lineTo(c*e,-u*e),t.lineTo(u*r-c*i,c*r+u*i)}t.closePath()}},em={draw:function(t,n){var e=Math.sqrt(n),r=-e/2;t.rect(r,r,e,e)}},rm=Math.sqrt(3),im={draw:function(t,n){var e=-Math.sqrt(n/(3*rm));t.moveTo(0,2*e),t.lineTo(-rm*e,-e),t.lineTo(rm*e,-e),t.closePath()}},om=-.5,am=Math.sqrt(3)/2,um=1/Math.sqrt(12),cm=3*(um/2+1),fm={draw:function(t,n){var e=Math.sqrt(n/cm),r=e/2,i=e*um,o=r,a=e*um+e,u=-o,c=a;t.moveTo(r,i),t.lineTo(o,a),t.lineTo(u,c),t.lineTo(om*r-am*i,am*r+om*i),t.lineTo(om*o-am*a,am*o+om*a),t.lineTo(om*u-am*c,am*u+om*c),t.lineTo(om*r+am*i,om*i-am*r),t.lineTo(om*o+am*a,om*a-am*o),t.lineTo(om*u+am*c,om*c-am*u),t.closePath()}},sm=[Vb,$b,Kb,em,nm,im,fm];function lm(){}function hm(t,n,e){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+n)/6,(t._y0+4*t._y1+e)/6)}function dm(t){this._context=t}function pm(t){this._context=t}function gm(t){this._context=t}dm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:hm(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:hm(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},pm.prototype={areaStart:lm,areaEnd:lm,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x2=t,this._y2=n;break;case 1:this._point=2,this._x3=t,this._y3=n;break;case 2:this._point=3,this._x4=t,this._y4=n,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+n)/6);break;default:hm(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},gm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var e=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+n)/6;this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break;case 3:this._point=4;default:hm(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}};class ym{constructor(t,n){this._context=t,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line}point(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,n,t,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,t,this._y0,t,n)}this._x0=t,this._y0=n}}function vm(t,n){this._basis=new dm(t),this._beta=n}vm.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,n=this._y,e=t.length-1;if(e>0)for(var r,i=t[0],o=n[0],a=t[e]-i,u=n[e]-o,c=-1;++c<=e;)r=c/e,this._basis.point(this._beta*t[c]+(1-this._beta)*(i+r*a),this._beta*n[c]+(1-this._beta)*(o+r*u));this._x=this._y=null,this._basis.lineEnd()},point:function(t,n){this._x.push(+t),this._y.push(+n)}};var _m=function t(n){function e(t){return 1===n?new dm(t):new vm(t,n)}return e.beta=function(n){return t(+n)},e}(.85);function bm(t,n,e){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-n),t._y2+t._k*(t._y1-e),t._x2,t._y2)}function mm(t,n){this._context=t,this._k=(1-n)/6}mm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:bm(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2,this._x1=t,this._y1=n;break;case 2:this._point=3;default:bm(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var xm=function t(n){function e(t){return new mm(t,n)}return e.tension=function(n){return t(+n)},e}(0);function wm(t,n){this._context=t,this._k=(1-n)/6}wm.prototype={areaStart:lm,areaEnd:lm,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:bm(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Mm=function t(n){function e(t){return new wm(t,n)}return e.tension=function(n){return t(+n)},e}(0);function Am(t,n){this._context=t,this._k=(1-n)/6}Am.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:bm(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Tm=function t(n){function e(t){return new Am(t,n)}return e.tension=function(n){return t(+n)},e}(0);function Sm(t,n,e){var r=t._x1,i=t._y1,o=t._x2,a=t._y2;if(t._l01_a>lb){var u=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*u-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,i=(i*u-t._y0*t._l12_2a+t._y2*t._l01_2a)/c}if(t._l23_a>lb){var f=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,s=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*f+t._x1*t._l23_2a-n*t._l12_2a)/s,a=(a*f+t._y1*t._l23_2a-e*t._l12_2a)/s}t._context.bezierCurveTo(r,i,o,a,t._x2,t._y2)}function Em(t,n){this._context=t,this._alpha=n}Em.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3;default:Sm(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var km=function t(n){function e(t){return n?new Em(t,n):new mm(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function Nm(t,n){this._context=t,this._alpha=n}Nm.prototype={areaStart:lm,areaEnd:lm,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:Sm(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Cm=function t(n){function e(t){return n?new Nm(t,n):new wm(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function Pm(t,n){this._context=t,this._alpha=n}Pm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Sm(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var zm=function t(n){function e(t){return n?new Pm(t,n):new Am(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function Dm(t){this._context=t}function qm(t){return t<0?-1:1}function Rm(t,n,e){var r=t._x1-t._x0,i=n-t._x1,o=(t._y1-t._y0)/(r||i<0&&-0),a=(e-t._y1)/(i||r<0&&-0),u=(o*i+a*r)/(r+i);return(qm(o)+qm(a))*Math.min(Math.abs(o),Math.abs(a),.5*Math.abs(u))||0}function Fm(t,n){var e=t._x1-t._x0;return e?(3*(t._y1-t._y0)/e-n)/2:n}function Om(t,n,e){var r=t._x0,i=t._y0,o=t._x1,a=t._y1,u=(o-r)/3;t._context.bezierCurveTo(r+u,i+u*n,o-u,a-u*e,o,a)}function Im(t){this._context=t}function Um(t){this._context=new Bm(t)}function Bm(t){this._context=t}function Ym(t){this._context=t}function Lm(t){var n,e,r=t.length-1,i=new Array(r),o=new Array(r),a=new Array(r);for(i[0]=0,o[0]=2,a[0]=t[0]+2*t[1],n=1;n<r-1;++n)i[n]=1,o[n]=4,a[n]=4*t[n]+2*t[n+1];for(i[r-1]=2,o[r-1]=7,a[r-1]=8*t[r-1]+t[r],n=1;n<r;++n)e=i[n]/o[n-1],o[n]-=e,a[n]-=e*a[n-1];for(i[r-1]=a[r-1]/o[r-1],n=r-2;n>=0;--n)i[n]=(a[n]-i[n+1])/o[n];for(o[r-1]=(t[r]+i[r-1])/2,n=0;n<r-1;++n)o[n]=2*t[n+1]-i[n+1];return[i,o]}function jm(t,n){this._context=t,this._t=n}function Hm(t,n){if((i=t.length)>1)for(var e,r,i,o=1,a=t[n[0]],u=a.length;o<i;++o)for(r=a,a=t[n[o]],e=0;e<u;++e)a[e][1]+=a[e][0]=isNaN(r[e][1])?r[e][0]:r[e][1]}function Xm(t){for(var n=t.length,e=new Array(n);--n>=0;)e[n]=n;return e}function Gm(t,n){return t[n]}function Vm(t){const n=[];return n.key=t,n}function $m(t){var n=t.map(Wm);return Xm(t).sort((function(t,e){return n[t]-n[e]}))}function Wm(t){for(var n,e=-1,r=0,i=t.length,o=-1/0;++e<i;)(n=+t[e][1])>o&&(o=n,r=e);return r}function Zm(t){var n=t.map(Km);return Xm(t).sort((function(t,e){return n[t]-n[e]}))}function Km(t){for(var n,e=0,r=-1,i=t.length;++r<i;)(n=+t[r][1])&&(e+=n);return e}Dm.prototype={areaStart:lm,areaEnd:lm,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,n){t=+t,n=+n,this._point?this._context.lineTo(t,n):(this._point=1,this._context.moveTo(t,n))}},Im.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Om(this,this._t0,Fm(this,this._t0))}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){var e=NaN;if(n=+n,(t=+t)!==this._x1||n!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3,Om(this,Fm(this,e=Rm(this,t,n)),e);break;default:Om(this,this._t0,e=Rm(this,t,n))}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n,this._t0=e}}},(Um.prototype=Object.create(Im.prototype)).point=function(t,n){Im.prototype.point.call(this,n,t)},Bm.prototype={moveTo:function(t,n){this._context.moveTo(n,t)},closePath:function(){this._context.closePath()},lineTo:function(t,n){this._context.lineTo(n,t)},bezierCurveTo:function(t,n,e,r,i,o){this._context.bezierCurveTo(n,t,r,e,o,i)}},Ym.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,n=this._y,e=t.length;if(e)if(this._line?this._context.lineTo(t[0],n[0]):this._context.moveTo(t[0],n[0]),2===e)this._context.lineTo(t[1],n[1]);else for(var r=Lm(t),i=Lm(n),o=0,a=1;a<e;++o,++a)this._context.bezierCurveTo(r[0][o],i[0][o],r[1][o],i[1][o],t[a],n[a]);(this._line||0!==this._line&&1===e)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(t,n){this._x.push(+t),this._y.push(+n)}},jm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&2===this._point&&this._context.lineTo(this._x,this._y),(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,n),this._context.lineTo(t,n);else{var e=this._x*(1-this._t)+t*this._t;this._context.lineTo(e,this._y),this._context.lineTo(e,n)}}this._x=t,this._y=n}};var Qm=t=>()=>t;function Jm(t,{sourceEvent:n,target:e,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},target:{value:e,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function tx(t,n,e){this.k=t,this.x=n,this.y=e}tx.prototype={constructor:tx,scale:function(t){return 1===t?this:new tx(this.k*t,this.x,this.y)},translate:function(t,n){return 0===t&0===n?this:new tx(this.k,this.x+this.k*t,this.y+this.k*n)},apply:function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return(t-this.x)/this.k},invertY:function(t){return(t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var nx=new tx(1,0,0);function ex(t){for(;!t.__zoom;)if(!(t=t.parentNode))return nx;return t.__zoom}function rx(t){t.stopImmediatePropagation()}function ix(t){t.preventDefault(),t.stopImmediatePropagation()}function ox(t){return!(t.ctrlKey&&"wheel"!==t.type||t.button)}function ax(){var t=this;return t instanceof SVGElement?(t=t.ownerSVGElement||t).hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]:[[0,0],[t.clientWidth,t.clientHeight]]}function ux(){return this.__zoom||nx}function cx(t){return-t.deltaY*(1===t.deltaMode?.05:t.deltaMode?1:.002)*(t.ctrlKey?10:1)}function fx(){return navigator.maxTouchPoints||"ontouchstart"in this}function sx(t,n,e){var r=t.invertX(n[0][0])-e[0][0],i=t.invertX(n[1][0])-e[1][0],o=t.invertY(n[0][1])-e[0][1],a=t.invertY(n[1][1])-e[1][1];return t.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),a>o?(o+a)/2:Math.min(0,o)||Math.max(0,a))}ex.prototype=tx.prototype,t.Adder=g,t.Delaunay=nu,t.FormatSpecifier=uc,t.InternMap=y,t.InternSet=v,t.Voronoi=Wa,t.active=function(t,n){var e,r,i=t.__transition;if(i)for(r in n=null==n?null:n+"",i)if((e=i[r]).state>1&&e.name===n)return new ji([[t]],_o,n,+r);return null},t.arc=function(){var t=vb,n=_b,e=rb(0),r=null,i=bb,o=mb,a=xb,u=null;function c(){var c,f,s=+t.apply(this,arguments),l=+n.apply(this,arguments),h=i.apply(this,arguments)-db,d=o.apply(this,arguments)-db,p=ib(d-h),g=d>h;if(u||(u=c=fa()),l<s&&(f=l,l=s,s=f),l>lb)if(p>pb-lb)u.moveTo(l*ab(h),l*fb(h)),u.arc(0,0,l,h,d,!g),s>lb&&(u.moveTo(s*ab(d),s*fb(d)),u.arc(0,0,s,d,h,g));else{var y,v,_=h,b=d,m=h,x=d,w=p,M=p,A=a.apply(this,arguments)/2,T=A>lb&&(r?+r.apply(this,arguments):sb(s*s+l*l)),S=cb(ib(l-s)/2,+e.apply(this,arguments)),E=S,k=S;if(T>lb){var N=yb(T/s*fb(A)),C=yb(T/l*fb(A));(w-=2*N)>lb?(m+=N*=g?1:-1,x-=N):(w=0,m=x=(h+d)/2),(M-=2*C)>lb?(_+=C*=g?1:-1,b-=C):(M=0,_=b=(h+d)/2)}var P=l*ab(_),z=l*fb(_),D=s*ab(x),q=s*fb(x);if(S>lb){var R,F=l*ab(b),O=l*fb(b),I=s*ab(m),U=s*fb(m);if(p<hb&&(R=wb(P,z,I,U,F,O,D,q))){var B=P-R[0],Y=z-R[1],L=F-R[0],j=O-R[1],H=1/fb(gb((B*L+Y*j)/(sb(B*B+Y*Y)*sb(L*L+j*j)))/2),X=sb(R[0]*R[0]+R[1]*R[1]);E=cb(S,(s-X)/(H-1)),k=cb(S,(l-X)/(H+1))}}M>lb?k>lb?(y=Mb(I,U,P,z,l,k,g),v=Mb(F,O,D,q,l,k,g),u.moveTo(y.cx+y.x01,y.cy+y.y01),k<S?u.arc(y.cx,y.cy,k,ob(y.y01,y.x01),ob(v.y01,v.x01),!g):(u.arc(y.cx,y.cy,k,ob(y.y01,y.x01),ob(y.y11,y.x11),!g),u.arc(0,0,l,ob(y.cy+y.y11,y.cx+y.x11),ob(v.cy+v.y11,v.cx+v.x11),!g),u.arc(v.cx,v.cy,k,ob(v.y11,v.x11),ob(v.y01,v.x01),!g))):(u.moveTo(P,z),u.arc(0,0,l,_,b,!g)):u.moveTo(P,z),s>lb&&w>lb?E>lb?(y=Mb(D,q,F,O,s,-E,g),v=Mb(P,z,I,U,s,-E,g),u.lineTo(y.cx+y.x01,y.cy+y.y01),E<S?u.arc(y.cx,y.cy,E,ob(y.y01,y.x01),ob(v.y01,v.x01),!g):(u.arc(y.cx,y.cy,E,ob(y.y01,y.x01),ob(y.y11,y.x11),!g),u.arc(0,0,s,ob(y.cy+y.y11,y.cx+y.x11),ob(v.cy+v.y11,v.cx+v.x11),g),u.arc(v.cx,v.cy,E,ob(v.y11,v.x11),ob(v.y01,v.x01),!g))):u.arc(0,0,s,x,m,g):u.lineTo(D,q)}else u.moveTo(0,0);if(u.closePath(),c)return u=null,c+""||null}return c.centroid=function(){var e=(+t.apply(this,arguments)+ +n.apply(this,arguments))/2,r=(+i.apply(this,arguments)+ +o.apply(this,arguments))/2-hb/2;return[ab(r)*e,fb(r)*e]},c.innerRadius=function(n){return arguments.length?(t="function"==typeof n?n:rb(+n),c):t},c.outerRadius=function(t){return arguments.length?(n="function"==typeof t?t:rb(+t),c):n},c.cornerRadius=function(t){return arguments.length?(e="function"==typeof t?t:rb(+t),c):e},c.padRadius=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:rb(+t),c):r},c.startAngle=function(t){return arguments.length?(i="function"==typeof t?t:rb(+t),c):i},c.endAngle=function(t){return arguments.length?(o="function"==typeof t?t:rb(+t),c):o},c.padAngle=function(t){return arguments.length?(a="function"==typeof t?t:rb(+t),c):a},c.context=function(t){return arguments.length?(u=null==t?null:t,c):u},c},t.area=Pb,t.areaRadial=Ub,t.ascending=n,t.autoType=function(t){for(var n in t){var e,r,i=t[n].trim();if(i)if("true"===i)i=!0;else if("false"===i)i=!1;else if("NaN"===i)i=NaN;else if(isNaN(e=+i)){if(!(r=i.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/)))continue;Tu&&r[4]&&!r[7]&&(i=i.replace(/-/g,"/").replace(/T/," ")),i=new Date(i)}else i=e;else i=null;t[n]=i}return t},t.axisBottom=function(t){return ht(3,t)},t.axisLeft=function(t){return ht(4,t)},t.axisRight=function(t){return ht(2,t)},t.axisTop=function(t){return ht(1,t)},t.bin=U,t.bisect=o,t.bisectCenter=u,t.bisectLeft=a,t.bisectRight=o,t.bisector=e,t.blob=function(t,n){return fetch(t,n).then(Su)},t.brush=function(){return Go(qo)},t.brushSelection=function(t){var n=t.__brush;return n?n.dim.output(n.selection):null},t.brushX=function(){return Go(zo)},t.brushY=function(){return Go(Do)},t.buffer=function(t,n){return fetch(t,n).then(Eu)},t.chord=function(){return ra(!1,!1)},t.chordDirected=function(){return ra(!0,!1)},t.chordTranspose=function(){return ra(!1,!0)},t.cluster=function(){var t=Yh,n=1,e=1,r=!1;function i(i){var o,a=0;i.eachAfter((function(n){var e=n.children;e?(n.x=function(t){return t.reduce(Lh,0)/t.length}(e),n.y=function(t){return 1+t.reduce(jh,0)}(e)):(n.x=o?a+=t(n,o):0,n.y=0,o=n)}));var u=function(t){for(var n;n=t.children;)t=n[0];return t}(i),c=function(t){for(var n;n=t.children;)t=n[n.length-1];return t}(i),f=u.x-t(u,c)/2,s=c.x+t(c,u)/2;return i.eachAfter(r?function(t){t.x=(t.x-i.x)*n,t.y=(i.y-t.y)*e}:function(t){t.x=(t.x-f)/(s-f)*n,t.y=(1-(i.y?t.y/i.y:1))*e})}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.color=de,t.contourDensity=function(){var t=Pa,n=za,e=Da,r=960,i=500,o=20,a=2,u=3*o,c=r+2*u>>a,f=i+2*u>>a,s=wa(20);function l(r){var i=new Float32Array(c*f),l=new Float32Array(c*f);r.forEach((function(r,o,s){var l=+t(r,o,s)+u>>a,h=+n(r,o,s)+u>>a,d=+e(r,o,s);l>=0&&l<c&&h>=0&&h<f&&(i[l+h*c]+=d)})),Na({width:c,height:f,data:i},{width:c,height:f,data:l},o>>a),Ca({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a),Na({width:c,height:f,data:i},{width:c,height:f,data:l},o>>a),Ca({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a),Na({width:c,height:f,data:i},{width:c,height:f,data:l},o>>a),Ca({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a);var d=s(i);if(!Array.isArray(d)){var p=B(i);d=F(0,p,d),(d=Z(0,Math.floor(p/d)*d,d)).shift()}return ka().thresholds(d).size([c,f])(i).map(h)}function h(t){return t.value*=Math.pow(2,-2*a),t.coordinates.forEach(d),t}function d(t){t.forEach(p)}function p(t){t.forEach(g)}function g(t){t[0]=t[0]*Math.pow(2,a)-u,t[1]=t[1]*Math.pow(2,a)-u}function y(){return c=r+2*(u=3*o)>>a,f=i+2*u>>a,l}return l.x=function(n){return arguments.length?(t="function"==typeof n?n:wa(+n),l):t},l.y=function(t){return arguments.length?(n="function"==typeof t?t:wa(+t),l):n},l.weight=function(t){return arguments.length?(e="function"==typeof t?t:wa(+t),l):e},l.size=function(t){if(!arguments.length)return[r,i];var n=+t[0],e=+t[1];if(!(n>=0&&e>=0))throw new Error("invalid size");return r=n,i=e,y()},l.cellSize=function(t){if(!arguments.length)return 1<<a;if(!((t=+t)>=1))throw new Error("invalid cell size");return a=Math.floor(Math.log(t)/Math.LN2),y()},l.thresholds=function(t){return arguments.length?(s="function"==typeof t?t:Array.isArray(t)?wa(ma.call(t)):wa(t),l):s},l.bandwidth=function(t){if(!arguments.length)return Math.sqrt(o*(o+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return o=Math.round((Math.sqrt(4*t*t+1)-1)/2),y()},l},t.contours=ka,t.count=c,t.create=function(t){return Dn(At(t).call(document.documentElement))},t.creator=At,t.cross=function(...t){const n="function"==typeof t[t.length-1]&&function(t){return n=>t(...n)}(t.pop()),e=(t=t.map(l)).map(f),r=t.length-1,i=new Array(r+1).fill(0),o=[];if(r<0||e.some(s))return o;for(;;){o.push(i.map(((n,e)=>t[e][n])));let a=r;for(;++i[a]===e[a];){if(0===a)return n?o.map(n):o;i[a--]=0}}},t.csv=Pu,t.csvFormat=hu,t.csvFormatBody=du,t.csvFormatRow=gu,t.csvFormatRows=pu,t.csvFormatValue=yu,t.csvParse=su,t.csvParseRows=lu,t.cubehelix=tr,t.cumsum=function(t,n){var e=0,r=0;return Float64Array.from(t,void 0===n?t=>e+=+t||0:i=>e+=+n(i,r++,t)||0)},t.curveBasis=function(t){return new dm(t)},t.curveBasisClosed=function(t){return new pm(t)},t.curveBasisOpen=function(t){return new gm(t)},t.curveBumpX=function(t){return new ym(t,!0)},t.curveBumpY=function(t){return new ym(t,!1)},t.curveBundle=_m,t.curveCardinal=xm,t.curveCardinalClosed=Mm,t.curveCardinalOpen=Tm,t.curveCatmullRom=km,t.curveCatmullRomClosed=Cm,t.curveCatmullRomOpen=zm,t.curveLinear=Eb,t.curveLinearClosed=function(t){return new Dm(t)},t.curveMonotoneX=function(t){return new Im(t)},t.curveMonotoneY=function(t){return new Um(t)},t.curveNatural=function(t){return new Ym(t)},t.curveStep=function(t){return new jm(t,.5)},t.curveStepAfter=function(t){return new jm(t,1)},t.curveStepBefore=function(t){return new jm(t,0)},t.descending=function(t,n){return n<t?-1:n>t?1:n>=t?0:NaN},t.deviation=d,t.difference=function(t,...n){t=new Set(t);for(const e of n)for(const n of e)t.delete(n);return t},t.disjoint=function(t,n){const e=n[Symbol.iterator](),r=new Set;for(const n of t){if(r.has(n))return!1;let t,i;for(;({value:t,done:i}=e.next())&&!i;){if(Object.is(n,t))return!1;r.add(t)}}return!0},t.dispatch=pt,t.drag=function(){var t,n,e,r,i=Xn,o=Gn,a=Vn,u=$n,c={},f=pt("start","drag","end"),s=0,l=0;function h(t){t.on("mousedown.drag",d).filter(u).on("touchstart.drag",y).on("touchmove.drag",v).on("touchend.drag touchcancel.drag",_).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function d(a,u){if(!r&&i.call(this,a,u)){var c=b(this,o.call(this,a,u),a,u,"mouse");c&&(Dn(a.view).on("mousemove.drag",p,!0).on("mouseup.drag",g,!0),Yn(a.view),Un(a),e=!1,t=a.clientX,n=a.clientY,c("start",a))}}function p(r){if(Bn(r),!e){var i=r.clientX-t,o=r.clientY-n;e=i*i+o*o>l}c.mouse("drag",r)}function g(t){Dn(t.view).on("mousemove.drag mouseup.drag",null),Ln(t.view,e),Bn(t),c.mouse("end",t)}function y(t,n){if(i.call(this,t,n)){var e,r,a=t.changedTouches,u=o.call(this,t,n),c=a.length;for(e=0;e<c;++e)(r=b(this,u,t,n,a[e].identifier,a[e]))&&(Un(t),r("start",t,a[e]))}}function v(t){var n,e,r=t.changedTouches,i=r.length;for(n=0;n<i;++n)(e=c[r[n].identifier])&&(Bn(t),e("drag",t,r[n]))}function _(t){var n,e,i=t.changedTouches,o=i.length;for(r&&clearTimeout(r),r=setTimeout((function(){r=null}),500),n=0;n<o;++n)(e=c[i[n].identifier])&&(Un(t),e("end",t,i[n]))}function b(t,n,e,r,i,o){var u,l,d,p=f.copy(),g=In(o||e,n);if(null!=(d=a.call(t,new Hn("beforestart",{sourceEvent:e,target:h,identifier:i,active:s,x:g[0],y:g[1],dx:0,dy:0,dispatch:p}),r)))return u=d.x-g[0]||0,l=d.y-g[1]||0,function e(o,a,f){var y,v=g;switch(o){case"start":c[i]=e,y=s++;break;case"end":delete c[i],--s;case"drag":g=In(f||a,n),y=s}p.call(o,t,new Hn(o,{sourceEvent:a,subject:d,target:h,identifier:i,active:y,x:g[0]+u,y:g[1]+l,dx:g[0]-v[0],dy:g[1]-v[1],dispatch:p}),r)}}return h.filter=function(t){return arguments.length?(i="function"==typeof t?t:jn(!!t),h):i},h.container=function(t){return arguments.length?(o="function"==typeof t?t:jn(t),h):o},h.subject=function(t){return arguments.length?(a="function"==typeof t?t:jn(t),h):a},h.touchable=function(t){return arguments.length?(u="function"==typeof t?t:jn(!!t),h):u},h.on=function(){var t=f.on.apply(f,arguments);return t===f?h:t},h.clickDistance=function(t){return arguments.length?(l=(t=+t)*t,h):Math.sqrt(l)},h},t.dragDisable=Yn,t.dragEnable=Ln,t.dsv=function(t,n,e,r){3===arguments.length&&"function"==typeof e&&(r=e,e=void 0);var i=cu(t);return Nu(n,e).then((function(t){return i.parse(t,r)}))},t.dsvFormat=cu,t.easeBack=so,t.easeBackIn=co,t.easeBackInOut=so,t.easeBackOut=fo,t.easeBounce=ao,t.easeBounceIn=function(t){return 1-ao(1-t)},t.easeBounceInOut=function(t){return((t*=2)<=1?1-ao(1-t):ao(t-1)+1)/2},t.easeBounceOut=ao,t.easeCircle=ro,t.easeCircleIn=function(t){return 1-Math.sqrt(1-t*t)},t.easeCircleInOut=ro,t.easeCircleOut=function(t){return Math.sqrt(1- --t*t)},t.easeCubic=$i,t.easeCubicIn=function(t){return t*t*t},t.easeCubicInOut=$i,t.easeCubicOut=function(t){return--t*t*t+1},t.easeElastic=po,t.easeElasticIn=ho,t.easeElasticInOut=go,t.easeElasticOut=po,t.easeExp=eo,t.easeExpIn=function(t){return no(1-+t)},t.easeExpInOut=eo,t.easeExpOut=function(t){return 1-no(t)},t.easeLinear=t=>+t,t.easePoly=Ki,t.easePolyIn=Wi,t.easePolyInOut=Ki,t.easePolyOut=Zi,t.easeQuad=Vi,t.easeQuadIn=function(t){return t*t},t.easeQuadInOut=Vi,t.easeQuadOut=function(t){return t*(2-t)},t.easeSin=to,t.easeSinIn=function(t){return 1==+t?1:1-Math.cos(t*Ji)},t.easeSinInOut=to,t.easeSinOut=function(t){return Math.sin(t*Ji)},t.every=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");let e=-1;for(const r of t)if(!n(r,++e,t))return!1;return!0},t.extent=p,t.fcumsum=function(t,n){const e=new g;let r=-1;return Float64Array.from(t,void 0===n?t=>e.add(+t||0):i=>e.add(+n(i,++r,t)||0))},t.filter=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");const e=[];let r=-1;for(const i of t)n(i,++r,t)&&e.push(i);return e},t.forceCenter=function(t,n){var e,r=1;function i(){var i,o,a=e.length,u=0,c=0;for(i=0;i<a;++i)u+=(o=e[i]).x,c+=o.y;for(u=(u/a-t)*r,c=(c/a-n)*r,i=0;i<a;++i)(o=e[i]).x-=u,o.y-=c}return null==t&&(t=0),null==n&&(n=0),i.initialize=function(t){e=t},i.x=function(n){return arguments.length?(t=+n,i):t},i.y=function(t){return arguments.length?(n=+t,i):n},i.strength=function(t){return arguments.length?(r=+t,i):r},i},t.forceCollide=function(t){var n,e,r,i=1,o=1;function a(){for(var t,a,c,f,s,l,h,d=n.length,p=0;p<o;++p)for(a=Lu(n,$u,Wu).visitAfter(u),t=0;t<d;++t)c=n[t],l=e[c.index],h=l*l,f=c.x+c.vx,s=c.y+c.vy,a.visit(g);function g(t,n,e,o,a){var u=t.data,d=t.r,p=l+d;if(!u)return n>f+p||o<f-p||e>s+p||a<s-p;if(u.index>c.index){var g=f-u.x-u.vx,y=s-u.y-u.vy,v=g*g+y*y;v<p*p&&(0===g&&(v+=(g=Vu(r))*g),0===y&&(v+=(y=Vu(r))*y),v=(p-(v=Math.sqrt(v)))/v*i,c.vx+=(g*=v)*(p=(d*=d)/(h+d)),c.vy+=(y*=v)*p,u.vx-=g*(p=1-p),u.vy-=y*p)}}}function u(t){if(t.data)return t.r=e[t.data.index];for(var n=t.r=0;n<4;++n)t[n]&&t[n].r>t.r&&(t.r=t[n].r)}function c(){if(n){var r,i,o=n.length;for(e=new Array(o),r=0;r<o;++r)i=n[r],e[i.index]=+t(i,r,n)}}return"function"!=typeof t&&(t=Gu(null==t?1:+t)),a.initialize=function(t,e){n=t,r=e,c()},a.iterations=function(t){return arguments.length?(o=+t,a):o},a.strength=function(t){return arguments.length?(i=+t,a):i},a.radius=function(n){return arguments.length?(t="function"==typeof n?n:Gu(+n),c(),a):t},a},t.forceLink=function(t){var n,e,r,i,o,a,u=Zu,c=function(t){return 1/Math.min(i[t.source.index],i[t.target.index])},f=Gu(30),s=1;function l(r){for(var i=0,u=t.length;i<s;++i)for(var c,f,l,h,d,p,g,y=0;y<u;++y)f=(c=t[y]).source,h=(l=c.target).x+l.vx-f.x-f.vx||Vu(a),d=l.y+l.vy-f.y-f.vy||Vu(a),h*=p=((p=Math.sqrt(h*h+d*d))-e[y])/p*r*n[y],d*=p,l.vx-=h*(g=o[y]),l.vy-=d*g,f.vx+=h*(g=1-g),f.vy+=d*g}function h(){if(r){var a,c,f=r.length,s=t.length,l=new Map(r.map(((t,n)=>[u(t,n,r),t])));for(a=0,i=new Array(f);a<s;++a)(c=t[a]).index=a,"object"!=typeof c.source&&(c.source=Ku(l,c.source)),"object"!=typeof c.target&&(c.target=Ku(l,c.target)),i[c.source.index]=(i[c.source.index]||0)+1,i[c.target.index]=(i[c.target.index]||0)+1;for(a=0,o=new Array(s);a<s;++a)c=t[a],o[a]=i[c.source.index]/(i[c.source.index]+i[c.target.index]);n=new Array(s),d(),e=new Array(s),p()}}function d(){if(r)for(var e=0,i=t.length;e<i;++e)n[e]=+c(t[e],e,t)}function p(){if(r)for(var n=0,i=t.length;n<i;++n)e[n]=+f(t[n],n,t)}return null==t&&(t=[]),l.initialize=function(t,n){r=t,a=n,h()},l.links=function(n){return arguments.length?(t=n,h(),l):t},l.id=function(t){return arguments.length?(u=t,l):u},l.iterations=function(t){return arguments.length?(s=+t,l):s},l.strength=function(t){return arguments.length?(c="function"==typeof t?t:Gu(+t),d(),l):c},l.distance=function(t){return arguments.length?(f="function"==typeof t?t:Gu(+t),p(),l):f},l},t.forceManyBody=function(){var t,n,e,r,i,o=Gu(-30),a=1,u=1/0,c=.81;function f(e){var i,o=t.length,a=Lu(t,Ju,tc).visitAfter(l);for(r=e,i=0;i<o;++i)n=t[i],a.visit(h)}function s(){if(t){var n,e,r=t.length;for(i=new Array(r),n=0;n<r;++n)e=t[n],i[e.index]=+o(e,n,t)}}function l(t){var n,e,r,o,a,u=0,c=0;if(t.length){for(r=o=a=0;a<4;++a)(n=t[a])&&(e=Math.abs(n.value))&&(u+=n.value,c+=e,r+=e*n.x,o+=e*n.y);t.x=r/c,t.y=o/c}else{(n=t).x=n.data.x,n.y=n.data.y;do{u+=i[n.data.index]}while(n=n.next)}t.value=u}function h(t,o,f,s){if(!t.value)return!0;var l=t.x-n.x,h=t.y-n.y,d=s-o,p=l*l+h*h;if(d*d/c<p)return p<u&&(0===l&&(p+=(l=Vu(e))*l),0===h&&(p+=(h=Vu(e))*h),p<a&&(p=Math.sqrt(a*p)),n.vx+=l*t.value*r/p,n.vy+=h*t.value*r/p),!0;if(!(t.length||p>=u)){(t.data!==n||t.next)&&(0===l&&(p+=(l=Vu(e))*l),0===h&&(p+=(h=Vu(e))*h),p<a&&(p=Math.sqrt(a*p)));do{t.data!==n&&(d=i[t.data.index]*r/p,n.vx+=l*d,n.vy+=h*d)}while(t=t.next)}}return f.initialize=function(n,r){t=n,e=r,s()},f.strength=function(t){return arguments.length?(o="function"==typeof t?t:Gu(+t),s(),f):o},f.distanceMin=function(t){return arguments.length?(a=t*t,f):Math.sqrt(a)},f.distanceMax=function(t){return arguments.length?(u=t*t,f):Math.sqrt(u)},f.theta=function(t){return arguments.length?(c=t*t,f):Math.sqrt(c)},f},t.forceRadial=function(t,n,e){var r,i,o,a=Gu(.1);function u(t){for(var a=0,u=r.length;a<u;++a){var c=r[a],f=c.x-n||1e-6,s=c.y-e||1e-6,l=Math.sqrt(f*f+s*s),h=(o[a]-l)*i[a]*t/l;c.vx+=f*h,c.vy+=s*h}}function c(){if(r){var n,e=r.length;for(i=new Array(e),o=new Array(e),n=0;n<e;++n)o[n]=+t(r[n],n,r),i[n]=isNaN(o[n])?0:+a(r[n],n,r)}}return"function"!=typeof t&&(t=Gu(+t)),null==n&&(n=0),null==e&&(e=0),u.initialize=function(t){r=t,c()},u.strength=function(t){return arguments.length?(a="function"==typeof t?t:Gu(+t),c(),u):a},u.radius=function(n){return arguments.length?(t="function"==typeof n?n:Gu(+n),c(),u):t},u.x=function(t){return arguments.length?(n=+t,u):n},u.y=function(t){return arguments.length?(e=+t,u):e},u},t.forceSimulation=function(t){var n,e=1,r=.001,i=1-Math.pow(r,1/300),o=0,a=.6,u=new Map,c=ri(l),f=pt("tick","end"),s=function(){let t=1;return()=>(t=(1664525*t+1013904223)%Qu)/Qu}();function l(){h(),f.call("tick",n),e<r&&(c.stop(),f.call("end",n))}function h(r){var c,f,s=t.length;void 0===r&&(r=1);for(var l=0;l<r;++l)for(e+=(o-e)*i,u.forEach((function(t){t(e)})),c=0;c<s;++c)null==(f=t[c]).fx?f.x+=f.vx*=a:(f.x=f.fx,f.vx=0),null==f.fy?f.y+=f.vy*=a:(f.y=f.fy,f.vy=0);return n}function d(){for(var n,e=0,r=t.length;e<r;++e){if((n=t[e]).index=e,null!=n.fx&&(n.x=n.fx),null!=n.fy&&(n.y=n.fy),isNaN(n.x)||isNaN(n.y)){var i=10*Math.sqrt(.5+e),o=e*nc;n.x=i*Math.cos(o),n.y=i*Math.sin(o)}(isNaN(n.vx)||isNaN(n.vy))&&(n.vx=n.vy=0)}}function p(n){return n.initialize&&n.initialize(t,s),n}return null==t&&(t=[]),d(),n={tick:h,restart:function(){return c.restart(l),n},stop:function(){return c.stop(),n},nodes:function(e){return arguments.length?(t=e,d(),u.forEach(p),n):t},alpha:function(t){return arguments.length?(e=+t,n):e},alphaMin:function(t){return arguments.length?(r=+t,n):r},alphaDecay:function(t){return arguments.length?(i=+t,n):+i},alphaTarget:function(t){return arguments.length?(o=+t,n):o},velocityDecay:function(t){return arguments.length?(a=1-t,n):1-a},randomSource:function(t){return arguments.length?(s=t,u.forEach(p),n):s},force:function(t,e){return arguments.length>1?(null==e?u.delete(t):u.set(t,p(e)),n):u.get(t)},find:function(n,e,r){var i,o,a,u,c,f=0,s=t.length;for(null==r?r=1/0:r*=r,f=0;f<s;++f)(a=(i=n-(u=t[f]).x)*i+(o=e-u.y)*o)<r&&(c=u,r=a);return c},on:function(t,e){return arguments.length>1?(f.on(t,e),n):f.on(t)}}},t.forceX=function(t){var n,e,r,i=Gu(.1);function o(t){for(var i,o=0,a=n.length;o<a;++o)(i=n[o]).vx+=(r[o]-i.x)*e[o]*t}function a(){if(n){var o,a=n.length;for(e=new Array(a),r=new Array(a),o=0;o<a;++o)e[o]=isNaN(r[o]=+t(n[o],o,n))?0:+i(n[o],o,n)}}return"function"!=typeof t&&(t=Gu(null==t?0:+t)),o.initialize=function(t){n=t,a()},o.strength=function(t){return arguments.length?(i="function"==typeof t?t:Gu(+t),a(),o):i},o.x=function(n){return arguments.length?(t="function"==typeof n?n:Gu(+n),a(),o):t},o},t.forceY=function(t){var n,e,r,i=Gu(.1);function o(t){for(var i,o=0,a=n.length;o<a;++o)(i=n[o]).vy+=(r[o]-i.y)*e[o]*t}function a(){if(n){var o,a=n.length;for(e=new Array(a),r=new Array(a),o=0;o<a;++o)e[o]=isNaN(r[o]=+t(n[o],o,n))?0:+i(n[o],o,n)}}return"function"!=typeof t&&(t=Gu(null==t?0:+t)),o.initialize=function(t){n=t,a()},o.strength=function(t){return arguments.length?(i="function"==typeof t?t:Gu(+t),a(),o):i},o.y=function(n){return arguments.length?(t="function"==typeof n?n:Gu(+n),a(),o):t},o},t.formatDefaultLocale=gc,t.formatLocale=pc,t.formatSpecifier=ac,t.fsum=function(t,n){const e=new g;if(void 0===n)for(let n of t)(n=+n)&&e.add(n);else{let r=-1;for(let i of t)(i=+n(i,++r,t))&&e.add(i)}return+e},t.geoAlbers=bh,t.geoAlbersUsa=function(){var t,n,e,r,i,o,a=bh(),u=_h().rotate([154,0]).center([-2,58.5]).parallels([55,65]),c=_h().rotate([157,0]).center([-3,19.9]).parallels([8,18]),f={point:function(t,n){o=[t,n]}};function s(t){var n=t[0],a=t[1];return o=null,e.point(n,a),o||(r.point(n,a),o)||(i.point(n,a),o)}function l(){return t=n=null,s}return s.invert=function(t){var n=a.scale(),e=a.translate(),r=(t[0]-e[0])/n,i=(t[1]-e[1])/n;return(i>=.12&&i<.234&&r>=-.425&&r<-.214?u:i>=.166&&i<.234&&r>=-.214&&r<-.115?c:a).invert(t)},s.stream=function(e){return t&&n===e?t:(r=[a.stream(n=e),u.stream(e),c.stream(e)],i=r.length,t={point:function(t,n){for(var e=-1;++e<i;)r[e].point(t,n)},sphere:function(){for(var t=-1;++t<i;)r[t].sphere()},lineStart:function(){for(var t=-1;++t<i;)r[t].lineStart()},lineEnd:function(){for(var t=-1;++t<i;)r[t].lineEnd()},polygonStart:function(){for(var t=-1;++t<i;)r[t].polygonStart()},polygonEnd:function(){for(var t=-1;++t<i;)r[t].polygonEnd()}});var r,i},s.precision=function(t){return arguments.length?(a.precision(t),u.precision(t),c.precision(t),l()):a.precision()},s.scale=function(t){return arguments.length?(a.scale(t),u.scale(.35*t),c.scale(t),s.translate(a.translate())):a.scale()},s.translate=function(t){if(!arguments.length)return a.translate();var n=a.scale(),o=+t[0],s=+t[1];return e=a.translate(t).clipExtent([[o-.455*n,s-.238*n],[o+.455*n,s+.238*n]]).stream(f),r=u.translate([o-.307*n,s+.201*n]).clipExtent([[o-.425*n+bc,s+.12*n+bc],[o-.214*n-bc,s+.234*n-bc]]).stream(f),i=c.translate([o-.205*n,s+.212*n]).clipExtent([[o-.214*n+bc,s+.166*n+bc],[o-.115*n-bc,s+.234*n-bc]]).stream(f),l()},s.fitExtent=function(t,n){return ah(s,t,n)},s.fitSize=function(t,n){return uh(s,t,n)},s.fitWidth=function(t,n){return ch(s,t,n)},s.fitHeight=function(t,n){return fh(s,t,n)},s.scale(1070)},t.geoArea=function(t){return pf=new g,Wc(t,gf),2*pf},t.geoAzimuthalEqualArea=function(){return ph(wh).scale(124.75).clipAngle(179.999)},t.geoAzimuthalEqualAreaRaw=wh,t.geoAzimuthalEquidistant=function(){return ph(Mh).scale(79.4188).clipAngle(179.999)},t.geoAzimuthalEquidistantRaw=Mh,t.geoBounds=function(t){var n,e,r,i,o,a,u;if(of=rf=-(nf=ef=1/0),lf=[],Wc(t,jf),e=lf.length){for(lf.sort(Qf),n=1,o=[r=lf[0]];n<e;++n)Jf(r,(i=lf[n])[0])||Jf(r,i[1])?(Kf(r[0],i[1])>Kf(r[0],r[1])&&(r[1]=i[1]),Kf(i[0],r[1])>Kf(r[0],r[1])&&(r[0]=i[0])):o.push(r=i);for(a=-1/0,n=0,r=o[e=o.length-1];n<=e;r=i,++n)i=o[n],(u=Kf(r[1],i[0]))>a&&(a=u,nf=i[0],rf=r[1])}return lf=hf=null,nf===1/0||ef===1/0?[[NaN,NaN],[NaN,NaN]]:[[nf,ef],[rf,of]]},t.geoCentroid=function(t){Ef=kf=Nf=Cf=Pf=zf=Df=qf=0,Rf=new g,Ff=new g,Of=new g,Wc(t,ts);var n=+Rf,e=+Ff,r=+Of,i=Dc(n,e,r);return i<mc&&(n=zf,e=Df,r=qf,kf<bc&&(n=Nf,e=Cf,r=Pf),(i=Dc(n,e,r))<mc)?[NaN,NaN]:[Nc(e,n)*Tc,Yc(r/i)*Tc]},t.geoCircle=function(){var t,n,e=ls([0,0]),r=ls(90),i=ls(6),o={point:function(e,r){t.push(e=n(e,r)),e[0]*=Tc,e[1]*=Tc}};function a(){var a=e.apply(this,arguments),u=r.apply(this,arguments)*Sc,c=i.apply(this,arguments)*Sc;return t=[],n=ps(-a[0]*Sc,-a[1]*Sc,0).invert,bs(o,u,c,1),a={type:"Polygon",coordinates:[t]},t=n=null,a}return a.center=function(t){return arguments.length?(e="function"==typeof t?t:ls([+t[0],+t[1]]),a):e},a.radius=function(t){return arguments.length?(r="function"==typeof t?t:ls(+t),a):r},a.precision=function(t){return arguments.length?(i="function"==typeof t?t:ls(+t),a):i},a},t.geoClipAntimeridian=Ps,t.geoClipCircle=zs,t.geoClipExtent=function(){var t,n,e,r=0,i=0,o=960,a=500;return e={stream:function(e){return t&&n===e?t:t=Us(r,i,o,a)(n=e)},extent:function(u){return arguments.length?(r=+u[0][0],i=+u[0][1],o=+u[1][0],a=+u[1][1],t=n=null,e):[[r,i],[o,a]]}}},t.geoClipRectangle=Us,t.geoConicConformal=function(){return yh(Eh).scale(109.5).parallels([30,30])},t.geoConicConformalRaw=Eh,t.geoConicEqualArea=_h,t.geoConicEqualAreaRaw=vh,t.geoConicEquidistant=function(){return yh(Nh).scale(131.154).center([0,13.9389])},t.geoConicEquidistantRaw=Nh,t.geoContains=function(t,n){return(t&&$s.hasOwnProperty(t.type)?$s[t.type]:Zs)(t,n)},t.geoDistance=Vs,t.geoEqualEarth=function(){return ph(Rh).scale(177.158)},t.geoEqualEarthRaw=Rh,t.geoEquirectangular=function(){return ph(kh).scale(152.63)},t.geoEquirectangularRaw=kh,t.geoGnomonic=function(){return ph(Fh).scale(144.049).clipAngle(60)},t.geoGnomonicRaw=Fh,t.geoGraticule=il,t.geoGraticule10=function(){return il()()},t.geoIdentity=function(){var t,n,e,r,i,o,a,u=1,c=0,f=0,s=1,l=1,h=0,d=null,p=1,g=1,y=rh({point:function(t,n){var e=b([t,n]);this.stream.point(e[0],e[1])}}),v=fl;function _(){return p=u*s,g=u*l,o=a=null,b}function b(e){var r=e[0]*p,i=e[1]*g;if(h){var o=i*t-r*n;r=r*t+i*n,i=o}return[r+c,i+f]}return b.invert=function(e){var r=e[0]-c,i=e[1]-f;if(h){var o=i*t+r*n;r=r*t-i*n,i=o}return[r/p,i/g]},b.stream=function(t){return o&&a===t?o:o=y(v(a=t))},b.postclip=function(t){return arguments.length?(v=t,d=e=r=i=null,_()):v},b.clipExtent=function(t){return arguments.length?(v=null==t?(d=e=r=i=null,fl):Us(d=+t[0][0],e=+t[0][1],r=+t[1][0],i=+t[1][1]),_()):null==d?null:[[d,e],[r,i]]},b.scale=function(t){return arguments.length?(u=+t,_()):u},b.translate=function(t){return arguments.length?(c=+t[0],f=+t[1],_()):[c,f]},b.angle=function(e){return arguments.length?(n=Fc(h=e%360*Sc),t=Cc(h),_()):h*Tc},b.reflectX=function(t){return arguments.length?(s=t?-1:1,_()):s<0},b.reflectY=function(t){return arguments.length?(l=t?-1:1,_()):l<0},b.fitExtent=function(t,n){return ah(b,t,n)},b.fitSize=function(t,n){return uh(b,t,n)},b.fitWidth=function(t,n){return ch(b,t,n)},b.fitHeight=function(t,n){return fh(b,t,n)},b},t.geoInterpolate=function(t,n){var e=t[0]*Sc,r=t[1]*Sc,i=n[0]*Sc,o=n[1]*Sc,a=Cc(r),u=Fc(r),c=Cc(o),f=Fc(o),s=a*Cc(e),l=a*Fc(e),h=c*Cc(i),d=c*Fc(i),p=2*Yc(Ic(Lc(o-r)+a*c*Lc(i-e))),g=Fc(p),y=p?function(t){var n=Fc(t*=p)/g,e=Fc(p-t)/g,r=e*s+n*h,i=e*l+n*d,o=e*u+n*f;return[Nc(i,r)*Tc,Nc(o,Ic(r*r+i*i))*Tc]}:function(){return[e*Tc,r*Tc]};return y.distance=p,y},t.geoLength=Hs,t.geoMercator=function(){return Th(Ah).scale(961/Ac)},t.geoMercatorRaw=Ah,t.geoNaturalEarth1=function(){return ph(Oh).scale(175.295)},t.geoNaturalEarth1Raw=Oh,t.geoOrthographic=function(){return ph(Ih).scale(249.5).clipAngle(90.000001)},t.geoOrthographicRaw=Ih,t.geoPath=function(t,n){var e,r,i=4.5;function o(t){return t&&("function"==typeof i&&r.pointRadius(+i.apply(this,arguments)),Wc(t,e(r))),r.result()}return o.area=function(t){return Wc(t,e(hl)),hl.result()},o.measure=function(t){return Wc(t,e(Ql)),Ql.result()},o.bounds=function(t){return Wc(t,e(xl)),xl.result()},o.centroid=function(t){return Wc(t,e(Rl)),Rl.result()},o.projection=function(n){return arguments.length?(e=null==n?(t=null,fl):(t=n).stream,o):t},o.context=function(t){return arguments.length?(r=null==t?(n=null,new nh):new Xl(n=t),"function"!=typeof i&&r.pointRadius(i),o):n},o.pointRadius=function(t){return arguments.length?(i="function"==typeof t?t:(r.pointRadius(+t),+t),o):i},o.projection(t).context(n)},t.geoProjection=ph,t.geoProjectionMutator=gh,t.geoRotation=_s,t.geoStereographic=function(){return ph(Uh).scale(250).clipAngle(142)},t.geoStereographicRaw=Uh,t.geoStream=Wc,t.geoTransform=function(t){return{stream:rh(t)}},t.geoTransverseMercator=function(){var t=Th(Bh),n=t.center,e=t.rotate;return t.center=function(t){return arguments.length?n([-t[1],t[0]]):[(t=n())[1],-t[0]]},t.rotate=function(t){return arguments.length?e([t[0],t[1],t.length>2?t[2]+90:90]):[(t=e())[0],t[1],t[2]-90]},e([0,0,90]).scale(159.155)},t.geoTransverseMercatorRaw=Bh,t.gray=function(t,n){return new Fe(t,0,0,null==n?1:n)},t.greatest=function(t,e=n){let r,i=!1;if(1===e.length){let o;for(const a of t){const t=e(a);(i?n(t,o)>0:0===n(t,t))&&(r=a,o=t,i=!0)}}else for(const n of t)(i?e(n,r)>0:0===e(n,n))&&(r=n,i=!0);return r},t.greatestIndex=function(t,e=n){if(1===e.length)return G(t,e);let r,i=-1,o=-1;for(const n of t)++o,(i<0?0===e(n,n):e(n,r)>0)&&(r=n,i=o);return i},t.group=M,t.groupSort=function(t,e,r){return(1===e.length?k(A(t,e,r),(([t,e],[r,i])=>n(e,i)||n(t,r))):k(M(t,r),(([t,r],[i,o])=>e(r,o)||n(t,i)))).map((([t])=>t))},t.groups=function(t,...n){return S(t,Array.from,w,n)},t.hcl=Le,t.hierarchy=Xh,t.histogram=U,t.hsl=Ae,t.html=Fu,t.image=function(t,n){return new Promise((function(e,r){var i=new Image;for(var o in n)i[o]=n[o];i.onerror=r,i.onload=function(){e(i)},i.src=t}))},t.index=function(t,...n){return S(t,w,T,n)},t.indexes=function(t,...n){return S(t,Array.from,T,n)},t.interpolate=Mr,t.interpolateArray=function(t,n){return(gr(n)?pr:yr)(t,n)},t.interpolateBasis=rr,t.interpolateBasisClosed=ir,t.interpolateBlues=q_,t.interpolateBrBG=Gv,t.interpolateBuGn=s_,t.interpolateBuPu=h_,t.interpolateCividis=function(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-t*(35.34-t*(2381.73-t*(6402.7-t*(7024.72-2710.57*t)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+t*(170.73+t*(52.82-t*(131.46-t*(176.58-67.37*t)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+t*(442.36-t*(2482.43-t*(6167.24-t*(6614.94-2475.67*t)))))))+")"},t.interpolateCool=V_,t.interpolateCubehelix=Yr,t.interpolateCubehelixDefault=X_,t.interpolateCubehelixLong=Lr,t.interpolateDate=vr,t.interpolateDiscrete=function(t){var n=t.length;return function(e){return t[Math.max(0,Math.min(n-1,Math.floor(e*n)))]}},t.interpolateGnBu=p_,t.interpolateGreens=F_,t.interpolateGreys=I_,t.interpolateHcl=Ir,t.interpolateHclLong=Ur,t.interpolateHsl=Rr,t.interpolateHslLong=Fr,t.interpolateHue=function(t,n){var e=ur(+t,+n);return function(t){var n=e(t);return n-360*Math.floor(n/360)}},t.interpolateInferno=nb,t.interpolateLab=function(t,n){var e=fr((t=Re(t)).l,(n=Re(n)).l),r=fr(t.a,n.a),i=fr(t.b,n.b),o=fr(t.opacity,n.opacity);return function(n){return t.l=e(n),t.a=r(n),t.b=i(n),t.opacity=o(n),t+""}},t.interpolateMagma=tb,t.interpolateNumber=_r,t.interpolateNumberArray=pr,t.interpolateObject=br,t.interpolateOrRd=y_,t.interpolateOranges=H_,t.interpolatePRGn=$v,t.interpolatePiYG=Zv,t.interpolatePlasma=eb,t.interpolatePuBu=m_,t.interpolatePuBuGn=__,t.interpolatePuOr=Qv,t.interpolatePuRd=w_,t.interpolatePurples=B_,t.interpolateRainbow=function(t){(t<0||t>1)&&(t-=Math.floor(t));var n=Math.abs(t-.5);return $_.h=360*t-100,$_.s=1.5-1.5*n,$_.l=.8-.9*n,$_+""},t.interpolateRdBu=t_,t.interpolateRdGy=e_,t.interpolateRdPu=A_,t.interpolateRdYlBu=i_,t.interpolateRdYlGn=a_,t.interpolateReds=L_,t.interpolateRgb=sr,t.interpolateRgbBasis=hr,t.interpolateRgbBasisClosed=dr,t.interpolateRound=Ar,t.interpolateSinebow=function(t){var n;return t=(.5-t)*Math.PI,W_.r=255*(n=Math.sin(t))*n,W_.g=255*(n=Math.sin(t+Z_))*n,W_.b=255*(n=Math.sin(t+K_))*n,W_+""},t.interpolateSpectral=c_,t.interpolateString=wr,t.interpolateTransformCss=Cr,t.interpolateTransformSvg=Pr,t.interpolateTurbo=function(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"},t.interpolateViridis=J_,t.interpolateWarm=G_,t.interpolateYlGn=k_,t.interpolateYlGnBu=S_,t.interpolateYlOrBr=C_,t.interpolateYlOrRd=z_,t.interpolateZoom=Dr,t.interrupt=gi,t.intersection=function(t,...n){t=new Set(t),n=n.map(et);t:for(const e of t)for(const r of n)if(!r.has(e)){t.delete(e);continue t}return t},t.interval=function(t,n,e){var r=new ei,i=n;return null==n?(r.restart(t,n,e),r):(r._restart=r.restart,r.restart=function(t,n,e){n=+n,e=null==e?ti():+e,r._restart((function o(a){a+=i,r._restart(o,i+=n,e),t(a)}),n,e)},r.restart(t,n,e),r)},t.isoFormat=Mv,t.isoParse=Av,t.json=function(t,n){return fetch(t,n).then(Du)},t.lab=Re,t.lch=function(t,n,e,r){return 1===arguments.length?Ye(t):new je(e,n,t,null==r?1:r)},t.least=function(t,e=n){let r,i=!1;if(1===e.length){let o;for(const a of t){const t=e(a);(i?n(t,o)<0:0===n(t,t))&&(r=a,o=t,i=!0)}}else for(const n of t)(i?e(n,r)<0:0===e(n,n))&&(r=n,i=!0);return r},t.leastIndex=K,t.line=Cb,t.lineRadial=Ib,t.linkHorizontal=function(){return jb(Hb)},t.linkRadial=function(){var t=jb(Gb);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t},t.linkVertical=function(){return jb(Xb)},t.local=Rn,t.map=function(t,n){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");if("function"!=typeof n)throw new TypeError("mapper is not a function");return Array.from(t,((e,r)=>n(e,r,t)))},t.matcher=Ct,t.max=B,t.maxIndex=G,t.mean=function(t,n){let e=0,r=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(++e,r+=n);else{let i=-1;for(let o of t)null!=(o=n(o,++i,t))&&(o=+o)>=o&&(++e,r+=o)}if(e)return r/e},t.median=function(t,n){return H(t,.5,n)},t.merge=V,t.min=Y,t.minIndex=$,t.namespace=xt,t.namespaces=mt,t.nice=O,t.now=ti,t.pack=function(){var t=null,n=1,e=1,r=hd;function i(i){return i.x=n/2,i.y=e/2,t?i.eachBefore(gd(t)).eachAfter(yd(r,.5)).eachBefore(vd(1)):i.eachBefore(gd(pd)).eachAfter(yd(hd,1)).eachAfter(yd(r,i.r/Math.min(n,e))).eachBefore(vd(Math.min(n,e)/(2*i.r))),i}return i.radius=function(n){return arguments.length?(t=sd(n),i):t},i.size=function(t){return arguments.length?(n=+t[0],e=+t[1],i):[n,e]},i.padding=function(t){return arguments.length?(r="function"==typeof t?t:dd(+t),i):r},i},t.packEnclose=Kh,t.packSiblings=function(t){return fd(t),t},t.pairs=function(t,n=W){const e=[];let r,i=!1;for(const o of t)i&&e.push(n(r,o)),r=o,i=!0;return e},t.partition=function(){var t=1,n=1,e=0,r=!1;function i(i){var o=i.height+1;return i.x0=i.y0=e,i.x1=t,i.y1=n/o,i.eachBefore(function(t,n){return function(r){r.children&&bd(r,r.x0,t*(r.depth+1)/n,r.x1,t*(r.depth+2)/n);var i=r.x0,o=r.y0,a=r.x1-e,u=r.y1-e;a<i&&(i=a=(i+a)/2),u<o&&(o=u=(o+u)/2),r.x0=i,r.y0=o,r.x1=a,r.y1=u}}(n,o)),r&&i.eachBefore(_d),i}return i.round=function(t){return arguments.length?(r=!!t,i):r},i.size=function(e){return arguments.length?(t=+e[0],n=+e[1],i):[t,n]},i.padding=function(t){return arguments.length?(e=+t,i):e},i},t.path=fa,t.permute=E,t.pie=function(){var t=Db,n=zb,e=null,r=rb(0),i=rb(pb),o=rb(0);function a(a){var u,c,f,s,l,h=(a=Tb(a)).length,d=0,p=new Array(h),g=new Array(h),y=+r.apply(this,arguments),v=Math.min(pb,Math.max(-pb,i.apply(this,arguments)-y)),_=Math.min(Math.abs(v)/h,o.apply(this,arguments)),b=_*(v<0?-1:1);for(u=0;u<h;++u)(l=g[p[u]=u]=+t(a[u],u,a))>0&&(d+=l);for(null!=n?p.sort((function(t,e){return n(g[t],g[e])})):null!=e&&p.sort((function(t,n){return e(a[t],a[n])})),u=0,f=d?(v-h*b)/d:0;u<h;++u,y=s)c=p[u],s=y+((l=g[c])>0?l*f:0)+b,g[c]={data:a[c],index:u,value:l,startAngle:y,endAngle:s,padAngle:_};return g}return a.value=function(n){return arguments.length?(t="function"==typeof n?n:rb(+n),a):t},a.sortValues=function(t){return arguments.length?(n=t,e=null,a):n},a.sort=function(t){return arguments.length?(e=t,n=null,a):e},a.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:rb(+t),a):r},a.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:rb(+t),a):i},a.padAngle=function(t){return arguments.length?(o="function"==typeof t?t:rb(+t),a):o},a},t.piecewise=jr,t.pointRadial=Bb,t.pointer=In,t.pointers=function(t,n){return t.target&&(t=On(t),void 0===n&&(n=t.currentTarget),t=t.touches||[t]),Array.from(t,(t=>In(t,n)))},t.polygonArea=function(t){for(var n,e=-1,r=t.length,i=t[r-1],o=0;++e<r;)n=i,i=t[e],o+=n[1]*i[0]-n[0]*i[1];return o/2},t.polygonCentroid=function(t){for(var n,e,r=-1,i=t.length,o=0,a=0,u=t[i-1],c=0;++r<i;)n=u,u=t[r],c+=e=n[0]*u[1]-u[0]*n[1],o+=(n[0]+u[0])*e,a+=(n[1]+u[1])*e;return[o/(c*=3),a/c]},t.polygonContains=function(t,n){for(var e,r,i=t.length,o=t[i-1],a=n[0],u=n[1],c=o[0],f=o[1],s=!1,l=0;l<i;++l)e=(o=t[l])[0],(r=o[1])>u!=f>u&&a<(c-e)*(u-r)/(f-r)+e&&(s=!s),c=e,f=r;return s},t.polygonHull=function(t){if((e=t.length)<3)return null;var n,e,r=new Array(e),i=new Array(e);for(n=0;n<e;++n)r[n]=[+t[n][0],+t[n][1],n];for(r.sort(Fd),n=0;n<e;++n)i[n]=[r[n][0],-r[n][1]];var o=Od(r),a=Od(i),u=a[0]===o[0],c=a[a.length-1]===o[o.length-1],f=[];for(n=o.length-1;n>=0;--n)f.push(t[r[o[n]][2]]);for(n=+u;n<a.length-c;++n)f.push(t[r[a[n]][2]]);return f},t.polygonLength=function(t){for(var n,e,r=-1,i=t.length,o=t[i-1],a=o[0],u=o[1],c=0;++r<i;)n=a,e=u,n-=a=(o=t[r])[0],e-=u=o[1],c+=Math.hypot(n,e);return c},t.precisionFixed=yc,t.precisionPrefix=vc,t.precisionRound=_c,t.quadtree=Lu,t.quantile=H,t.quantileSorted=X,t.quantize=function(t,n){for(var e=new Array(n),r=0;r<n;++r)e[r]=t(r/(n-1));return e},t.quickselect=L,t.radialArea=Ub,t.radialLine=Ib,t.randomBates=Hd,t.randomBernoulli=Vd,t.randomBeta=Zd,t.randomBinomial=Kd,t.randomCauchy=Jd,t.randomExponential=Xd,t.randomGamma=Wd,t.randomGeometric=$d,t.randomInt=Bd,t.randomIrwinHall=jd,t.randomLcg=function(t=Math.random()){let n=0|(0<=t&&t<1?t/ep:Math.abs(t));return()=>(n=1664525*n+1013904223|0,ep*(n>>>0))},t.randomLogNormal=Ld,t.randomLogistic=tp,t.randomNormal=Yd,t.randomPareto=Gd,t.randomPoisson=np,t.randomUniform=Ud,t.randomWeibull=Qd,t.range=Z,t.reduce=function(t,n,e){if("function"!=typeof n)throw new TypeError("reducer is not a function");const r=t[Symbol.iterator]();let i,o,a=-1;if(arguments.length<3){if(({done:i,value:e}=r.next()),i)return;++a}for(;({done:i,value:o}=r.next()),!i;)e=n(e,o,++a,t);return e},t.reverse=function(t){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");return Array.from(t).reverse()},t.rgb=ve,t.ribbon=function(){return ba()},t.ribbonArrow=function(){return ba(_a)},t.rollup=A,t.rollups=function(t,n,...e){return S(t,Array.from,n,e)},t.scaleBand=up,t.scaleDiverging=function t(){var n=bp(Pv()(lp));return n.copy=function(){return Nv(n,t())},ip.apply(n,arguments)},t.scaleDivergingLog=function t(){var n=Ep(Pv()).domain([.1,1,10]);return n.copy=function(){return Nv(n,t()).base(n.base())},ip.apply(n,arguments)},t.scaleDivergingPow=zv,t.scaleDivergingSqrt=function(){return zv.apply(null,arguments).exponent(.5)},t.scaleDivergingSymlog=function t(){var n=Cp(Pv());return n.copy=function(){return Nv(n,t()).constant(n.constant())},ip.apply(n,arguments)},t.scaleIdentity=function t(n){var e;function r(t){return null==t||isNaN(t=+t)?e:t}return r.invert=r,r.domain=r.range=function(t){return arguments.length?(n=Array.from(t,fp),r):n.slice()},r.unknown=function(t){return arguments.length?(e=t,r):e},r.copy=function(){return t(n).unknown(e)},n=arguments.length?Array.from(n,fp):[0,1],bp(r)},t.scaleImplicit=op,t.scaleLinear=function t(){var n=vp();return n.copy=function(){return gp(n,t())},rp.apply(n,arguments),bp(n)},t.scaleLog=function t(){var n=Ep(yp()).domain([1,10]);return n.copy=function(){return gp(n,t()).base(n.base())},rp.apply(n,arguments),n},t.scaleOrdinal=ap,t.scalePoint=function(){return cp(up.apply(null,arguments).paddingInner(1))},t.scalePow=Rp,t.scaleQuantile=function t(){var e,r=[],i=[],a=[];function u(){var t=0,n=Math.max(1,i.length);for(a=new Array(n-1);++t<n;)a[t-1]=X(r,t/n);return c}function c(t){return null==t||isNaN(t=+t)?e:i[o(a,t)]}return c.invertExtent=function(t){var n=i.indexOf(t);return n<0?[NaN,NaN]:[n>0?a[n-1]:r[0],n<a.length?a[n]:r[r.length-1]]},c.domain=function(t){if(!arguments.length)return r.slice();r=[];for(let n of t)null==n||isNaN(n=+n)||r.push(n);return r.sort(n),u()},c.range=function(t){return arguments.length?(i=Array.from(t),u()):i.slice()},c.unknown=function(t){return arguments.length?(e=t,c):e},c.quantiles=function(){return a.slice()},c.copy=function(){return t().domain(r).range(i).unknown(e)},rp.apply(c,arguments)},t.scaleQuantize=function t(){var n,e=0,r=1,i=1,a=[.5],u=[0,1];function c(t){return null!=t&&t<=t?u[o(a,t,0,i)]:n}function f(){var t=-1;for(a=new Array(i);++t<i;)a[t]=((t+1)*r-(t-i)*e)/(i+1);return c}return c.domain=function(t){return arguments.length?([e,r]=t,e=+e,r=+r,f()):[e,r]},c.range=function(t){return arguments.length?(i=(u=Array.from(t)).length-1,f()):u.slice()},c.invertExtent=function(t){var n=u.indexOf(t);return n<0?[NaN,NaN]:n<1?[e,a[0]]:n>=i?[a[i-1],r]:[a[n-1],a[n]]},c.unknown=function(t){return arguments.length?(n=t,c):c},c.thresholds=function(){return a.slice()},c.copy=function(){return t().domain([e,r]).range(u).unknown(n)},rp.apply(bp(c),arguments)},t.scaleRadial=function t(){var n,e=vp(),r=[0,1],i=!1;function o(t){var r=Op(e(t));return isNaN(r)?n:i?Math.round(r):r}return o.invert=function(t){return e.invert(Fp(t))},o.domain=function(t){return arguments.length?(e.domain(t),o):e.domain()},o.range=function(t){return arguments.length?(e.range((r=Array.from(t,fp)).map(Fp)),o):r.slice()},o.rangeRound=function(t){return o.range(t).round(!0)},o.round=function(t){return arguments.length?(i=!!t,o):i},o.clamp=function(t){return arguments.length?(e.clamp(t),o):e.clamp()},o.unknown=function(t){return arguments.length?(n=t,o):n},o.copy=function(){return t(e.domain(),r).round(i).clamp(e.clamp()).unknown(n)},rp.apply(o,arguments),bp(o)},t.scaleSequential=function t(){var n=bp(kv()(lp));return n.copy=function(){return Nv(n,t())},ip.apply(n,arguments)},t.scaleSequentialLog=function t(){var n=Ep(kv()).domain([1,10]);return n.copy=function(){return Nv(n,t()).base(n.base())},ip.apply(n,arguments)},t.scaleSequentialPow=Cv,t.scaleSequentialQuantile=function t(){var e=[],r=lp;function i(t){if(null!=t&&!isNaN(t=+t))return r((o(e,t,1)-1)/(e.length-1))}return i.domain=function(t){if(!arguments.length)return e.slice();e=[];for(let n of t)null==n||isNaN(n=+n)||e.push(n);return e.sort(n),i},i.interpolator=function(t){return arguments.length?(r=t,i):r},i.range=function(){return e.map(((t,n)=>r(n/(e.length-1))))},i.quantiles=function(t){return Array.from({length:t+1},((n,r)=>H(e,r/t)))},i.copy=function(){return t(r).domain(e)},ip.apply(i,arguments)},t.scaleSequentialSqrt=function(){return Cv.apply(null,arguments).exponent(.5)},t.scaleSequentialSymlog=function t(){var n=Cp(kv());return n.copy=function(){return Nv(n,t()).constant(n.constant())},ip.apply(n,arguments)},t.scaleSqrt=function(){return Rp.apply(null,arguments).exponent(.5)},t.scaleSymlog=function t(){var n=Cp(yp());return n.copy=function(){return gp(n,t()).constant(n.constant())},rp.apply(n,arguments)},t.scaleThreshold=function t(){var n,e=[.5],r=[0,1],i=1;function a(t){return null!=t&&t<=t?r[o(e,t,0,i)]:n}return a.domain=function(t){return arguments.length?(e=Array.from(t),i=Math.min(e.length,r.length-1),a):e.slice()},a.range=function(t){return arguments.length?(r=Array.from(t),i=Math.min(e.length,r.length-1),a):r.slice()},a.invertExtent=function(t){var n=r.indexOf(t);return[e[n-1],e[n]]},a.unknown=function(t){return arguments.length?(n=t,a):n},a.copy=function(){return t().domain(e).range(r).unknown(n)},rp.apply(a,arguments)},t.scaleTime=function(){return rp.apply(Ev(Kg,Qg,xg,bg,og,eg,tg,Qp,Zp,t.timeFormat).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)},t.scaleUtc=function(){return rp.apply(Ev(Wg,Zg,Gg,Hg,Cg,Eg,Tg,Mg,Zp,t.utcFormat).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)},t.scan=function(t,n){const e=K(t,n);return e<0?void 0:e},t.schemeAccent=Rv,t.schemeBlues=D_,t.schemeBrBG=Xv,t.schemeBuGn=f_,t.schemeBuPu=l_,t.schemeCategory10=qv,t.schemeDark2=Fv,t.schemeGnBu=d_,t.schemeGreens=R_,t.schemeGreys=O_,t.schemeOrRd=g_,t.schemeOranges=j_,t.schemePRGn=Vv,t.schemePaired=Ov,t.schemePastel1=Iv,t.schemePastel2=Uv,t.schemePiYG=Wv,t.schemePuBu=b_,t.schemePuBuGn=v_,t.schemePuOr=Kv,t.schemePuRd=x_,t.schemePurples=U_,t.schemeRdBu=Jv,t.schemeRdGy=n_,t.schemeRdPu=M_,t.schemeRdYlBu=r_,t.schemeRdYlGn=o_,t.schemeReds=Y_,t.schemeSet1=Bv,t.schemeSet2=Yv,t.schemeSet3=Lv,t.schemeSpectral=u_,t.schemeTableau10=jv,t.schemeYlGn=E_,t.schemeYlGnBu=T_,t.schemeYlOrBr=N_,t.schemeYlOrRd=P_,t.select=Dn,t.selectAll=function(t){return"string"==typeof t?new Pn([document.querySelectorAll(t)],[document.documentElement]):new Pn([null==t?[]:Et(t)],Cn)},t.selection=zn,t.selector=St,t.selectorAll=Nt,t.shuffle=Q,t.shuffler=J,t.some=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");let e=-1;for(const r of t)if(n(r,++e,t))return!0;return!1},t.sort=k,t.stack=function(){var t=rb([]),n=Xm,e=Hm,r=Gm;function i(i){var o,a,u=Array.from(t.apply(this,arguments),Vm),c=u.length,f=-1;for(const t of i)for(o=0,++f;o<c;++o)(u[o][f]=[0,+r(t,u[o].key,f,i)]).data=t;for(o=0,a=Tb(n(u));o<c;++o)u[a[o]].index=o;return e(u,a),u}return i.keys=function(n){return arguments.length?(t="function"==typeof n?n:rb(Array.from(n)),i):t},i.value=function(t){return arguments.length?(r="function"==typeof t?t:rb(+t),i):r},i.order=function(t){return arguments.length?(n=null==t?Xm:"function"==typeof t?t:rb(Array.from(t)),i):n},i.offset=function(t){return arguments.length?(e=null==t?Hm:t,i):e},i},t.stackOffsetDiverging=function(t,n){if((u=t.length)>0)for(var e,r,i,o,a,u,c=0,f=t[n[0]].length;c<f;++c)for(o=a=0,e=0;e<u;++e)(i=(r=t[n[e]][c])[1]-r[0])>0?(r[0]=o,r[1]=o+=i):i<0?(r[1]=a,r[0]=a+=i):(r[0]=0,r[1]=i)},t.stackOffsetExpand=function(t,n){if((r=t.length)>0){for(var e,r,i,o=0,a=t[0].length;o<a;++o){for(i=e=0;e<r;++e)i+=t[e][o][1]||0;if(i)for(e=0;e<r;++e)t[e][o][1]/=i}Hm(t,n)}},t.stackOffsetNone=Hm,t.stackOffsetSilhouette=function(t,n){if((e=t.length)>0){for(var e,r=0,i=t[n[0]],o=i.length;r<o;++r){for(var a=0,u=0;a<e;++a)u+=t[a][r][1]||0;i[r][1]+=i[r][0]=-u/2}Hm(t,n)}},t.stackOffsetWiggle=function(t,n){if((i=t.length)>0&&(r=(e=t[n[0]]).length)>0){for(var e,r,i,o=0,a=1;a<r;++a){for(var u=0,c=0,f=0;u<i;++u){for(var s=t[n[u]],l=s[a][1]||0,h=(l-(s[a-1][1]||0))/2,d=0;d<u;++d){var p=t[n[d]];h+=(p[a][1]||0)-(p[a-1][1]||0)}c+=l,f+=h*l}e[a-1][1]+=e[a-1][0]=o,c&&(o-=f/c)}e[a-1][1]+=e[a-1][0]=o,Hm(t,n)}},t.stackOrderAppearance=$m,t.stackOrderAscending=Zm,t.stackOrderDescending=function(t){return Zm(t).reverse()},t.stackOrderInsideOut=function(t){var n,e,r=t.length,i=t.map(Km),o=$m(t),a=0,u=0,c=[],f=[];for(n=0;n<r;++n)e=o[n],a<u?(a+=i[e],c.push(e)):(u+=i[e],f.push(e));return f.reverse().concat(c)},t.stackOrderNone=Xm,t.stackOrderReverse=function(t){return Xm(t).reverse()},t.stratify=function(){var t=wd,n=Md;function e(e){var r,i,o,a,u,c,f,s=Array.from(e),l=s.length,h=new Map;for(i=0;i<l;++i)r=s[i],u=s[i]=new Zh(r),null!=(c=t(r,i,e))&&(c+="")&&(f=u.id=c,h.set(f,h.has(f)?xd:u)),null!=(c=n(r,i,e))&&(c+="")&&(u.parent=c);for(i=0;i<l;++i)if(c=(u=s[i]).parent){if(!(a=h.get(c)))throw new Error("missing: "+c);if(a===xd)throw new Error("ambiguous: "+c);a.children?a.children.push(u):a.children=[u],u.parent=a}else{if(o)throw new Error("multiple roots");o=u}if(!o)throw new Error("no root");if(o.parent=md,o.eachBefore((function(t){t.depth=t.parent.depth+1,--l})).eachBefore(Wh),o.parent=null,l>0)throw new Error("cycle");return o}return e.id=function(n){return arguments.length?(t=ld(n),e):t},e.parentId=function(t){return arguments.length?(n=ld(t),e):n},e},t.style=Jt,t.subset=function(t,n){return rt(n,t)},t.sum=function(t,n){let e=0;if(void 0===n)for(let n of t)(n=+n)&&(e+=n);else{let r=-1;for(let i of t)(i=+n(i,++r,t))&&(e+=i)}return e},t.superset=rt,t.svg=Ou,t.symbol=function(t,n){var e=null;function r(){var r;if(e||(e=r=fa()),t.apply(this,arguments).draw(e,+n.apply(this,arguments)),r)return e=null,r+""||null}return t="function"==typeof t?t:rb(t||Vb),n="function"==typeof n?n:rb(void 0===n?64:+n),r.type=function(n){return arguments.length?(t="function"==typeof n?n:rb(n),r):t},r.size=function(t){return arguments.length?(n="function"==typeof t?t:rb(+t),r):n},r.context=function(t){return arguments.length?(e=null==t?null:t,r):e},r},t.symbolCircle=Vb,t.symbolCross=$b,t.symbolDiamond=Kb,t.symbolSquare=em,t.symbolStar=nm,t.symbolTriangle=im,t.symbolWye=fm,t.symbols=sm,t.text=Nu,t.thresholdFreedmanDiaconis=function(t,n,e){return Math.ceil((e-n)/(2*(H(t,.75)-H(t,.25))*Math.pow(c(t),-1/3)))},t.thresholdScott=function(t,n,e){return Math.ceil((e-n)/(3.5*d(t)*Math.pow(c(t),-1/3)))},t.thresholdSturges=I,t.tickFormat=_p,t.tickIncrement=R,t.tickStep=F,t.ticks=q,t.timeDay=eg,t.timeDays=rg,t.timeFormatDefaultLocale=xv,t.timeFormatLocale=ey,t.timeFriday=sg,t.timeFridays=vg,t.timeHour=tg,t.timeHours=ng,t.timeInterval=Bp,t.timeMillisecond=Yp,t.timeMilliseconds=Lp,t.timeMinute=Qp,t.timeMinutes=Jp,t.timeMonday=ag,t.timeMondays=dg,t.timeMonth=bg,t.timeMonths=mg,t.timeSaturday=lg,t.timeSaturdays=_g,t.timeSecond=Zp,t.timeSeconds=Kp,t.timeSunday=og,t.timeSundays=hg,t.timeThursday=fg,t.timeThursdays=yg,t.timeTickInterval=Qg,t.timeTicks=Kg,t.timeTuesday=ug,t.timeTuesdays=pg,t.timeWednesday=cg,t.timeWednesdays=gg,t.timeWeek=og,t.timeWeeks=hg,t.timeYear=xg,t.timeYears=wg,t.timeout=ci,t.timer=ri,t.timerFlush=ii,t.transition=Hi,t.transpose=tt,t.tree=function(){var t=Ad,n=1,e=1,r=null;function i(i){var c=function(t){for(var n,e,r,i,o,a=new Nd(t,0),u=[a];n=u.pop();)if(r=n._.children)for(n.children=new Array(o=r.length),i=o-1;i>=0;--i)u.push(e=n.children[i]=new Nd(r[i],i)),e.parent=n;return(a.parent=new Nd(null,0)).children=[a],a}(i);if(c.eachAfter(o),c.parent.m=-c.z,c.eachBefore(a),r)i.eachBefore(u);else{var f=i,s=i,l=i;i.eachBefore((function(t){t.x<f.x&&(f=t),t.x>s.x&&(s=t),t.depth>l.depth&&(l=t)}));var h=f===s?1:t(f,s)/2,d=h-f.x,p=n/(s.x+h+d),g=e/(l.depth||1);i.eachBefore((function(t){t.x=(t.x+d)*p,t.y=t.depth*g}))}return i}function o(n){var e=n.children,r=n.parent.children,i=n.i?r[n.i-1]:null;if(e){!function(t){for(var n,e=0,r=0,i=t.children,o=i.length;--o>=0;)(n=i[o]).z+=e,n.m+=e,e+=n.s+(r+=n.c)}(n);var o=(e[0].z+e[e.length-1].z)/2;i?(n.z=i.z+t(n._,i._),n.m=n.z-o):n.z=o}else i&&(n.z=i.z+t(n._,i._));n.parent.A=function(n,e,r){if(e){for(var i,o=n,a=n,u=e,c=o.parent.children[0],f=o.m,s=a.m,l=u.m,h=c.m;u=Sd(u),o=Td(o),u&&o;)c=Td(c),(a=Sd(a)).a=n,(i=u.z+l-o.z-f+t(u._,o._))>0&&(Ed(kd(u,n,r),n,i),f+=i,s+=i),l+=u.m,f+=o.m,h+=c.m,s+=a.m;u&&!Sd(a)&&(a.t=u,a.m+=l-s),o&&!Td(c)&&(c.t=o,c.m+=f-h,r=n)}return r}(n,i,n.parent.A||r[0])}function a(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function u(t){t.x*=n,t.y=t.depth*e}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.treemap=function(){var t=Dd,n=!1,e=1,r=1,i=[0],o=hd,a=hd,u=hd,c=hd,f=hd;function s(t){return t.x0=t.y0=0,t.x1=e,t.y1=r,t.eachBefore(l),i=[0],n&&t.eachBefore(_d),t}function l(n){var e=i[n.depth],r=n.x0+e,s=n.y0+e,l=n.x1-e,h=n.y1-e;l<r&&(r=l=(r+l)/2),h<s&&(s=h=(s+h)/2),n.x0=r,n.y0=s,n.x1=l,n.y1=h,n.children&&(e=i[n.depth+1]=o(n)/2,r+=f(n)-e,s+=a(n)-e,(l-=u(n)-e)<r&&(r=l=(r+l)/2),(h-=c(n)-e)<s&&(s=h=(s+h)/2),t(n,r,s,l,h))}return s.round=function(t){return arguments.length?(n=!!t,s):n},s.size=function(t){return arguments.length?(e=+t[0],r=+t[1],s):[e,r]},s.tile=function(n){return arguments.length?(t=ld(n),s):t},s.padding=function(t){return arguments.length?s.paddingInner(t).paddingOuter(t):s.paddingInner()},s.paddingInner=function(t){return arguments.length?(o="function"==typeof t?t:dd(+t),s):o},s.paddingOuter=function(t){return arguments.length?s.paddingTop(t).paddingRight(t).paddingBottom(t).paddingLeft(t):s.paddingTop()},s.paddingTop=function(t){return arguments.length?(a="function"==typeof t?t:dd(+t),s):a},s.paddingRight=function(t){return arguments.length?(u="function"==typeof t?t:dd(+t),s):u},s.paddingBottom=function(t){return arguments.length?(c="function"==typeof t?t:dd(+t),s):c},s.paddingLeft=function(t){return arguments.length?(f="function"==typeof t?t:dd(+t),s):f},s},t.treemapBinary=function(t,n,e,r,i){var o,a,u=t.children,c=u.length,f=new Array(c+1);for(f[0]=a=o=0;o<c;++o)f[o+1]=a+=u[o].value;!function t(n,e,r,i,o,a,c){if(n>=e-1){var s=u[n];return s.x0=i,s.y0=o,s.x1=a,void(s.y1=c)}var l=f[n],h=r/2+l,d=n+1,p=e-1;for(;d<p;){var g=d+p>>>1;f[g]<h?d=g+1:p=g}h-f[d-1]<f[d]-h&&n+1<d&&--d;var y=f[d]-l,v=r-y;if(a-i>c-o){var _=r?(i*v+a*y)/r:a;t(n,d,y,i,o,_,c),t(d,e,v,_,o,a,c)}else{var b=r?(o*v+c*y)/r:c;t(n,d,y,i,o,a,b),t(d,e,v,i,b,a,c)}}(0,c,t.value,n,e,r,i)},t.treemapDice=bd,t.treemapResquarify=qd,t.treemapSlice=Cd,t.treemapSliceDice=function(t,n,e,r,i){(1&t.depth?Cd:bd)(t,n,e,r,i)},t.treemapSquarify=Dd,t.tsv=zu,t.tsvFormat=mu,t.tsvFormatBody=xu,t.tsvFormatRow=Mu,t.tsvFormatRows=wu,t.tsvFormatValue=Au,t.tsvParse=_u,t.tsvParseRows=bu,t.union=function(...t){const n=new Set;for(const e of t)for(const t of e)n.add(t);return n},t.utcDay=Eg,t.utcDays=kg,t.utcFriday=Rg,t.utcFridays=Lg,t.utcHour=Tg,t.utcHours=Sg,t.utcMillisecond=Yp,t.utcMilliseconds=Lp,t.utcMinute=Mg,t.utcMinutes=Ag,t.utcMonday=Pg,t.utcMondays=Ig,t.utcMonth=Hg,t.utcMonths=Xg,t.utcSaturday=Fg,t.utcSaturdays=jg,t.utcSecond=Zp,t.utcSeconds=Kp,t.utcSunday=Cg,t.utcSundays=Og,t.utcThursday=qg,t.utcThursdays=Yg,t.utcTickInterval=Zg,t.utcTicks=Wg,t.utcTuesday=zg,t.utcTuesdays=Ug,t.utcWednesday=Dg,t.utcWednesdays=Bg,t.utcWeek=Cg,t.utcWeeks=Og,t.utcYear=Gg,t.utcYears=Vg,t.variance=h,t.version="6.7.0",t.window=Wt,t.xml=Ru,t.zip=function(){return tt(arguments)},t.zoom=function(){var t,n,e,r=ox,i=ax,o=sx,a=cx,u=fx,c=[0,1/0],f=[[-1/0,-1/0],[1/0,1/0]],s=250,l=Dr,h=pt("start","zoom","end"),d=500,p=0,g=10;function y(t){t.property("__zoom",ux).on("wheel.zoom",M).on("mousedown.zoom",A).on("dblclick.zoom",T).filter(u).on("touchstart.zoom",S).on("touchmove.zoom",E).on("touchend.zoom touchcancel.zoom",k).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function v(t,n){return(n=Math.max(c[0],Math.min(c[1],n)))===t.k?t:new tx(n,t.x,t.y)}function _(t,n,e){var r=n[0]-e[0]*t.k,i=n[1]-e[1]*t.k;return r===t.x&&i===t.y?t:new tx(t.k,r,i)}function b(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function m(t,n,e,r){t.on("start.zoom",(function(){x(this,arguments).event(r).start()})).on("interrupt.zoom end.zoom",(function(){x(this,arguments).event(r).end()})).tween("zoom",(function(){var t=this,o=arguments,a=x(t,o).event(r),u=i.apply(t,o),c=null==e?b(u):"function"==typeof e?e.apply(t,o):e,f=Math.max(u[1][0]-u[0][0],u[1][1]-u[0][1]),s=t.__zoom,h="function"==typeof n?n.apply(t,o):n,d=l(s.invert(c).concat(f/s.k),h.invert(c).concat(f/h.k));return function(t){if(1===t)t=h;else{var n=d(t),e=f/n[2];t=new tx(e,c[0]-n[0]*e,c[1]-n[1]*e)}a.zoom(null,t)}}))}function x(t,n,e){return!e&&t.__zooming||new w(t,n)}function w(t,n){this.that=t,this.args=n,this.active=0,this.sourceEvent=null,this.extent=i.apply(t,n),this.taps=0}function M(t,...n){if(r.apply(this,arguments)){var e=x(this,n).event(t),i=this.__zoom,u=Math.max(c[0],Math.min(c[1],i.k*Math.pow(2,a.apply(this,arguments)))),s=In(t);if(e.wheel)e.mouse[0][0]===s[0]&&e.mouse[0][1]===s[1]||(e.mouse[1]=i.invert(e.mouse[0]=s)),clearTimeout(e.wheel);else{if(i.k===u)return;e.mouse=[s,i.invert(s)],gi(this),e.start()}ix(t),e.wheel=setTimeout(l,150),e.zoom("mouse",o(_(v(i,u),e.mouse[0],e.mouse[1]),e.extent,f))}function l(){e.wheel=null,e.end()}}function A(t,...n){if(!e&&r.apply(this,arguments)){var i=x(this,n,!0).event(t),a=Dn(t.view).on("mousemove.zoom",h,!0).on("mouseup.zoom",d,!0),u=In(t,c),c=t.currentTarget,s=t.clientX,l=t.clientY;Yn(t.view),rx(t),i.mouse=[u,this.__zoom.invert(u)],gi(this),i.start()}function h(t){if(ix(t),!i.moved){var n=t.clientX-s,e=t.clientY-l;i.moved=n*n+e*e>p}i.event(t).zoom("mouse",o(_(i.that.__zoom,i.mouse[0]=In(t,c),i.mouse[1]),i.extent,f))}function d(t){a.on("mousemove.zoom mouseup.zoom",null),Ln(t.view,i.moved),ix(t),i.event(t).end()}}function T(t,...n){if(r.apply(this,arguments)){var e=this.__zoom,a=In(t.changedTouches?t.changedTouches[0]:t,this),u=e.invert(a),c=e.k*(t.shiftKey?.5:2),l=o(_(v(e,c),a,u),i.apply(this,n),f);ix(t),s>0?Dn(this).transition().duration(s).call(m,l,a,t):Dn(this).call(y.transform,l,a,t)}}function S(e,...i){if(r.apply(this,arguments)){var o,a,u,c,f=e.touches,s=f.length,l=x(this,i,e.changedTouches.length===s).event(e);for(rx(e),a=0;a<s;++a)c=[c=In(u=f[a],this),this.__zoom.invert(c),u.identifier],l.touch0?l.touch1||l.touch0[2]===c[2]||(l.touch1=c,l.taps=0):(l.touch0=c,o=!0,l.taps=1+!!t);t&&(t=clearTimeout(t)),o&&(l.taps<2&&(n=c[0],t=setTimeout((function(){t=null}),d)),gi(this),l.start())}}function E(t,...n){if(this.__zooming){var e,r,i,a,u=x(this,n).event(t),c=t.changedTouches,s=c.length;for(ix(t),e=0;e<s;++e)i=In(r=c[e],this),u.touch0&&u.touch0[2]===r.identifier?u.touch0[0]=i:u.touch1&&u.touch1[2]===r.identifier&&(u.touch1[0]=i);if(r=u.that.__zoom,u.touch1){var l=u.touch0[0],h=u.touch0[1],d=u.touch1[0],p=u.touch1[1],g=(g=d[0]-l[0])*g+(g=d[1]-l[1])*g,y=(y=p[0]-h[0])*y+(y=p[1]-h[1])*y;r=v(r,Math.sqrt(g/y)),i=[(l[0]+d[0])/2,(l[1]+d[1])/2],a=[(h[0]+p[0])/2,(h[1]+p[1])/2]}else{if(!u.touch0)return;i=u.touch0[0],a=u.touch0[1]}u.zoom("touch",o(_(r,i,a),u.extent,f))}}function k(t,...r){if(this.__zooming){var i,o,a=x(this,r).event(t),u=t.changedTouches,c=u.length;for(rx(t),e&&clearTimeout(e),e=setTimeout((function(){e=null}),d),i=0;i<c;++i)o=u[i],a.touch0&&a.touch0[2]===o.identifier?delete a.touch0:a.touch1&&a.touch1[2]===o.identifier&&delete a.touch1;if(a.touch1&&!a.touch0&&(a.touch0=a.touch1,delete a.touch1),a.touch0)a.touch0[1]=this.__zoom.invert(a.touch0[0]);else if(a.end(),2===a.taps&&(o=In(o,this),Math.hypot(n[0]-o[0],n[1]-o[1])<g)){var f=Dn(this).on("dblclick.zoom");f&&f.apply(this,arguments)}}}return y.transform=function(t,n,e,r){var i=t.selection?t.selection():t;i.property("__zoom",ux),t!==i?m(t,n,e,r):i.interrupt().each((function(){x(this,arguments).event(r).start().zoom(null,"function"==typeof n?n.apply(this,arguments):n).end()}))},y.scaleBy=function(t,n,e,r){y.scaleTo(t,(function(){var t=this.__zoom.k,e="function"==typeof n?n.apply(this,arguments):n;return t*e}),e,r)},y.scaleTo=function(t,n,e,r){y.transform(t,(function(){var t=i.apply(this,arguments),r=this.__zoom,a=null==e?b(t):"function"==typeof e?e.apply(this,arguments):e,u=r.invert(a),c="function"==typeof n?n.apply(this,arguments):n;return o(_(v(r,c),a,u),t,f)}),e,r)},y.translateBy=function(t,n,e,r){y.transform(t,(function(){return o(this.__zoom.translate("function"==typeof n?n.apply(this,arguments):n,"function"==typeof e?e.apply(this,arguments):e),i.apply(this,arguments),f)}),null,r)},y.translateTo=function(t,n,e,r,a){y.transform(t,(function(){var t=i.apply(this,arguments),a=this.__zoom,u=null==r?b(t):"function"==typeof r?r.apply(this,arguments):r;return o(nx.translate(u[0],u[1]).scale(a.k).translate("function"==typeof n?-n.apply(this,arguments):-n,"function"==typeof e?-e.apply(this,arguments):-e),t,f)}),r,a)},w.prototype={event:function(t){return t&&(this.sourceEvent=t),this},start:function(){return 1==++this.active&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(t,n){return this.mouse&&"mouse"!==t&&(this.mouse[1]=n.invert(this.mouse[0])),this.touch0&&"touch"!==t&&(this.touch0[1]=n.invert(this.touch0[0])),this.touch1&&"touch"!==t&&(this.touch1[1]=n.invert(this.touch1[0])),this.that.__zoom=n,this.emit("zoom"),this},end:function(){return 0==--this.active&&(delete this.that.__zooming,this.emit("end")),this},emit:function(t){var n=Dn(this.that).datum();h.call(t,this.that,new Jm(t,{sourceEvent:this.sourceEvent,target:y,type:t,transform:this.that.__zoom,dispatch:h}),n)}},y.wheelDelta=function(t){return arguments.length?(a="function"==typeof t?t:Qm(+t),y):a},y.filter=function(t){return arguments.length?(r="function"==typeof t?t:Qm(!!t),y):r},y.touchable=function(t){return arguments.length?(u="function"==typeof t?t:Qm(!!t),y):u},y.extent=function(t){return arguments.length?(i="function"==typeof t?t:Qm([[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]]),y):i},y.scaleExtent=function(t){return arguments.length?(c[0]=+t[0],c[1]=+t[1],y):[c[0],c[1]]},y.translateExtent=function(t){return arguments.length?(f[0][0]=+t[0][0],f[1][0]=+t[1][0],f[0][1]=+t[0][1],f[1][1]=+t[1][1],y):[[f[0][0],f[0][1]],[f[1][0],f[1][1]]]},y.constrain=function(t){return arguments.length?(o=t,y):o},y.duration=function(t){return arguments.length?(s=+t,y):s},y.interpolate=function(t){return arguments.length?(l=t,y):l},y.on=function(){var t=h.on.apply(h,arguments);return t===h?y:t},y.clickDistance=function(t){return arguments.length?(p=(t=+t)*t,y):Math.sqrt(p)},y.tapDistance=function(t){return arguments.length?(g=+t,y):g},y},t.zoomIdentity=nx,t.zoomTransform=ex,Object.defineProperty(t,"__esModule",{value:!0})}));
|
2951121599/Bili-Insight
| 10,465
|
chrome-extension/scripts/ui.js
|
function numberToDisplay(number) {
if (number > 10000) {
return `${(number / 10000).toFixed(1)}万`;
}
return number;
}
function timestampToDisplay(timestamp) {
if (timestamp == null) {
return ""
}
let date = new Date(timestamp * 1000);
let timediff = Date.now() / 1000 - timestamp;
const hour = 60 * 60;
const day = 24 * hour;
if (timediff < hour) {
return "刚刚";
} else if (timediff < day) {
return `${Math.floor(timediff / hour)}小时前`;
} else if (timediff < 30 * day) {
return `${Math.floor(timediff / day)}天前`;
} else {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
}
function secondsToDisplay(sec) {
if (!sec) {
return 0;
}
function digitToStr(n) {
n = Math.floor(n);
return n < 10 ? "0" + n : n;
}
sec = Math.floor(sec);
if (sec < 60) {
return `00:${digitToStr(sec)}`;
} else if (sec < 60 * 60) {
return `${digitToStr(sec / 60)}:${digitToStr(sec % 60)}`;
} else {
return `${digitToStr(sec / 60 / 60)}:${digitToStr(sec / 60) % 60}:${digitToStr(sec % 60)}`;
}
}
function getVideoProfileCardDataHTML(data) {
return `
<div class="idc-info clearfix">
<div class="idc-content h">
<div class="idc-meta">
<span class="idc-meta-item"><data-title>点赞</data-title> ${numberToDisplay(data["like"]) || 0}</span>
<span class="idc-meta-item"><data-title>投币</data-title> ${numberToDisplay(data["coin"]) || 0}</span>
<span class="idc-meta-item"><data-title>收藏</data-title> ${numberToDisplay(data["favorite"]) || 0}</span>
</div>
<div class="idc-meta">
<span class="idc-meta-item"><data-title>分享</data-title> ${numberToDisplay(data["share"]) || 0}</span>
<span class="idc-meta-item"><data-title>投稿</data-title> ${timestampToDisplay(data["pubdate"])}</span>
<span class="idc-meta-item"><data-title>时长</data-title> ${secondsToDisplay(data["duration"])}</span>
</div>
</div>
<div id="tag-list-bi">
</div>
<div class="description" style="${data["summary"] ? "" : "display: none"}">
<span style="display: flex">
总结: ${data["summary"]}
</span>
</div>
</div>
`
}
function getVideoProfileCardHTML(data) {
return `
<div id="biliinsight-video-card" style="position: absolute;">
<div id="biliinsight-video-card-data-bi">
${getVideoProfileCardDataHTML(data)}
</div>
<div id="word-cloud-canvas-wrapper-bi">
<canvas id="word-cloud-canvas-bi" style="width: 100%; height: 0"></canvas>
</div>
<div class="markmap markmap-wrapper">
<svg class="markmap">
</svg>
</div>
</div>
`
}
function VideoProfileCard() {
this.videoId = null;
this.data = {};
this.cursorX = 0;
this.cursorY = 0;
this.target = null;
this.enabled = false;
this.wordCloud = null;
this.el = document.createElement("div");
this.el.style.position = "absolute";
this.el.style.display = "none";
this.el.innerHTML = getVideoProfileCardHTML(this.data);
this.el.addEventListener("transitionend", () => {
this.updateCursor(this.cursorX, this.cursorY);
})
this.idCardObserver = new MutationObserver((mutationList, observer) => {
this.clearOriginalCard();
})
this.disable();
document.body.appendChild(this.el);
}
VideoProfileCard.prototype.disable = function () {
this.videoId = null;
this.enabled = false;
this.data = {};
if (this.el) {
this.el.style.display = "none";
let canvas = document.getElementById("word-cloud-canvas-bi");
if (canvas) {
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
canvas.parentNode.classList.remove("canvas-show");
}
let svgEl = document.getElementsByClassName('markmap')[1];
if (svgEl) {
svgEl.parentNode.classList.remove("canvas-show");
}
this.idCardObserver.disconnect();
}
}
VideoProfileCard.prototype.enable = function () {
if (!this.enabled) {
this.enabled = true;
this.idCardObserver.observe(document.body, {
"childList": true,
"subtree": true
})
return true;
}
return false;
}
VideoProfileCard.prototype.checkTargetValid = function (target) {
if (this.enabled && this.target) {
while (target) {
if (target == this.target) {
return;
}
target = target.parentNode;
}
this.disable();
}
}
VideoProfileCard.prototype.clearOriginalCard = function () {
while (document.getElementById("id-card")) {
document.getElementById("id-card").remove();
}
for (let card of document.getElementsByClassName("user-card")) {
card.remove();
}
for (let card of document.getElementsByClassName("card-loaded")) {
card.remove();
}
}
VideoProfileCard.prototype.updateVideoId = function (videoId) {
this.videoId = videoId;
}
VideoProfileCard.prototype.updateCursor = function (cursorX, cursorY) {
const cursorPadding = 10;
const windowPadding = 20;
this.cursorX = cursorX;
this.cursorY = cursorY;
if (this.el) {
let width = this.el.scrollWidth;
let height = this.el.scrollHeight;
if (this.cursorX + width + windowPadding > window.scrollX + window.innerWidth) {
// Will overflow to the right, put it on the left
this.el.style.left = `${this.cursorX - cursorPadding - width}px`;
} else {
this.el.style.left = `${this.cursorX + cursorPadding}px`;
}
if (this.cursorY + height + windowPadding > window.scrollY + window.innerHeight) {
// Will overflow to the bottom, put it on the top
if (this.cursorY - windowPadding - height < window.scrollY) {
// Can't fit on top either, put it in the middle
this.el.style.top = `${window.scrollY + (window.innerHeight - height) / 2}px`;
} else {
this.el.style.top = `${this.cursorY - cursorPadding - height}px`;
}
} else {
this.el.style.top = `${this.cursorY + cursorPadding}px`;
}
}
}
VideoProfileCard.prototype.updateTarget = function (target) {
this.target = target;
let vpc = this
this.target.addEventListener("mouseleave", function leaveHandle(ev) {
vpc.disable();
this.removeEventListener("mouseleave", leaveHandle);
})
}
VideoProfileCard.prototype.wordCloudMaxCount = function () {
return Math.max(...this.data["wordcloud"].map(item => item[1]))
}
VideoProfileCard.prototype.drawVideoTags = function () {
let tagList = document.getElementById("tag-list-bi");
tagList.innerHTML = "";
if (this.data["video_type"]) {
for (let d of this.data["video_type"]) {
if (BILIBILI_VIDEO_TYPE_MAP[d[0]]) {
let el = document.createElement("span");
el.className = "badge";
el.innerHTML = BILIBILI_VIDEO_TYPE_MAP[d[0]];
tagList.appendChild(el);
}
}
}
}
VideoProfileCard.prototype.updateData = function (data) {
let uid = data["uid"];
let d = data["payload"];
if (uid != this.videoId) {
return;
}
if (data["api"] == "info") {
this.data["like"] = d["data"]['like']
this.data["coin"] = d["data"]['coin']
this.data["favorite"] = d["data"]['favorite']
this.data["share"] = d["data"]['share']
this.data["pubdate"] = d["data"]['pubdate']
this.data["duration"] = d["data"]['duration']
this.data["summary"] = d["data"]["summary"];
} else if (data["api"] == "wordcloud") {
this.data["wordcloud"] = d["word"];
this.data["video_type"] = d["type"];
}
if (data["api"] == "wordcloud") {
let canvas = document.getElementById("word-cloud-canvas-bi");
if (this.data["wordcloud"].length > 0) {
canvas.style.height = `${canvas.offsetWidth / 2}px`;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
canvas.parentNode.classList.add("canvas-show");
WordCloud(canvas, {
list: JSON.parse(JSON.stringify(this.data["wordcloud"])),
backgroundColor: "transparent",
weightFactor: 100 / this.wordCloudMaxCount(),
shrinkToFit: true,
minSize: biliInsightOptions.minSize
});
this.drawVideoTags();
} else {
canvas.style.height = "0px";
canvas.height = 0;
}
} else if (this.data['duration']) {
// if has duration
document.getElementById("biliinsight-video-card-data-bi").innerHTML = getVideoProfileCardDataHTML(this.data);
this.drawVideoTags();
}
if (data["api"] == "markmap") {
let svgEl = document.getElementsByClassName('markmap')[1]
if (!this.mm) {
this.mm = markmap.Markmap.create(svgEl);
}
let markMapConfig = `---
markmap:
colorFreezeLevel: 2
maxWidth: 300
embedAssets: true
---\n`
let markmapContext = data.payload.data
if (markmapContext && data.payload.data.split('\n').length > 12) {
markmapContext = data.payload.data.split('\n').slice(0, 12).join('\n')
}
if (!markmapContext) {
return
}
let { root } = new markmap.Transformer().transform(markMapConfig + markmapContext);
if (root.children) {
this.mm.setData(root);
this.mm.fit();
svgEl.parentNode.classList.add("canvas-show");
} else {
svgEl.parentNode.classList.remove("canvas-show");
}
}
if (this.enabled && this.el && this.el.style.display != "flex") {
this.clearOriginalCard();
this.el.style.display = "flex";
}
this.updateCursor(this.cursorX, this.cursorY);
}
videoProfileCard = new VideoProfileCard();
|
2977094657/ZsxqCrawler
| 1,683
|
frontend/src/components/SafeImage.tsx
|
'use client';
import { useState } from 'react';
interface SafeImageProps {
src?: string;
alt: string;
className?: string;
fallbackClassName?: string;
fallbackText?: string;
fallbackGradient?: string;
}
export default function SafeImage({
src,
alt,
className = '',
fallbackClassName = '',
fallbackText,
fallbackGradient = 'from-blue-400 to-purple-500'
}: SafeImageProps) {
const [imageError, setImageError] = useState(false);
const [imageLoading, setImageLoading] = useState(true);
// 如果没有图片URL或图片加载失败,显示渐变背景
if (!src || imageError) {
return (
<div
className={`bg-gradient-to-br ${fallbackGradient} flex items-center justify-center ${fallbackClassName || className}`}
>
{fallbackText && (
<span className="text-white font-medium text-sm opacity-80">
{fallbackText}
</span>
)}
</div>
);
}
return (
<div className={`relative ${className}`}>
{imageLoading && (
<div
className={`absolute inset-0 bg-gradient-to-br ${fallbackGradient} animate-pulse flex items-center justify-center`}
>
<div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
</div>
)}
<img
src={src}
alt={alt}
className={`${className} ${imageLoading ? 'opacity-0' : 'opacity-100'} transition-opacity duration-300`}
onLoad={() => setImageLoading(false)}
onError={() => {
setImageError(true);
setImageLoading(false);
}}
referrerPolicy="no-referrer"
crossOrigin="anonymous"
/>
</div>
);
}
|
2977094657/ZsxqCrawler
| 10,157
|
frontend/src/components/DataPanel.tsx
|
'use client';
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { apiClient, Topic, FileItem, PaginatedResponse, Group } from '@/lib/api';
interface DataPanelProps {
selectedGroup?: Group | null;
}
export default function DataPanel({ selectedGroup }: DataPanelProps) {
const [topicsData, setTopicsData] = useState<PaginatedResponse<Topic> | null>(null);
const [filesData, setFilesData] = useState<PaginatedResponse<FileItem> | null>(null);
const [loading, setLoading] = useState(false);
// 话题查询参数
const [topicsPage, setTopicsPage] = useState(1);
const [topicsSearch, setTopicsSearch] = useState('');
// 文件查询参数
const [filesPage, setFilesPage] = useState(1);
const [filesStatus, setFilesStatus] = useState<string>('');
useEffect(() => {
loadTopics();
}, [topicsPage]);
useEffect(() => {
loadFiles();
}, [filesPage, filesStatus]);
const loadTopics = async () => {
try {
setLoading(true);
let data;
if (selectedGroup) {
// 如果选择了群组,获取该群组的话题
data = await apiClient.getGroupTopics(selectedGroup.group_id, topicsPage, 20, topicsSearch || undefined);
} else {
// 否则获取所有话题
data = await apiClient.getTopics(topicsPage, 20, topicsSearch || undefined);
}
setTopicsData(data);
} catch (error) {
console.error('加载话题数据失败:', error);
} finally {
setLoading(false);
}
};
const loadFiles = async () => {
try {
setLoading(true);
const data = await apiClient.getFiles(filesPage, 20, filesStatus || undefined);
setFilesData(data);
} catch (error) {
console.error('加载文件数据失败:', error);
} finally {
setLoading(false);
}
};
const handleTopicsSearch = () => {
setTopicsPage(1);
loadTopics();
};
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString('zh-CN');
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'completed':
return <Badge className="bg-green-100 text-green-800">已完成</Badge>;
case 'pending':
return <Badge className="bg-yellow-100 text-yellow-800">待下载</Badge>;
case 'failed':
return <Badge className="bg-red-100 text-red-800">失败</Badge>;
default:
return <Badge variant="secondary">{status}</Badge>;
}
};
return (
<Tabs defaultValue="topics" className="space-y-6">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="topics">话题数据</TabsTrigger>
<TabsTrigger value="files">文件数据</TabsTrigger>
</TabsList>
<TabsContent value="topics">
<Card className="border border-gray-200 shadow-none">
<CardHeader>
<CardTitle>
{selectedGroup ? `${selectedGroup.name} - 话题列表` : '话题列表'}
</CardTitle>
<CardDescription>
{selectedGroup
? `查看 ${selectedGroup.name} 群组的话题数据`
: '查看已采集的话题数据'
}
</CardDescription>
</CardHeader>
<CardContent>
{/* 搜索栏 */}
<div className="flex gap-2 mb-4">
<Input
placeholder="搜索话题标题..."
value={topicsSearch}
onChange={(e) => setTopicsSearch(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleTopicsSearch()}
/>
<Button onClick={handleTopicsSearch} disabled={loading}>
搜索
</Button>
</div>
{/* 话题表格 */}
{topicsData && (
<>
<Table>
<TableHeader>
<TableRow>
<TableHead>标题</TableHead>
<TableHead>创建时间</TableHead>
<TableHead>点赞数</TableHead>
<TableHead>评论数</TableHead>
<TableHead>阅读数</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{topicsData.data.map((topic) => (
<TableRow key={topic.topic_id}>
<TableCell className="max-w-md">
<div className="truncate" title={topic.title}>
{topic.title || '无标题'}
</div>
</TableCell>
<TableCell>{formatDate(topic.create_time)}</TableCell>
<TableCell>{topic.likes_count}</TableCell>
<TableCell>{topic.comments_count}</TableCell>
<TableCell>{topic.reading_count}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{/* 分页控制 */}
<div className="flex items-center justify-between mt-4">
<div className="text-sm text-muted-foreground">
共 {topicsData.pagination.total} 条记录,第 {topicsData.pagination.page} / {topicsData.pagination.pages} 页
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setTopicsPage(Math.max(1, topicsPage - 1))}
disabled={topicsPage <= 1 || loading}
>
上一页
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setTopicsPage(Math.min(topicsData.pagination.pages, topicsPage + 1))}
disabled={topicsPage >= topicsData.pagination.pages || loading}
>
下一页
</Button>
</div>
</div>
</>
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="files">
<Card className="border border-gray-200 shadow-none">
<CardHeader>
<CardTitle>文件列表</CardTitle>
<CardDescription>查看已收集的文件信息</CardDescription>
</CardHeader>
<CardContent>
{/* 状态筛选 */}
<div className="flex gap-2 mb-4">
<Select value={filesStatus} onValueChange={setFilesStatus}>
<SelectTrigger className="w-48">
<SelectValue placeholder="选择状态筛选" />
</SelectTrigger>
<SelectContent>
<SelectItem value="">全部状态</SelectItem>
<SelectItem value="pending">待下载</SelectItem>
<SelectItem value="completed">已完成</SelectItem>
<SelectItem value="failed">失败</SelectItem>
</SelectContent>
</Select>
</div>
{/* 文件表格 */}
{filesData && (
<>
<Table>
<TableHeader>
<TableRow>
<TableHead>文件名</TableHead>
<TableHead>大小</TableHead>
<TableHead>下载次数</TableHead>
<TableHead>创建时间</TableHead>
<TableHead>状态</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filesData.data.map((file) => (
<TableRow key={file.file_id}>
<TableCell className="max-w-md">
<div className="truncate" title={file.name}>
{file.name}
</div>
</TableCell>
<TableCell>{formatFileSize(file.size)}</TableCell>
<TableCell>{file.download_count}</TableCell>
<TableCell>{formatDate(file.create_time)}</TableCell>
<TableCell>{getStatusBadge(file.download_status)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{/* 分页控制 */}
<div className="flex items-center justify-between mt-4">
<div className="text-sm text-muted-foreground">
共 {filesData.pagination.total} 条记录,第 {filesData.pagination.page} / {filesData.pagination.pages} 页
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setFilesPage(Math.max(1, filesPage - 1))}
disabled={filesPage <= 1 || loading}
>
上一页
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setFilesPage(Math.min(filesData.pagination.pages, filesPage + 1))}
disabled={filesPage >= filesData.pagination.pages || loading}
>
下一页
</Button>
</div>
</div>
</>
)}
</CardContent>
</Card>
</TabsContent>
</Tabs>
);
}
|
281677160/openwrt-package
| 3,659
|
luci-app-passwall/luasrc/passwall/util_trojan.lua
|
module("luci.passwall.util_trojan", package.seeall)
local api = require "luci.passwall.api"
local uci = api.uci
local json = api.jsonc
function gen_config_server(node)
local cipher = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA"
local cipher13 = "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384"
local config = {
run_type = "server",
local_addr = "::",
local_port = tonumber(node.port),
remote_addr = (node.remote_enable == "1" and node.remote_address) and node.remote_address or nil,
remote_port = (node.remote_enable == "1" and node.remote_port) and tonumber(node.remote_port) or nil,
password = node.uuid,
log_level = (node.log and node.log == "1") and tonumber(node.loglevel) or 5,
ssl = {
cert = node.tls_certificateFile,
key = node.tls_keyFile,
key_password = "",
cipher = cipher,
cipher_tls13 = cipher13,
prefer_server_cipher = true,
reuse_session = true,
session_ticket = (node.tls_sessionTicket == "1") and true or false,
session_timeout = 600,
plain_http_response = "",
curves = "",
dhparam = ""
},
tcp = {
prefer_ipv4 = false,
no_delay = true,
keep_alive = true,
reuse_port = false,
fast_open = (node.tcp_fast_open and node.tcp_fast_open == "1") and true or false,
fast_open_qlen = 20
}
}
return config
end
function gen_config(var)
local node_id = var["-node"]
if not node_id then
print("-node 不能为空")
return
end
local node = uci:get_all("passwall", node_id)
local run_type = var["-run_type"]
local local_addr = var["-local_addr"]
local local_port = var["-local_port"]
local server_host = var["-server_host"] or node.address
local server_port = var["-server_port"] or node.port
local loglevel = var["-loglevel"] or 2
local cipher = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA"
local cipher13 = "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384"
if api.is_ipv6(server_host) then
server_host = api.get_ipv6_only(server_host)
end
local server = server_host
local trojan = {
run_type = run_type,
local_addr = local_addr,
local_port = tonumber(local_port),
remote_addr = server,
remote_port = tonumber(server_port),
password = {node.password},
log_level = tonumber(loglevel),
ssl = {
verify = (node.tls_allowInsecure ~= "1") and true or false,
verify_hostname = true,
cert = nil,
cipher = cipher,
cipher_tls13 = cipher13,
sni = node.tls_serverName or server,
alpn = {"h2", "http/1.1"},
reuse_session = true,
session_ticket = (node.tls_sessionTicket and node.tls_sessionTicket == "1") and true or false,
curves = ""
},
udp_timeout = 60,
tcp = {
use_tproxy = (node.type == "Trojan-Plus" and var["-use_tproxy"]) and true or nil,
no_delay = true,
keep_alive = true,
reuse_port = true,
fast_open = (node.tcp_fast_open == "true") and true or false,
fast_open_qlen = 20
}
}
return json.stringify(trojan, 1)
end
_G.gen_config = gen_config
if arg[1] then
local func =_G[arg[1]]
if func then
print(func(api.get_function_args(arg)))
end
end
|
2977094657/ZsxqCrawler
| 14,538
|
frontend/src/components/GroupSelector.tsx
|
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Users, MessageSquare, Crown, UserCog, RefreshCw } from 'lucide-react';
import { apiClient, Group, GroupStats, AccountSelf } from '@/lib/api';
import { toast } from 'sonner';
import SafeImage from './SafeImage';
import '../styles/group-selector.css';
interface GroupSelectorProps {
onGroupSelected: (group: Group) => void;
}
export default function GroupSelector({ onGroupSelected }: GroupSelectorProps) {
const router = useRouter();
const [groups, setGroups] = useState<Group[]>([]);
const [groupStats, setGroupStats] = useState<Record<number, GroupStats>>({});
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [retryCount, setRetryCount] = useState(0);
const [isRetrying, setIsRetrying] = useState(false);
const [accountSelfMap, setAccountSelfMap] = useState<Record<number, AccountSelf | null>>({});
useEffect(() => {
loadGroups();
}, []);
const loadGroups = async (currentRetryCount = 0) => {
try {
if (currentRetryCount === 0) {
setLoading(true);
setError(null);
setRetryCount(0);
setIsRetrying(false);
} else {
setIsRetrying(true);
setRetryCount(currentRetryCount);
}
const data = await apiClient.getGroups();
// 检查返回数据(允许为空,显示空态,不再抛错)
setGroups(data.groups);
// 并发拉取每个群组的所属账号用户信息(头像/昵称等)
try {
const selfPromises = data.groups.map(async (group: Group) => {
try {
const res = await apiClient.getGroupAccountSelf(group.group_id);
return { groupId: group.group_id, self: (res as any)?.self || null };
} catch {
return { groupId: group.group_id, self: null };
}
});
const selfResults = await Promise.all(selfPromises);
const selfMap: Record<number, AccountSelf | null> = {};
selfResults.forEach(({ groupId, self }) => {
selfMap[groupId] = self;
});
setAccountSelfMap(selfMap);
} catch (e) {
// 忽略单独失败
console.warn('加载群组账号用户信息失败:', e);
}
// 加载每个群组的统计信息
const statsPromises = data.groups.map(async (group: Group) => {
try {
const stats = await apiClient.getGroupStats(group.group_id);
return { groupId: group.group_id, stats };
} catch (error) {
console.warn(`获取群组 ${group.group_id} 统计信息失败:`, error);
return { groupId: group.group_id, stats: null };
}
});
const statsResults = await Promise.all(statsPromises);
const statsMap: Record<number, GroupStats> = {};
statsResults.forEach(({ groupId, stats }) => {
if (stats) {
statsMap[groupId] = stats;
}
});
setGroupStats(statsMap);
// 成功获取数据,重置状态
setError(null);
setRetryCount(0);
setIsRetrying(false);
setLoading(false);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : '加载群组列表失败';
// 如果是API保护机制导致的错误,持续重试
if (errorMessage.includes('未知错误') || errorMessage.includes('空数据') || errorMessage.includes('反爬虫')) {
const nextRetryCount = currentRetryCount + 1;
const delay = Math.min(1000 + (nextRetryCount * 500), 5000); // 递增延迟,最大5秒
console.log(`群组列表加载失败,正在重试 (第${nextRetryCount}次)...`);
setTimeout(() => {
loadGroups(nextRetryCount);
}, delay);
return;
}
// 其他错误,停止重试
setError(errorMessage);
setIsRetrying(false);
setLoading(false);
}
};
const handleRefresh = async () => {
try {
await apiClient.refreshLocalGroups();
await loadGroups(0);
toast.success('已刷新本地群目录');
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
toast.error(`刷新失败: ${msg}`);
}
};
const formatDate = (dateString?: string) => {
if (!dateString) return '';
try {
return new Date(dateString).toLocaleDateString('zh-CN');
} catch {
return '';
}
};
const getGradientByType = (type: string) => {
switch (type) {
case 'private':
return 'from-purple-400 to-pink-500';
case 'public':
return 'from-blue-400 to-cyan-500';
default:
return 'from-gray-400 to-gray-600';
}
};
// 判断是否即将过期(过期前一个月)
const isExpiringWithinMonth = (expiryTime?: string) => {
if (!expiryTime) return false;
const expiryDate = new Date(expiryTime);
const now = new Date();
const oneMonthFromNow = new Date();
oneMonthFromNow.setMonth(now.getMonth() + 1);
return expiryDate <= oneMonthFromNow && expiryDate > now;
};
if (loading || isRetrying) {
return (
<div className="min-h-screen bg-background">
<div className="container mx-auto p-6">
<div className="mb-8">
<h1 className="text-4xl font-bold mb-2">🌟 知识星球数据采集器</h1>
<p className="text-muted-foreground">
{isRetrying ? '正在重试获取群组列表...' : '正在加载您的知识星球群组...'}
</p>
</div>
<div className="flex items-center justify-center py-12">
<div className="text-center">
<Progress value={undefined} className="w-64 mb-4" />
<p className="text-muted-foreground">
{isRetrying ? `正在重试... (第${retryCount}次)` : '加载群组列表中...'}
</p>
{isRetrying && (
<p className="text-xs text-gray-400 mt-2">
检测到API防护机制,正在自动重试获取数据
</p>
)}
</div>
</div>
</div>
</div>
);
}
if (error) {
return (
<div className="min-h-screen bg-background">
<div className="container mx-auto p-6">
<div className="mb-8">
<h1 className="text-4xl font-bold mb-2">🌟 知识星球数据采集器</h1>
<p className="text-muted-foreground">
加载群组列表时出现错误
</p>
</div>
<Card className="max-w-md mx-auto">
<CardHeader>
<CardTitle className="text-red-600">加载失败</CardTitle>
<CardDescription>无法获取群组列表</CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-4">{error}</p>
<Button onClick={loadGroups} className="w-full">
重试
</Button>
</CardContent>
</Card>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-background">
<div className="container mx-auto p-6">
<div className="mb-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-4xl font-bold mb-2">🌟 知识星球数据采集器</h1>
<p className="text-muted-foreground">
选择要操作的知识星球群组
</p>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
onClick={handleRefresh}
className="flex items-center gap-2"
>
<RefreshCw className="h-4 w-4" />
刷新本地群
</Button>
<Button
variant="outline"
onClick={() => router.push('/accounts')}
className="flex items-center gap-2"
>
<UserCog className="h-4 w-4" />
账号管理
</Button>
</div>
</div>
</div>
{/* 群组统计 */}
<div className="mb-6">
<p className="text-sm text-muted-foreground">
共 {groups.length} 个群组
</p>
</div>
{/* 群组网格 */}
{groups.length === 0 ? (
<Card className="max-w-md mx-auto border border-gray-200 shadow-none">
<CardContent className="pt-6">
<div className="text-center">
<p className="text-muted-foreground">
暂无可访问的群组
</p>
</div>
</CardContent>
</Card>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{groups.map((group) => {
const stats = groupStats[group.group_id];
return (
<Card
key={group.group_id}
className="cursor-pointer border border-gray-200 hover:border-gray-300 transition-all duration-200 shadow-none hover:shadow-sm"
onClick={() => router.push(`/groups/${group.group_id}`)}
>
<CardContent className="p-4">
{/* 群组头像/背景图 */}
<div className="mb-4">
<SafeImage
src={group.background_url}
alt={group.name}
className="w-full h-32 rounded-lg object-cover"
fallbackClassName="w-full h-32 rounded-lg"
fallbackText={group.name.slice(0, 2)}
fallbackGradient={getGradientByType(group.type)}
/>
</div>
{/* 群组名称 */}
<h3 className="text-lg font-semibold text-gray-900 line-clamp-2 mb-3 min-h-[3.5rem]">
{group.name}
</h3>
{/* 统计信息 */}
<div className="space-y-2 mb-4">
<div className="flex items-center justify-between text-sm">
{/* 群主信息 */}
{group.owner && (
<div className="flex items-center gap-1 text-gray-600">
<Crown className="h-4 w-4" />
<span className="truncate">{group.owner.name}</span>
</div>
)}
{/* 话题数量 */}
{stats && (
<div className="flex items-center gap-1 text-gray-600">
<MessageSquare className="h-4 w-4" />
<span>{stats.topics_count || 0}</span>
</div>
)}
</div>
{/* 所属账号标记(头像 + 名称) */}
<div className="flex items-center gap-2 text-xs text-gray-600">
{accountSelfMap[group.group_id]?.avatar_url ? (
<img
src={apiClient.getProxyImageUrl(accountSelfMap[group.group_id]!.avatar_url!)}
alt={accountSelfMap[group.group_id]?.name || ''}
className="w-5 h-5 rounded-full"
onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = 'none'; }}
/>
) : (
<div className="w-5 h-5 rounded-full bg-gray-200" />
)}
<span className="truncate">
{accountSelfMap[group.group_id]?.name ||
(group.account?.name || group.account?.id) ||
'默认账号'}
</span>
</div>
</div>
{/* 类型标识和状态 */}
<div className="flex items-center justify-between">
{/* 根据付费状态和过期情况显示不同颜色 */}
{group.type === 'pay' ? (
// 付费群组:检查是否过期或即将过期
group.status === 'expired' ? (
<Badge variant="destructive" className="text-xs">
{group.is_trial ? '试用已过期' : '付费已过期'}
</Badge>
) : isExpiringWithinMonth(group.expiry_time) ? (
<Badge variant="outline" className="text-xs text-yellow-600 border-yellow-200">
{group.is_trial ? '试用即将过期' : '付费即将过期'}
</Badge>
) : (
<Badge className={`text-xs ${group.is_trial ? 'bg-purple-600 hover:bg-purple-700' : 'bg-green-600 hover:bg-green-700'}`}>
{group.is_trial ? '试用中' : '付费'}
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs">
{group.type === 'free' ? '免费' : group.type}
</Badge>
)}
{/* 来源标签 */}
<div className="flex items-center gap-1">
{group.source?.includes('account') && (
<Badge variant="secondary" className="text-xs">账号</Badge>
)}
{group.source?.includes('local') && (
<Badge variant="outline" className="text-xs">本地</Badge>
)}
</div>
</div>
{/* 时间信息 */}
<div className="mt-3 pt-3 border-t border-gray-100">
<div className="space-y-1 text-xs text-gray-500">
{group.join_time && (
<div>
加入时间: {formatDate(group.join_time)}
</div>
)}
{group.expiry_time && (
<div className={
group.status === 'expiring_soon' ? 'text-yellow-600' :
group.status === 'expired' ? 'text-red-600' : ''
}>
{group.is_trial ? '试用' : '会员'}过期时间: {formatDate(group.expiry_time)}
</div>
)}
</div>
</div>
</CardContent>
</Card>
);
})}
</div>
)}
</div>
</div>
);
}
|
2977094657/ZsxqCrawler
| 9,805
|
frontend/src/components/TaskPanel.tsx
|
'use client';
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { apiClient, Task } from '@/lib/api';
export default function TaskPanel() {
const [tasks, setTasks] = useState<Task[]>([]);
const [loading, setLoading] = useState(false);
const [autoRefresh, setAutoRefresh] = useState(true);
useEffect(() => {
loadTasks();
}, []);
useEffect(() => {
if (!autoRefresh) return;
const interval = setInterval(() => {
loadTasks();
}, 3000); // 每3秒刷新一次
return () => clearInterval(interval);
}, [autoRefresh]);
const loadTasks = async () => {
try {
setLoading(true);
const data = await apiClient.getTasks();
setTasks(data.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()));
} catch (error) {
console.error('加载任务列表失败:', error);
} finally {
setLoading(false);
}
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'pending':
return <Badge className="bg-gray-100 text-gray-800">⏳ 等待中</Badge>;
case 'running':
return <Badge className="bg-blue-100 text-blue-800">🔄 运行中</Badge>;
case 'completed':
return <Badge className="bg-green-100 text-green-800">✅ 已完成</Badge>;
case 'failed':
return <Badge className="bg-red-100 text-red-800">❌ 失败</Badge>;
default:
return <Badge variant="secondary">{status}</Badge>;
}
};
const getTaskTypeLabel = (type: string) => {
switch (type) {
case 'crawl_latest':
return '🆕 获取最新记录';
case 'crawl_historical':
return '📚 增量爬取历史';
case 'crawl_all':
return '🔄 全量爬取';
case 'collect_files':
return '📋 收集文件列表';
case 'download_files':
return '⬇️ 下载文件';
case 'crawl_time_range':
return '🗓️ 按时间区间爬取';
default:
return type;
}
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString('zh-CN');
};
const formatDuration = (startTime: string, endTime?: string) => {
const start = new Date(startTime).getTime();
const end = endTime ? new Date(endTime).getTime() : Date.now();
const duration = Math.floor((end - start) / 1000);
if (duration < 60) {
return `${duration}秒`;
} else if (duration < 3600) {
return `${Math.floor(duration / 60)}分${duration % 60}秒`;
} else {
const hours = Math.floor(duration / 3600);
const minutes = Math.floor((duration % 3600) / 60);
return `${hours}小时${minutes}分`;
}
};
const getRunningTasks = () => tasks.filter(task => task.status === 'running');
const getCompletedTasks = () => tasks.filter(task => task.status === 'completed');
const getFailedTasks = () => tasks.filter(task => task.status === 'failed');
return (
<div className="space-y-6">
{/* 任务统计概览 */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<Card className="border border-gray-200 shadow-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">总任务数</CardTitle>
<Badge variant="secondary">📊</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{tasks.length}</div>
<p className="text-xs text-muted-foreground">所有任务</p>
</CardContent>
</Card>
<Card className="border border-gray-200 shadow-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">运行中</CardTitle>
<Badge variant="secondary" className="bg-blue-100 text-blue-800">🔄</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-blue-600">{getRunningTasks().length}</div>
<p className="text-xs text-muted-foreground">正在执行</p>
</CardContent>
</Card>
<Card className="border border-gray-200 shadow-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">已完成</CardTitle>
<Badge variant="secondary" className="bg-green-100 text-green-800">✅</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-green-600">{getCompletedTasks().length}</div>
<p className="text-xs text-muted-foreground">执行成功</p>
</CardContent>
</Card>
<Card className="border border-gray-200 shadow-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">失败</CardTitle>
<Badge variant="secondary" className="bg-red-100 text-red-800">❌</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-red-600">{getFailedTasks().length}</div>
<p className="text-xs text-muted-foreground">需要处理</p>
</CardContent>
</Card>
</div>
{/* 任务列表 */}
<Card className="border border-gray-200 shadow-none">
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>任务列表</CardTitle>
<CardDescription>查看所有任务的执行状态和结果</CardDescription>
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setAutoRefresh(!autoRefresh)}
>
{autoRefresh ? '🔄 自动刷新' : '⏸️ 手动刷新'}
</Button>
<Button
variant="outline"
size="sm"
onClick={loadTasks}
disabled={loading}
>
{loading ? '刷新中...' : '立即刷新'}
</Button>
</div>
</div>
</CardHeader>
<CardContent>
{tasks.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
暂无任务记录
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>任务类型</TableHead>
<TableHead>状态</TableHead>
<TableHead>消息</TableHead>
<TableHead>创建时间</TableHead>
<TableHead>耗时</TableHead>
<TableHead>结果</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{tasks.map((task) => (
<TableRow key={task.task_id}>
<TableCell>
<div className="font-medium">
{getTaskTypeLabel(task.type)}
</div>
<div className="text-xs text-muted-foreground">
{task.task_id}
</div>
</TableCell>
<TableCell>{getStatusBadge(task.status)}</TableCell>
<TableCell className="max-w-md">
<div className="truncate" title={task.message}>
{task.message}
</div>
</TableCell>
<TableCell>{formatDate(task.created_at)}</TableCell>
<TableCell>
{formatDuration(task.created_at, task.status === 'running' ? undefined : task.updated_at)}
</TableCell>
<TableCell>
{task.result ? (
<div className="text-xs">
{task.result.new_topics && (
<div>新增: {task.result.new_topics}</div>
)}
{task.result.updated_topics && (
<div>更新: {task.result.updated_topics}</div>
)}
{task.result.downloaded_files && (
<div>下载: {task.result.downloaded_files}</div>
)}
</div>
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
{/* 运行中任务的进度显示 */}
{getRunningTasks().length > 0 && (
<Card className="border border-gray-200 shadow-none">
<CardHeader>
<CardTitle>运行中的任务</CardTitle>
<CardDescription>正在执行的任务详情</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{getRunningTasks().map((task) => (
<div key={task.task_id} className="space-y-2">
<div className="flex items-center justify-between">
<span className="font-medium">{getTaskTypeLabel(task.type)}</span>
<Badge className="bg-blue-100 text-blue-800">运行中</Badge>
</div>
<Progress value={undefined} className="w-full" />
<p className="text-sm text-muted-foreground">{task.message}</p>
</div>
))}
</CardContent>
</Card>
)}
</div>
);
}
|
2977094657/ZsxqCrawler
| 8,366
|
frontend/src/components/ConfigPanel.tsx
|
'use client';
import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { apiClient } from '@/lib/api';
import { toast } from 'sonner';
interface ConfigPanelProps {
onConfigSaved: () => void;
}
export default function ConfigPanel({ onConfigSaved }: ConfigPanelProps) {
const [loading, setLoading] = useState(false);
const [cookie, setCookie] = useState('');
const [groupId, setGroupId] = useState('');
const [showInstructions, setShowInstructions] = useState(false);
const handleSaveConfig = async () => {
if (!cookie.trim() || !groupId.trim()) {
toast.error('请填写完整的Cookie和群组ID');
return;
}
try {
setLoading(true);
const response = await apiClient.updateConfig({
cookie: cookie.trim(),
group_id: groupId.trim(),
db_path: 'zsxq_interactive.db'
});
toast.success('配置保存成功!');
onConfigSaved();
} catch (error) {
toast.error(`配置保存失败: ${error instanceof Error ? error.message : '未知错误'}`);
} finally {
setLoading(false);
}
};
const extractGroupIdFromUrl = (url: string) => {
const match = url.match(/group\/(\d+)/);
if (match) {
setGroupId(match[1]);
toast.success('已自动提取群组ID');
} else {
toast.error('无法从URL中提取群组ID,请检查URL格式');
}
};
return (
<div className="min-h-screen bg-background">
<div className="container mx-auto p-6">
<div className="mb-8">
<h1 className="text-4xl font-bold mb-2">🌟 知识星球数据采集器</h1>
<p className="text-muted-foreground">
请配置您的知识星球认证信息以开始使用
</p>
</div>
<div className="max-w-2xl mx-auto space-y-6">
{/* 配置表单 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Badge variant="secondary">⚙️</Badge>
配置认证信息
</CardTitle>
<CardDescription>
填写您的知识星球Cookie和群组ID
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="cookie">知识星球Cookie</Label>
<Textarea
id="cookie"
placeholder="请粘贴完整的Cookie值..."
value={cookie}
onChange={(e) => setCookie(e.target.value)}
rows={3}
/>
<p className="text-xs text-muted-foreground">
从浏览器开发者工具的Network标签中复制完整的Cookie值
</p>
</div>
<div className="space-y-2">
<Label htmlFor="group-id">群组ID</Label>
<div className="flex gap-2">
<Input
id="group-id"
placeholder="例如: 123456789"
value={groupId}
onChange={(e) => setGroupId(e.target.value)}
/>
<Button
variant="outline"
onClick={() => {
const url = prompt('请输入知识星球群组页面URL:');
if (url) extractGroupIdFromUrl(url);
}}
>
从URL提取
</Button>
</div>
<p className="text-xs text-muted-foreground">
从知识星球群组页面URL中提取的数字ID
</p>
</div>
<div className="flex gap-2">
<Button
onClick={handleSaveConfig}
disabled={loading || !cookie.trim() || !groupId.trim()}
className="flex-1"
>
{loading ? '保存中...' : '保存配置'}
</Button>
<Button
variant="outline"
onClick={() => setShowInstructions(true)}
>
📖 查看详细说明
</Button>
</div>
</CardContent>
</Card>
{/* 快速测试 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Badge variant="secondary">🧪</Badge>
测试配置
</CardTitle>
<CardDescription>
保存配置后可以测试连接是否正常
</CardDescription>
</CardHeader>
<CardContent>
<Button
variant="outline"
onClick={() => window.open('http://localhost:8000/docs', '_blank')}
className="w-full"
>
📖 查看API文档
</Button>
</CardContent>
</Card>
</div>
{/* 详细说明对话框 */}
<AlertDialog open={showInstructions} onOpenChange={setShowInstructions}>
<AlertDialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
<AlertDialogHeader>
<AlertDialogTitle>📖 详细配置说明</AlertDialogTitle>
<AlertDialogDescription>
按照以下步骤获取所需的认证信息
</AlertDialogDescription>
</AlertDialogHeader>
<div className="space-y-6">
{/* Cookie获取说明 */}
<div className="space-y-3">
<h3 className="text-lg font-semibold">1. 获取Cookie</h3>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 space-y-2">
<ol className="list-decimal list-inside space-y-2 text-sm">
<li>使用Chrome或Edge浏览器访问 <code className="bg-gray-100 px-1 rounded">https://wx.zsxq.com/</code></li>
<li>登录您的知识星球账号</li>
<li>按 <kbd className="bg-gray-200 px-2 py-1 rounded">F12</kbd> 打开开发者工具</li>
<li>切换到 <strong>Network</strong> (网络) 标签</li>
<li>刷新页面或点击任意链接</li>
<li>在网络请求列表中找到任意一个请求(通常是API请求)</li>
<li>点击该请求,在右侧面板中找到 <strong>Request Headers</strong></li>
<li>找到 <code className="bg-gray-100 px-1 rounded">Cookie:</code> 行,复制完整的值</li>
</ol>
</div>
</div>
{/* 群组ID获取说明 */}
<div className="space-y-3">
<h3 className="text-lg font-semibold">2. 获取群组ID</h3>
<div className="bg-green-50 border border-green-200 rounded-lg p-4 space-y-2">
<ol className="list-decimal list-inside space-y-2 text-sm">
<li>在知识星球中进入您要采集的目标群组</li>
<li>查看浏览器地址栏的URL</li>
<li>URL格式类似:<code className="bg-gray-100 px-1 rounded">https://wx.zsxq.com/group/123456789</code></li>
<li>其中的数字部分 <code className="bg-gray-100 px-1 rounded">123456789</code> 就是群组ID</li>
<li>或者点击上方的"从URL提取"按钮,粘贴完整URL自动提取</li>
</ol>
</div>
</div>
{/* 注意事项 */}
<div className="space-y-3">
<h3 className="text-lg font-semibold">⚠️ 注意事项</h3>
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 space-y-2">
<ul className="list-disc list-inside space-y-1 text-sm">
<li>Cookie包含您的登录凭证,请妥善保管,不要泄露给他人</li>
<li>Cookie有时效性,如果采集失败可能需要重新获取</li>
<li>确保您有权限访问目标知识星球群组</li>
<li>请遵守知识星球的使用条款和相关法律法规</li>
<li>本工具仅供学习和研究使用</li>
</ul>
</div>
</div>
</div>
<AlertDialogFooter>
<AlertDialogAction onClick={() => setShowInstructions(false)}>
我知道了
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
);
}
|
2951121599/Bili-Insight
| 11,054
|
chrome-extension/scripts/wordcloud2.min.js
|
"use strict";window.setImmediate||(window.setImmediate=window.msSetImmediate||window.webkitSetImmediate||window.mozSetImmediate||window.oSetImmediate||function(){if(!window.postMessage||!window.addEventListener)return null;var a=[void 0],r="zero-timeout-message";return window.addEventListener("message",function(t){"string"==typeof t.data&&t.data.substr(0,r.length)===r&&(t.stopImmediatePropagation(),t=parseInt(t.data.substr(r.length),36),a[t]&&(a[t](),a[t]=void 0))},!0),window.clearImmediate=function(t){a[t]&&(a[t]=void 0)},function(t){var e=a.length;return a.push(t),window.postMessage(r+e.toString(36),"*"),e}}()||function(t){window.setTimeout(t,0)}),window.clearImmediate||(window.clearImmediate=window.msClearImmediate||window.webkitClearImmediate||window.mozClearImmediate||window.oClearImmediate||function(t){window.clearTimeout(t)}),function(t){function e(I,t){if(d){var u=Math.floor(Math.random()*Date.now());(I=!Array.isArray(I)?[I]:I).forEach(function(t,e){if("string"==typeof t){if(I[e]=document.getElementById(t),!I[e])throw new Error("The element id specified is not found.")}else if(!t.tagName&&!t.appendChild)throw new Error("You must pass valid HTML elements, or ID of the element.")});var e,k={list:[],fontFamily:'"Trebuchet MS", "Heiti TC", "微軟正黑體", "Arial Unicode MS", "Droid Fallback Sans", sans-serif',fontWeight:"normal",color:"random-dark",minSize:0,weightFactor:1,clearCanvas:!0,backgroundColor:"#fff",gridSize:8,drawOutOfBound:!1,shrinkToFit:!1,origin:null,drawMask:!1,maskColor:"rgba(255,0,0,0.3)",maskGapWidth:.3,wait:0,abortThreshold:0,abort:function(){},minRotation:-Math.PI/2,maxRotation:Math.PI/2,rotationSteps:0,shuffle:!0,rotateRatio:.1,shape:"circle",ellipticity:.65,classes:null,hover:null,click:null};if(t)for(var a in t)a in k&&(k[a]=t[a]);if("function"!=typeof k.weightFactor&&(e=k.weightFactor,k.weightFactor=function(t){return t*e}),"function"!=typeof k.shape)switch(k.shape){case"circle":default:k.shape="circle";break;case"cardioid":k.shape=function(t){return 1-Math.sin(t)};break;case"diamond":k.shape=function(t){t%=2*Math.PI/4;return 1/(Math.cos(t)+Math.sin(t))};break;case"square":k.shape=function(t){return Math.min(1/Math.abs(Math.cos(t)),1/Math.abs(Math.sin(t)))};break;case"triangle-forward":k.shape=function(t){t%=2*Math.PI/3;return 1/(Math.cos(t)+Math.sqrt(3)*Math.sin(t))};break;case"triangle":case"triangle-upright":k.shape=function(t){t=(t+3*Math.PI/2)%(2*Math.PI/3);return 1/(Math.cos(t)+Math.sqrt(3)*Math.sin(t))};break;case"pentagon":k.shape=function(t){t=(t+.955)%(2*Math.PI/5);return 1/(Math.cos(t)+.726543*Math.sin(t))};break;case"star":k.shape=function(t){var e=(t+.955)%(2*Math.PI/10);return 0<=(t+.955)%(2*Math.PI/5)-2*Math.PI/10?1/(Math.cos(2*Math.PI/10-e)+3.07768*Math.sin(2*Math.PI/10-e)):1/(Math.cos(e)+3.07768*Math.sin(e))}}k.gridSize=Math.max(Math.floor(k.gridSize),4);var C,S,E,m,F,w,P,R,O=k.gridSize,g=O-k.maskGapWidth,i=Math.abs(k.maxRotation-k.minRotation),o=Math.abs(Math.floor(k.rotationSteps)),s=Math.min(k.maxRotation,k.minRotation);switch(k.color){case"random-dark":P=function(){return n(10,50)};break;case"random-light":P=function(){return n(50,90)};break;default:"function"==typeof k.color&&(P=k.color)}"function"==typeof k.fontWeight&&(R=k.fontWeight);var A=null;"function"==typeof k.classes&&(A=k.classes);var v,M=!1,p=[],r=function(t){var e=t.currentTarget,a=e.getBoundingClientRect(),t=t.touches?(r=t.touches[0].clientX,t.touches[0].clientY):(r=t.clientX,t.clientY),r=r-a.left,t=t-a.top,r=Math.floor(r*(e.width/a.width||1)/O),a=Math.floor(t*(e.height/a.height||1)/O);return p[r][a]},x=function(t){var e=r(t);v!==e&&((v=e)?k.hover(e.item,e.dimension,t):k.hover(void 0,void 0,t))},b=function(t){var e=r(t);e&&(k.click(e.item,e.dimension,t),t.preventDefault())},l=[],z=function(){return 0<k.abortThreshold&&(new Date).getTime()-w>k.abortThreshold},W=function(t,e,a,r,i,o){var n,s,l=i.occupied,d=k.drawMask;d&&((n=I[0].getContext("2d")).save(),n.fillStyle=k.maskColor),M&&(s={x:(t+(i=i.bounds)[3])*O,y:(e+i[0])*O,w:(i[1]-i[3]+1)*O,h:(i[2]-i[0]+1)*O});for(var f,c,h,u=l.length;u--;){var m=t+l[u][0],w=e+l[u][1];S<=m||E<=w||m<0||w<0||(f=w,c=d,h=s,w=o,S<=(m=m)||E<=f||m<0||f<0||(C[m][f]=!1,c&&I[0].getContext("2d").fillRect(m*O,f*O,g,g),M&&(p[m][f]={item:w,dimension:h})))}d&&n.restore()},T=function t(n){var v,M,p;Array.isArray(n)?(v=n[0],M=n[1]):(v=n.word,M=n.weight,p=n.attributes);var x=0===k.rotateRatio||Math.random()>k.rotateRatio?0:0===i?s:0<o?s+Math.floor(Math.random()*o)*i/(o-1):s+Math.random()*i,b=function(t){if(Array.isArray(t)){t=t.slice();return t.splice(0,2),t}return[]}(n),T=function(t,e,a,r){var i=k.weightFactor(e);if(i<=k.minSize)return!1;var o=1;i<L&&(o=function(){for(var t=2;t*i<L;)t+=2;return t}());var n=R?R(t,e,i,r):k.fontWeight,s=document.createElement("canvas"),l=s.getContext("2d",{willReadFrequently:!0});l.font=n+" "+(i*o).toString(10)+"px "+k.fontFamily;var d=l.measureText(t).width/o,f=Math.max(i*o,l.measureText("m").width,l.measureText("W").width)/o,c=d+2*f,h=3*f,e=Math.ceil(c/O),r=Math.ceil(h/O),c=e*O,h=r*O,e=-d/2,r=.4*-f,u=Math.ceil((c*Math.abs(Math.sin(a))+h*Math.abs(Math.cos(a)))/O),c=Math.ceil((c*Math.abs(Math.cos(a))+h*Math.abs(Math.sin(a)))/O),m=c*O,h=u*O;s.setAttribute("width",m),s.setAttribute("height",h),l.scale(1/o,1/o),l.translate(m*o/2,h*o/2),l.rotate(-a),l.font=n+" "+(i*o).toString(10)+"px "+k.fontFamily,l.fillStyle="#000",l.textBaseline="middle",l.fillText(t,e*o,(r+.5*i)*o);var w=l.getImageData(0,0,m,h).data;if(z())return!1;for(var g,v,M,p=[],x=c,b=[u/2,c/2,u/2,c/2];x--;)for(g=u;g--;){M=O;t:for(;M--;)for(v=O;v--;)if(w[4*((g*O+M)*m+(x*O+v))+3]){p.push([x,g]),x<b[3]&&(b[3]=x),x>b[1]&&(b[1]=x),g<b[0]&&(b[0]=g),g>b[2]&&(b[2]=g);break t}0}return{mu:o,occupied:p,bounds:b,gw:c,gh:u,fillTextOffsetX:e,fillTextOffsetY:r,fillTextWidth:d,fillTextHeight:f,fontSize:i}}(v,M,x,b);if(!T)return!1;if(z())return!1;if(!k.drawOutOfBound&&!k.shrinkToFit){var e=T.bounds;if(e[1]-e[3]+1>S||e[2]-e[0]+1>E)return!1}for(var y=F+1,a=function(t){var s,l,d,f,e,a,r,c,h,u,m,w,g,i=Math.floor(t[0]-T.gw/2),o=Math.floor(t[1]-T.gh/2);T.gw,T.gh;return!!function(t,e,a){for(var r=a.length;r--;){var i=t+a[r][0],o=e+a[r][1];if(S<=i||E<=o||i<0||o<0){if(!k.drawOutOfBound)return!1}else if(!C[i][o])return!1}return!0}(i,o,T.occupied)&&(s=i,l=o,d=T,f=v,e=M,a=F-y,r=t[2],c=x,h=p,t=b,u=d.fontSize,m=P?P(f,e,u,a,r,t):k.color,w=R?R(f,e,u,t):k.fontWeight,g=A?A(f,e,u,t):k.classes,I.forEach(function(t){if(t.getContext){var e=t.getContext("2d"),a=d.mu;e.save(),e.scale(1/a,1/a),e.font=w+" "+(u*a).toString(10)+"px "+k.fontFamily,e.fillStyle=m,e.translate((s+d.gw/2)*O*a,(l+d.gh/2)*O*a),0!==c&&e.rotate(-c),e.textBaseline="middle",e.fillText(f,d.fillTextOffsetX*a,(d.fillTextOffsetY+.5*u)*a),e.restore()}else{var r=document.createElement("span"),e="",e="rotate("+-c/Math.PI*180+"deg) ";1!==d.mu&&(e+="translateX(-"+d.fillTextWidth/4+"px) scale("+1/d.mu+")");var i,o={position:"absolute",display:"block",font:w+" "+u*d.mu+"px "+k.fontFamily,left:(s+d.gw/2)*O+d.fillTextOffsetX+"px",top:(l+d.gh/2)*O+d.fillTextOffsetY+"px",width:d.fillTextWidth+"px",height:d.fillTextHeight+"px",lineHeight:u+"px",whiteSpace:"nowrap",transform:e,webkitTransform:e,msTransform:e,transformOrigin:"50% 40%",webkitTransformOrigin:"50% 40%",msTransformOrigin:"50% 40%"};for(i in m&&(o.color=m),r.textContent=f,o)r.style[i]=o[i];if(h)for(var n in h)r.setAttribute(n,h[n]);g&&(r.className+=g),t.appendChild(r)}}),W(i,o,0,0,T,n),!0)};y--;){var r=function(t){if(l[t])return l[t];var e=8*t,a=e,r=[];for(0===t&&r.push([m[0],m[1],0]);a--;){var i=1;"circle"!==k.shape&&(i=k.shape(a/e*2*Math.PI)),r.push([m[0]+t*i*Math.cos(-a/e*2*Math.PI),m[1]+t*i*Math.sin(-a/e*2*Math.PI)*k.ellipticity,a/e*2*Math.PI])}return l[t]=r}(F-y);if(k.shuffle&&function(t){for(var e,a,r=t.length;r;)e=Math.floor(Math.random()*r),a=t[--r],t[r]=t[e],t[e]=a}(r=[].concat(r)),r.some(a))return!0}return!!k.shrinkToFit&&(Array.isArray(n)?n[1]=3*n[1]/4:n.weight=3*n.weight/4,t(n))},y=function(a,t,r){if(t)return!I.some(function(t){var e=new CustomEvent(a,{detail:r||{}});return!t.dispatchEvent(e)},this);I.forEach(function(t){var e=new CustomEvent(a,{detail:r||{}});t.dispatchEvent(e)},this)};!function(){var t,a,e=I[0];if(E=e.getContext?(S=Math.ceil(e.width/O),Math.ceil(e.height/O)):(r=e.getBoundingClientRect(),S=Math.ceil(r.width/O),Math.ceil(r.height/O)),y("wordcloudstart",!0)){if(m=k.origin?[k.origin[0]/O,k.origin[1]/O]:[S/2,E/2],F=Math.floor(Math.sqrt(S*S+E*E)),C=[],!e.getContext||k.clearCanvas)for(I.forEach(function(t){var e;t.getContext?((e=t.getContext("2d")).fillStyle=k.backgroundColor,e.clearRect(0,0,S*(O+1),E*(O+1)),e.fillRect(0,0,S*(O+1),E*(O+1))):(t.textContent="",t.style.backgroundColor=k.backgroundColor,t.style.position="relative")}),l=S;l--;)for(C[l]=[],t=E;t--;)C[l][t]=!0;else{var r=document.createElement("canvas").getContext("2d");r.fillStyle=k.backgroundColor,r.fillRect(0,0,1,1);for(var i,o,n=r.getImageData(0,0,1,1).data,s=e.getContext("2d").getImageData(0,0,S*O,E*O).data,l=S;l--;)for(C[l]=[],t=E;t--;){o=O;t:for(;o--;)for(i=O;i--;)for(d=4;d--;)if(s[4*((t*O+o)*S*O+(l*O+i))+d]!==n[d]){C[l][t]=!1;break t}!1!==C[l][t]&&(C[l][t]=!0)}s=r=n=void 0}if(k.hover||k.click){for(M=!0,l=S+1;l--;)p[l]=[];k.hover&&e.addEventListener("mousemove",x),k.click&&(e.addEventListener("click",b),e.style.webkitTapHighlightColor="rgba(0, 0, 0, 0)"),e.addEventListener("wordcloudstart",function t(){e.removeEventListener("wordcloudstart",t),e.removeEventListener("mousemove",x),e.removeEventListener("click",b),v=void 0})}var d=0,f=0!==k.wait?(a=window.setTimeout,window.clearTimeout):(a=window.setImmediate,window.clearImmediate),c=function(e,a){I.forEach(function(t){t.removeEventListener(e,a)},this)},h=function t(){c("wordcloudstart",t),f(D[u])};!function(e,a){I.forEach(function(t){t.addEventListener(e,a)},this)}("wordcloudstart",h),D[u]=a(function t(){if(d>=k.list.length)return f(D[u]),y("wordcloudstop",!1),c("wordcloudstart",h),void delete D[u];w=(new Date).getTime();var e=T(k.list[d]),e=!y("wordclouddrawn",!0,{item:k.list[d],drawn:e});if(z()||e)return f(D[u]),k.abort(),y("wordcloudabort",!1),y("wordcloudstop",!1),c("wordcloudstart",h),void delete D[u];d++,D[u]=a(t,k.wait)},k.wait)}}()}function n(t,e){return"hsl("+(360*Math.random()).toFixed()+","+(30*Math.random()+70).toFixed()+"%,"+(Math.random()*(e-t)+t).toFixed()+"%)"}}var d=function(){var t=document.createElement("canvas");if(!t||!t.getContext)return!1;t=t.getContext("2d");return!!t&&(!!t.getImageData&&(!!t.fillText&&(!!Array.prototype.some&&!!Array.prototype.push)))}(),L=function(){if(d){for(var t,e,a=document.createElement("canvas").getContext("2d"),r=20;r;){if(a.font=r.toString(10)+"px sans-serif",a.measureText("W").width===t&&a.measureText("m").width===e)return r+1;t=a.measureText("W").width,e=a.measureText("m").width,r--}return 0}}(),D={};e.isSupported=d,e.minFontSize=L,e.stop=function(){if(D)for(var t in D)window.clearImmediate(D[t])},"function"==typeof define&&define.amd?(t.WordCloud=e,define("wordcloud",[],function(){return e})):"undefined"!=typeof module&&module.exports?module.exports=e:t.WordCloud=e}(this);
|
281677160/openwrt-package
| 62,861
|
luci-app-passwall/luasrc/passwall/util_sing-box.lua
|
module("luci.passwall.util_sing-box", package.seeall)
local api = require "luci.passwall.api"
local uci = api.uci
local sys = api.sys
local jsonc = api.jsonc
local appname = "passwall"
local fs = api.fs
local split = api.split
local local_version = api.get_app_version("sing-box"):match("[^v]+")
local version_ge_1_11_0 = api.compare_versions(local_version, ">=", "1.11.0")
local version_ge_1_12_0 = api.compare_versions(local_version, ">=", "1.12.0")
local geosite_all_tag = {}
local geoip_all_tag = {}
local srss_path = "/tmp/etc/" .. appname .."_tmp/srss/"
local function convert_geofile()
if api.compare_versions(local_version, "<", "1.8.0") then
api.log("!!!注意:Sing-Box 版本低,Sing-Box 分流无法启用!请在[组件更新]中更新。")
return
end
local geo_dir = (uci:get(appname, "@global_rules[0]", "v2ray_location_asset") or "/usr/share/v2ray/"):match("^(.*)/")
local geosite_path = geo_dir .. "/geosite.dat"
local geoip_path = geo_dir .. "/geoip.dat"
if not api.finded_com("geoview") then
api.log("!!!注意:缺少 Geoview 组件,Sing-Box 分流无法启用!请在[组件更新]中更新。")
return
else
if api.compare_versions(api.get_app_version("geoview"), "<", "0.1.10") then
api.log("!!!注意:Geoview 组件版本低,Sing-Box 分流无法启用!请在[组件更新]中更新。")
return
end
end
if not fs.access(srss_path) then
fs.mkdir(srss_path)
end
local function convert(file_path, prefix, tags)
if next(tags) and fs.access(file_path) then
local md5_file = srss_path .. prefix .. ".dat.md5"
local new_md5 = sys.exec("md5sum " .. file_path .. " 2>/dev/null | awk '{print $1}'"):gsub("\n", "")
local old_md5 = sys.exec("[ -f " .. md5_file .. " ] && head -n 1 " .. md5_file .. " | tr -d ' \t\n' || echo ''")
if new_md5 ~= "" and new_md5 ~= old_md5 then
sys.call("printf '%s' " .. new_md5 .. " > " .. md5_file)
sys.call("rm -rf " .. srss_path .. prefix .. "-*.srs" )
end
for k in pairs(tags) do
local srs_file = srss_path .. prefix .. "-" .. k .. ".srs"
if not fs.access(srs_file) then
local cmd = string.format("geoview -type %s -action convert -input '%s' -list '%s' -output '%s' -lowmem=true",
prefix, file_path, k, srs_file)
sys.exec(cmd)
--local status = fs.access(srs_file) and "成功。" or "失败!"
--api.log(string.format(" - 转换 %s:%s ... %s", prefix, k, status))
end
end
end
end
--api.log("Sing-Box 规则集转换:")
convert(geosite_path, "geosite", geosite_all_tag)
convert(geoip_path, "geoip", geoip_all_tag)
end
local new_port
local function get_new_port()
if new_port then
new_port = tonumber(sys.exec(string.format("echo -n $(/usr/share/%s/app.sh get_new_port %s tcp)", appname, new_port + 1)))
else
new_port = tonumber(sys.exec(string.format("echo -n $(/usr/share/%s/app.sh get_new_port auto tcp)", appname)))
end
return new_port
end
function gen_outbound(flag, node, tag, proxy_table)
local result = nil
if node then
local node_id = node[".name"]
if tag == nil then
tag = node_id
end
local proxy_tag = nil
local fragment = nil
local record_fragment = nil
local run_socks_instance = true
if proxy_table ~= nil and type(proxy_table) == "table" then
proxy_tag = proxy_table.tag or nil
fragment = proxy_table.fragment or nil
record_fragment = proxy_table.record_fragment or nil
run_socks_instance = proxy_table.run_socks_instance
end
if node.type ~= "sing-box" then
local relay_port = node.port
new_port = get_new_port()
local config_file = string.format("%s_%s_%s.json", flag, tag, new_port)
if tag and node_id and tag ~= node_id then
config_file = string.format("%s_%s_%s_%s.json", flag, tag, node_id, new_port)
end
if run_socks_instance then
sys.call(string.format('/usr/share/%s/app.sh run_socks "%s"> /dev/null',
appname,
string.format("flag=%s node=%s bind=%s socks_port=%s config_file=%s relay_port=%s",
new_port, --flag
node_id, --node
"127.0.0.1", --bind
new_port, --socks port
config_file, --config file
(proxy_tag and relay_port) and tostring(relay_port) or "" --relay port
)
)
)
end
node = {
protocol = "socks",
address = "127.0.0.1",
port = new_port
}
else
if proxy_tag then
node.detour = proxy_tag
end
end
result = {
_id = node_id,
_flag = flag,
_flag_proxy_tag = proxy_tag,
tag = tag,
type = node.protocol,
server = node.address,
server_port = tonumber(node.port),
domain_strategy = node.domain_strategy,
detour = node.detour,
}
if version_ge_1_12_0 then
--https://sing-box.sagernet.org/migration/#migrate-outbound-domain-strategy-option-to-domain-resolver
result.domain_strategy = nil
result.domain_resolver = {
server = "direct",
strategy = (node.domain_strategy and node.domain_strategy ~="") and node.domain_strategy or nil
}
end
local tls = nil
if node.tls == "1" then
local alpn = nil
if node.alpn and node.alpn ~= "default" then
alpn = {}
string.gsub(node.alpn, '[^' .. "," .. ']+', function(w)
table.insert(alpn, w)
end)
end
tls = {
enabled = true,
disable_sni = (node.tls_disable_sni == "1") and true or false, --不要在 ClientHello 中发送服务器名称.
server_name = node.tls_serverName, --用于验证返回证书上的主机名,除非设置不安全。它还包含在 ClientHello 中以支持虚拟主机,除非它是 IP 地址。
insecure = (node.tls_allowInsecure == "1") and true or false, --接受任何服务器证书。
alpn = alpn, --支持的应用层协议协商列表,按优先顺序排列。如果两个对等点都支持 ALPN,则选择的协议将是此列表中的一个,如果没有相互支持的协议则连接将失败。
--min_version = "1.2",
--max_version = "1.3",
fragment = fragment,
record_fragment = record_fragment,
ech = {
enabled = (node.ech == "1") and true or false,
config = node.ech_config and split(node.ech_config:gsub("\\n", "\n"), "\n") or {}
},
utls = {
enabled = (node.utls == "1" or node.reality == "1") and true or false,
fingerprint = node.fingerprint or "chrome"
},
reality = {
enabled = (node.reality == "1") and true or false,
public_key = node.reality_publicKey,
short_id = node.reality_shortId
}
}
end
local mux = nil
if node.mux == "1" then
mux = {
enabled = true,
protocol = node.mux_type or "h2mux",
max_connections = ( (node.tcpbrutal == "1") and 1 ) or tonumber(node.mux_concurrency) or 4,
padding = (node.mux_padding == "1") and true or false,
--min_streams = 4,
--max_streams = 0,
brutal = {
enabled = (node.tcpbrutal == "1") and true or false,
up_mbps = tonumber(node.tcpbrutal_up_mbps) or 10,
down_mbps = tonumber(node.tcpbrutal_down_mbps) or 50,
},
}
end
local v2ray_transport = nil
if node.transport == "tcp" and node.tcp_guise == "http" and (node.tcp_guise_http_host or "") ~= "" then --模拟xray raw(tcp)传输
v2ray_transport = {
type = "http",
host = node.tcp_guise_http_host,
path = node.tcp_guise_http_path and (function()
local first = node.tcp_guise_http_path[1]
return (first == "" or not first) and "/" or first
end)() or "/",
idle_timeout = (node.http_h2_health_check == "1") and node.http_h2_read_idle_timeout or nil,
ping_timeout = (node.http_h2_health_check == "1") and node.http_h2_health_check_timeout or nil,
}
--不强制执行 TLS。如果未配置 TLS,将使用纯 HTTP 1.1。
end
if node.transport == "http" then
v2ray_transport = {
type = "http",
host = node.http_host or {},
path = node.http_path or "/",
idle_timeout = (node.http_h2_health_check == "1") and node.http_h2_read_idle_timeout or nil,
ping_timeout = (node.http_h2_health_check == "1") and node.http_h2_health_check_timeout or nil,
}
--不强制执行 TLS。如果未配置 TLS,将使用纯 HTTP 1.1。
end
if node.transport == "ws" then
v2ray_transport = {
type = "ws",
path = node.ws_path or "/",
headers = (node.ws_host ~= nil) and { Host = node.ws_host } or nil,
max_early_data = tonumber(node.ws_maxEarlyData) or nil,
early_data_header_name = (node.ws_earlyDataHeaderName) and node.ws_earlyDataHeaderName or nil --要与 Xray-core 兼容,请将其设置为 Sec-WebSocket-Protocol。它需要与服务器保持一致。
}
end
if node.transport == "httpupgrade" then
v2ray_transport = {
type = "httpupgrade",
host = node.httpupgrade_host,
path = node.httpupgrade_path or "/",
}
end
if node.transport == "quic" then
v2ray_transport = {
type = "quic"
}
--没有额外的加密支持: 它基本上是重复加密。 并且 Xray-core 在这里与 v2ray-core 不兼容。
end
if node.transport == "grpc" then
v2ray_transport = {
type = "grpc",
service_name = node.grpc_serviceName,
idle_timeout = tonumber(node.grpc_idle_timeout) or nil,
ping_timeout = tonumber(node.grpc_health_check_timeout) or nil,
permit_without_stream = (node.grpc_permit_without_stream == "1") and true or nil,
}
end
local protocol_table = nil
if node.protocol == "socks" then
protocol_table = {
version = "5",
username = (node.username and node.password) and node.username or nil,
password = (node.username and node.password) and node.password or nil,
udp_over_tcp = node.uot == "1" and {
enabled = true,
version = 2
} or nil,
}
end
if node.protocol == "http" then
protocol_table = {
username = (node.username and node.password) and node.username or nil,
password = (node.username and node.password) and node.password or nil,
path = nil,
headers = nil,
tls = tls
}
end
if node.protocol == "shadowsocks" then
protocol_table = {
method = node.method or nil,
password = node.password or "",
plugin = (node.plugin_enabled and node.plugin) or nil,
plugin_opts = (node.plugin_enabled and node.plugin_opts) or nil,
udp_over_tcp = node.uot == "1" and {
enabled = true,
version = 2
} or nil,
multiplex = mux,
}
end
if node.protocol == "trojan" then
protocol_table = {
password = node.password,
tls = tls,
multiplex = mux,
transport = v2ray_transport
}
end
if node.protocol == "vmess" then
protocol_table = {
uuid = node.uuid,
security = node.security,
alter_id = (node.alter_id) and tonumber(node.alter_id) or 0,
global_padding = (node.global_padding == "1") and true or false,
authenticated_length = (node.authenticated_length == "1") and true or false,
tls = tls,
packet_encoding = "", --UDP 包编码。(空):禁用 packetaddr:由 v2ray 5+ 支持 xudp:由 xray 支持
multiplex = mux,
transport = v2ray_transport,
}
end
if node.protocol == "vless" then
protocol_table = {
uuid = node.uuid,
flow = (node.tls == '1' and node.flow) and node.flow or nil,
tls = tls,
packet_encoding = "xudp", --UDP 包编码。(空):禁用 packetaddr:由 v2ray 5+ 支持 xudp:由 xray 支持
multiplex = mux,
transport = v2ray_transport,
}
end
if node.protocol == "wireguard" then
if node.wireguard_reserved then
local bytes = {}
if not node.wireguard_reserved:match("[^%d,]+") then
node.wireguard_reserved:gsub("%d+", function(b)
bytes[#bytes + 1] = tonumber(b)
end)
else
local result = api.bin.b64decode(node.wireguard_reserved)
for i = 1, #result do
bytes[i] = result:byte(i)
end
end
node.wireguard_reserved = #bytes > 0 and bytes or nil
end
protocol_table = {
system_interface = nil,
interface_name = nil,
local_address = node.wireguard_local_address,
private_key = node.wireguard_secret_key,
peer_public_key = node.wireguard_public_key,
pre_shared_key = node.wireguard_preSharedKey,
reserved = node.wireguard_reserved,
mtu = tonumber(node.wireguard_mtu),
}
end
if node.protocol == "hysteria" then
local server_ports = {}
if node.hysteria_hop then
node.hysteria_hop = string.gsub(node.hysteria_hop, "-", ":")
for range in node.hysteria_hop:gmatch("([^,]+)") do
if range:match("^%d+:%d+$") then
table.insert(server_ports, range)
end
end
end
protocol_table = {
server_ports = next(server_ports) and server_ports or nil,
hop_interval = (function()
if not next(server_ports) then return nil end
local v = tonumber((node.hysteria_hop_interval or "30s"):match("^%d+"))
return (v and v >= 5) and (v .. "s") or "30s"
end)(),
up_mbps = tonumber(node.hysteria_up_mbps),
down_mbps = tonumber(node.hysteria_down_mbps),
obfs = node.hysteria_obfs,
auth = (node.hysteria_auth_type == "base64") and node.hysteria_auth_password or nil,
auth_str = (node.hysteria_auth_type == "string") and node.hysteria_auth_password or nil,
recv_window_conn = tonumber(node.hysteria_recv_window_conn),
recv_window = tonumber(node.hysteria_recv_window),
disable_mtu_discovery = (node.hysteria_disable_mtu_discovery == "1") and true or false,
tls = {
enabled = true,
server_name = node.tls_serverName,
insecure = (node.tls_allowInsecure == "1") and true or false,
fragment = fragment,
record_fragment = record_fragment,
alpn = (node.hysteria_alpn and node.hysteria_alpn ~= "") and {
node.hysteria_alpn
} or nil,
ech = {
enabled = (node.ech == "1") and true or false,
config = node.ech_config and split(node.ech_config:gsub("\\n", "\n"), "\n") or {}
}
}
}
end
if node.protocol == "shadowtls" then
protocol_table = {
version = tonumber(node.shadowtls_version),
password = (node.shadowtls_version == "2" or node.shadowtls_version == "3") and node.password or nil,
tls = tls,
}
end
if node.protocol == "tuic" then
protocol_table = {
uuid = node.uuid,
password = node.password,
congestion_control = node.tuic_congestion_control or "cubic",
udp_relay_mode = node.tuic_udp_relay_mode or "native",
udp_over_stream = false,
zero_rtt_handshake = (node.tuic_zero_rtt_handshake == "1") and true or false,
heartbeat = node.tuic_heartbeat .. "s",
tls = {
enabled = true,
server_name = node.tls_serverName,
insecure = (node.tls_allowInsecure == "1") and true or false,
fragment = fragment,
record_fragment = record_fragment,
alpn = (node.tuic_alpn and node.tuic_alpn ~= "") and {
node.tuic_alpn
} or nil,
ech = {
enabled = (node.ech == "1") and true or false,
config = node.ech_config and split(node.ech_config:gsub("\\n", "\n"), "\n") or {}
}
}
}
end
if node.protocol == "hysteria2" then
local server_ports = {}
if node.hysteria2_hop then
node.hysteria2_hop = string.gsub(node.hysteria2_hop, "-", ":")
for range in node.hysteria2_hop:gmatch("([^,]+)") do
if range:match("^%d+:%d+$") then
table.insert(server_ports, range)
end
end
end
protocol_table = {
server_ports = next(server_ports) and server_ports or nil,
hop_interval = (function()
if not next(server_ports) then return nil end
local v = tonumber((node.hysteria2_hop_interval or "30s"):match("^%d+"))
return (v and v >= 5) and (v .. "s") or "30s"
end)(),
up_mbps = (node.hysteria2_up_mbps and tonumber(node.hysteria2_up_mbps)) and tonumber(node.hysteria2_up_mbps) or nil,
down_mbps = (node.hysteria2_down_mbps and tonumber(node.hysteria2_down_mbps)) and tonumber(node.hysteria2_down_mbps) or nil,
obfs = {
type = node.hysteria2_obfs_type,
password = node.hysteria2_obfs_password
},
password = node.hysteria2_auth_password or nil,
tls = {
enabled = true,
server_name = node.tls_serverName,
insecure = (node.tls_allowInsecure == "1") and true or false,
fragment = fragment,
record_fragment = record_fragment,
ech = {
enabled = (node.ech == "1") and true or false,
config = node.ech_config and split(node.ech_config:gsub("\\n", "\n"), "\n") or {}
}
}
}
end
if node.protocol == "anytls" then
protocol_table = {
password = (node.password and node.password ~= "") and node.password or "",
idle_session_check_interval = "30s",
idle_session_timeout = "30s",
min_idle_session = 5,
tls = tls
}
end
if node.protocol == "ssh" then
protocol_table = {
user = (node.username and node.username ~= "") and node.username or "root",
password = (node.password and node.password ~= "") and node.password or "",
private_key = node.ssh_priv_key,
private_key_passphrase = node.ssh_priv_key_pp,
host_key = node.ssh_host_key,
host_key_algorithms = node.ssh_host_key_algo,
client_version = node.ssh_client_version
}
end
if protocol_table then
for key, value in pairs(protocol_table) do
result[key] = value
end
end
end
return result
end
function gen_config_server(node)
local outbounds = {
{ type = "direct", tag = "direct" },
{ type = "block", tag = "block" }
}
local tls = {
enabled = true,
certificate_path = node.tls_certificateFile,
key_path = node.tls_keyFile,
}
if node.tls == "1" and node.reality == "1" then
tls.certificate_path = nil
tls.key_path = nil
tls.server_name = node.reality_handshake_server
tls.reality = {
enabled = true,
private_key = node.reality_private_key,
short_id = {
node.reality_shortId
},
handshake = {
server = node.reality_handshake_server,
server_port = tonumber(node.reality_handshake_server_port)
}
}
end
if node.tls == "1" and node.ech == "1" then
tls.ech = {
enabled = true,
key = node.ech_key and split(node.ech_key:gsub("\\n", "\n"), "\n") or {}
}
end
local mux = nil
if node.mux == "1" then
mux = {
enabled = true,
padding = (node.mux_padding == "1") and true or false,
brutal = {
enabled = (node.tcpbrutal == "1") and true or false,
up_mbps = tonumber(node.tcpbrutal_up_mbps) or 10,
down_mbps = tonumber(node.tcpbrutal_down_mbps) or 50,
},
}
end
local v2ray_transport = nil
if node.transport == "http" then
v2ray_transport = {
type = "http",
host = node.http_host or {},
path = node.http_path or "/",
}
end
if node.transport == "ws" then
v2ray_transport = {
type = "ws",
path = node.ws_path or "/",
headers = (node.ws_host ~= nil) and { Host = node.ws_host } or nil,
early_data_header_name = (node.ws_earlyDataHeaderName) and node.ws_earlyDataHeaderName or nil --要与 Xray-core 兼容,请将其设置为 Sec-WebSocket-Protocol。它需要与服务器保持一致。
}
end
if node.transport == "httpupgrade" then
v2ray_transport = {
type = "httpupgrade",
host = node.httpupgrade_host,
path = node.httpupgrade_path or "/",
}
end
if node.transport == "quic" then
v2ray_transport = {
type = "quic"
}
--没有额外的加密支持: 它基本上是重复加密。 并且 Xray-core 在这里与 v2ray-core 不兼容。
end
if node.transport == "grpc" then
v2ray_transport = {
type = "grpc",
service_name = node.grpc_serviceName,
}
end
local inbound = {
type = node.protocol,
tag = "inbound",
listen = (node.bind_local == "1") and "127.0.0.1" or "::",
listen_port = tonumber(node.port),
}
local protocol_table = nil
if node.protocol == "mixed" then
protocol_table = {
users = (node.auth == "1") and {
{
username = node.username,
password = node.password
}
} or nil,
set_system_proxy = false
}
end
if node.protocol == "socks" then
protocol_table = {
users = (node.auth == "1") and {
{
username = node.username,
password = node.password
}
} or nil
}
end
if node.protocol == "http" then
protocol_table = {
users = (node.auth == "1") and {
{
username = node.username,
password = node.password
}
} or nil,
tls = (node.tls == "1") and tls or nil,
}
end
if node.protocol == "shadowsocks" then
protocol_table = {
method = node.method,
password = node.password,
multiplex = mux,
}
end
if node.protocol == "vmess" then
if node.uuid then
local users = {}
for i = 1, #node.uuid do
users[i] = {
name = node.uuid[i],
uuid = node.uuid[i],
alterId = 0,
}
end
protocol_table = {
users = users,
tls = (node.tls == "1") and tls or nil,
multiplex = mux,
transport = v2ray_transport,
}
end
end
if node.protocol == "vless" then
if node.uuid then
local users = {}
for i = 1, #node.uuid do
users[i] = {
name = node.uuid[i],
uuid = node.uuid[i],
flow = node.flow,
}
end
protocol_table = {
users = users,
tls = (node.tls == "1") and tls or nil,
multiplex = mux,
transport = v2ray_transport,
}
end
end
if node.protocol == "trojan" then
if node.uuid then
local users = {}
for i = 1, #node.uuid do
users[i] = {
name = node.uuid[i],
password = node.uuid[i],
}
end
protocol_table = {
users = users,
tls = (node.tls == "1") and tls or nil,
fallback = nil,
fallback_for_alpn = nil,
multiplex = mux,
transport = v2ray_transport,
}
end
end
if node.protocol == "naive" then
protocol_table = {
users = {
{
username = node.username,
password = node.password
}
},
tls = tls,
}
end
if node.protocol == "hysteria" then
tls.alpn = (node.hysteria_alpn and node.hysteria_alpn ~= "") and {
node.hysteria_alpn
} or nil
protocol_table = {
up = node.hysteria_up_mbps .. " Mbps",
down = node.hysteria_down_mbps .. " Mbps",
up_mbps = tonumber(node.hysteria_up_mbps),
down_mbps = tonumber(node.hysteria_down_mbps),
obfs = node.hysteria_obfs,
users = {
{
name = "user1",
auth = (node.hysteria_auth_type == "base64") and node.hysteria_auth_password or nil,
auth_str = (node.hysteria_auth_type == "string") and node.hysteria_auth_password or nil,
}
},
recv_window_conn = node.hysteria_recv_window_conn and tonumber(node.hysteria_recv_window_conn) or nil,
recv_window_client = node.hysteria_recv_window_client and tonumber(node.hysteria_recv_window_client) or nil,
max_conn_client = node.hysteria_max_conn_client and tonumber(node.hysteria_max_conn_client) or nil,
disable_mtu_discovery = (node.hysteria_disable_mtu_discovery == "1") and true or false,
tls = tls
}
end
if node.protocol == "tuic" then
if node.uuid then
local users = {}
for i = 1, #node.uuid do
users[i] = {
name = node.uuid[i],
uuid = node.uuid[i],
password = node.password
}
end
tls.alpn = (node.tuic_alpn and node.tuic_alpn ~= "") and {
node.tuic_alpn
} or nil
protocol_table = {
users = users,
congestion_control = node.tuic_congestion_control or "cubic",
zero_rtt_handshake = (node.tuic_zero_rtt_handshake == "1") and true or false,
heartbeat = node.tuic_heartbeat .. "s",
tls = tls
}
end
end
if node.protocol == "hysteria2" then
protocol_table = {
up_mbps = (node.hysteria2_ignore_client_bandwidth ~= "1" and node.hysteria2_up_mbps and tonumber(node.hysteria2_up_mbps)) and tonumber(node.hysteria2_up_mbps) or nil,
down_mbps = (node.hysteria2_ignore_client_bandwidth ~= "1" and node.hysteria2_down_mbps and tonumber(node.hysteria2_down_mbps)) and tonumber(node.hysteria2_down_mbps) or nil,
obfs = {
type = node.hysteria2_obfs_type,
password = node.hysteria2_obfs_password
},
users = {
{
name = "user1",
password = node.hysteria2_auth_password or nil,
}
},
ignore_client_bandwidth = (node.hysteria2_ignore_client_bandwidth == "1") and true or false,
tls = tls
}
end
if node.protocol == "anytls" then
protocol_table = {
users = {
{
name = (node.username and node.username ~= "") and node.username or "sekai",
password = node.password
}
},
tls = tls,
}
end
if node.protocol == "direct" then
protocol_table = {
network = (node.d_protocol ~= "TCP,UDP") and node.d_protocol or nil,
override_address = node.d_address,
override_port = tonumber(node.d_port)
}
end
if protocol_table then
for key, value in pairs(protocol_table) do
inbound[key] = value
end
end
local route = {
rules = {
{
ip_cidr = { "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16" },
outbound = (node.accept_lan == nil or node.accept_lan == "0") and "block" or "direct"
}
}
}
if node.outbound_node then
local outbound = nil
if node.outbound_node == "_iface" and node.outbound_node_iface then
outbound = {
type = "direct",
tag = "outbound",
bind_interface = node.outbound_node_iface,
routing_mark = 255,
}
sys.call(string.format("mkdir -p %s && touch %s/%s", api.TMP_IFACE_PATH, api.TMP_IFACE_PATH, node.outbound_node_iface))
else
local outbound_node_t = uci:get_all("passwall", node.outbound_node)
if node.outbound_node == "_socks" or node.outbound_node == "_http" then
outbound_node_t = {
type = node.type,
protocol = node.outbound_node:gsub("_", ""),
address = node.outbound_node_address,
port = tonumber(node.outbound_node_port),
username = (node.outbound_node_username and node.outbound_node_username ~= "") and node.outbound_node_username or nil,
password = (node.outbound_node_password and node.outbound_node_password ~= "") and node.outbound_node_password or nil,
}
end
outbound = require("luci.passwall.util_sing-box").gen_outbound(nil, outbound_node_t, "outbound")
end
if outbound then
route.final = "outbound"
table.insert(outbounds, 1, outbound)
end
end
local config = {
log = {
disabled = (not node or node.log == "0") and true or false,
level = node.loglevel or "info",
timestamp = true,
--output = logfile,
},
inbounds = { inbound },
outbounds = outbounds,
route = route
}
for index, value in ipairs(config.outbounds) do
for k, v in pairs(config.outbounds[index]) do
if k:find("_") == 1 then
config.outbounds[index][k] = nil
end
end
end
if version_ge_1_11_0 then
-- Migrate logics
-- https://sing-box.sagernet.org/migration/
for i = #config.outbounds, 1, -1 do
local value = config.outbounds[i]
if value.type == "block" then
-- https://sing-box.sagernet.org/migration/#migrate-legacy-special-outbounds-to-rule-actions
table.remove(config.outbounds, i)
end
end
-- https://sing-box.sagernet.org/migration/#migrate-legacy-special-outbounds-to-rule-actions
for i = #config.route.rules, 1, -1 do
local value = config.route.rules[i]
if value.outbound == "block" then
value.action = "reject"
value.outbound = nil
end
end
end
return config
end
function gen_config(var)
local flag = var["-flag"]
local log = var["-log"] or "0"
local loglevel = var["-loglevel"] or "warn"
local logfile = var["-logfile"] or "/dev/null"
local node_id = var["-node"]
local server_host = var["-server_host"]
local server_port = var["-server_port"]
local tcp_proxy_way = var["-tcp_proxy_way"]
local tcp_redir_port = var["-tcp_redir_port"]
local udp_redir_port = var["-udp_redir_port"]
local local_socks_address = var["-local_socks_address"] or "0.0.0.0"
local local_socks_port = var["-local_socks_port"]
local local_socks_username = var["-local_socks_username"]
local local_socks_password = var["-local_socks_password"]
local local_http_address = var["-local_http_address"] or "0.0.0.0"
local local_http_port = var["-local_http_port"]
local local_http_username = var["-local_http_username"]
local local_http_password = var["-local_http_password"]
local dns_listen_port = var["-dns_listen_port"]
local direct_dns_port = var["-direct_dns_port"]
local direct_dns_udp_server = var["-direct_dns_udp_server"]
local direct_dns_tcp_server = var["-direct_dns_tcp_server"]
local direct_dns_query_strategy = var["-direct_dns_query_strategy"]
local remote_dns_server = var["-remote_dns_server"]
local remote_dns_port = var["-remote_dns_port"]
local remote_dns_udp_server = var["-remote_dns_udp_server"]
local remote_dns_tcp_server = var["-remote_dns_tcp_server"]
local remote_dns_doh_url = var["-remote_dns_doh_url"]
local remote_dns_doh_host = var["-remote_dns_doh_host"]
local remote_dns_client_ip = var["-remote_dns_client_ip"]
local remote_dns_query_strategy = var["-remote_dns_query_strategy"]
local remote_dns_fake = var["-remote_dns_fake"]
local dns_cache = var["-dns_cache"]
local dns_socks_address = var["-dns_socks_address"]
local dns_socks_port = var["-dns_socks_port"]
local no_run = var["-no_run"]
local dns_domain_rules = {}
local dns = nil
local inbounds = {}
local outbounds = {}
local COMMON = {}
local singbox_settings = uci:get_all(appname, "@global_singbox[0]") or {}
local route = {
rules = {}
}
local experimental = nil
if node_id then
local node = uci:get_all(appname, node_id)
if node then
if server_host and server_port then
node.address = server_host
node.port = server_port
end
end
if local_socks_port then
local inbound = {
type = "socks",
tag = "socks-in",
listen = local_socks_address,
listen_port = tonumber(local_socks_port),
sniff = true
}
if local_socks_username and local_socks_password and local_socks_username ~= "" and local_socks_password ~= "" then
inbound.users = {
{
username = local_socks_username,
password = local_socks_password
}
}
end
table.insert(inbounds, inbound)
end
if local_http_port then
local inbound = {
type = "http",
tag = "http-in",
listen = local_http_address,
listen_port = tonumber(local_http_port)
}
if local_http_username and local_http_password and local_http_username ~= "" and local_http_password ~= "" then
inbound.users = {
{
username = local_http_username,
password = local_http_password
}
}
end
table.insert(inbounds, inbound)
end
if tcp_redir_port then
if tcp_proxy_way ~= "tproxy" then
local inbound = {
type = "redirect",
tag = "redirect_tcp",
listen = "::",
listen_port = tonumber(tcp_redir_port),
sniff = true,
sniff_override_destination = (singbox_settings.sniff_override_destination == "1") and true or false,
}
table.insert(inbounds, inbound)
else
local inbound = {
type = "tproxy",
tag = "tproxy_tcp",
network = "tcp",
listen = "::",
listen_port = tonumber(tcp_redir_port),
sniff = true,
sniff_override_destination = (singbox_settings.sniff_override_destination == "1") and true or false,
}
table.insert(inbounds, inbound)
end
end
if udp_redir_port then
local inbound = {
type = "tproxy",
tag = "tproxy_udp",
network = "udp",
listen = "::",
listen_port = tonumber(udp_redir_port),
sniff = true,
sniff_override_destination = (singbox_settings.sniff_override_destination == "1") and true or false,
}
table.insert(inbounds, inbound)
end
local function gen_urltest(_node)
local urltest_id = _node[".name"]
local urltest_tag = "urltest-" .. urltest_id
-- existing urltest
for _, v in ipairs(outbounds) do
if v.tag == urltest_tag then
return urltest_tag
end
end
-- new urltest
local ut_nodes = _node.urltest_node
local valid_nodes = {}
for i = 1, #ut_nodes do
local ut_node_id = ut_nodes[i]
local ut_node_tag = "ut-" .. ut_node_id
local is_new_ut_node = true
for _, outbound in ipairs(outbounds) do
if string.sub(outbound.tag, 1, #ut_node_tag) == ut_node_tag then
is_new_ut_node = false
valid_nodes[#valid_nodes + 1] = outbound.tag
break
end
end
if is_new_ut_node then
local ut_node = uci:get_all(appname, ut_node_id)
local outbound = gen_outbound(flag, ut_node, ut_node_tag, { fragment = singbox_settings.fragment == "1" or nil, record_fragment = singbox_settings.record_fragment == "1" or nil, run_socks_instance = not no_run })
if outbound then
outbound.tag = outbound.tag .. ":" .. ut_node.remarks
table.insert(outbounds, outbound)
valid_nodes[#valid_nodes + 1] = outbound.tag
end
end
end
if #valid_nodes == 0 then return nil end
local outbound = {
type = "urltest",
tag = urltest_tag,
outbounds = valid_nodes,
url = _node.urltest_url or "https://www.gstatic.com/generate_204",
interval = (api.format_go_time(_node.urltest_interval) ~= "0s") and api.format_go_time(_node.urltest_interval) or "3m",
tolerance = (_node.urltest_tolerance and tonumber(_node.urltest_tolerance) > 0) and tonumber(_node.urltest_tolerance) or 50,
idle_timeout = (api.format_go_time(_node.urltest_idle_timeout) ~= "0s") and api.format_go_time(_node.urltest_idle_timeout) or "30m",
interrupt_exist_connections = (_node.urltest_interrupt_exist_connections == "true" or _node.urltest_interrupt_exist_connections == "1") and true or false
}
table.insert(outbounds, outbound)
return urltest_tag
end
local function set_outbound_detour(node, outbound, outbounds_table, shunt_rule_name)
if not node or not outbound or not outbounds_table then return nil end
local default_outTag = outbound.tag
local last_insert_outbound
if node.shadowtls == "1" then
local _node = {
type = "sing-box",
protocol = "shadowtls",
shadowtls_version = node.shadowtls_version,
password = (node.shadowtls_version == "2" or node.shadowtls_version == "3") and node.shadowtls_password or nil,
address = node.address,
port = node.port,
tls = "1",
tls_serverName = node.shadowtls_serverName,
utls = node.shadowtls_utls,
fingerprint = node.shadowtls_fingerprint
}
local shadowtls_outbound = gen_outbound(nil, _node, outbound.tag .. "_shadowtls")
if shadowtls_outbound then
last_insert_outbound = shadowtls_outbound
outbound.detour = outbound.tag .. "_shadowtls"
outbound.server = nil
outbound.server_port = nil
end
end
if node.chain_proxy == "1" and node.preproxy_node then
if outbound["_flag_proxy_tag"] then
--Ignore
else
local preproxy_node = uci:get_all(appname, node.preproxy_node)
if preproxy_node then
local preproxy_outbound = gen_outbound(nil, preproxy_node)
if preproxy_outbound then
preproxy_outbound.tag = preproxy_node[".name"] .. ":" .. preproxy_node.remarks
outbound.tag = preproxy_outbound.tag .. " -> " .. outbound.tag
outbound.detour = preproxy_outbound.tag
last_insert_outbound = preproxy_outbound
default_outTag = outbound.tag
end
end
end
end
if node.chain_proxy == "2" and node.to_node then
local to_node = uci:get_all(appname, node.to_node)
if to_node then
local to_outbound = gen_outbound(nil, to_node)
if to_outbound then
if shunt_rule_name then
to_outbound.tag = outbound.tag
outbound.tag = node[".name"]
else
to_outbound.tag = outbound.tag .. " -> " .. to_outbound.tag
end
to_outbound.detour = outbound.tag
table.insert(outbounds_table, to_outbound)
default_outTag = to_outbound.tag
end
end
end
return default_outTag, last_insert_outbound
end
if node.protocol == "_shunt" then
local rules = {}
local preproxy_rule_name = node.preproxy_enabled == "1" and "main" or nil
local preproxy_tag = preproxy_rule_name
local preproxy_node_id = preproxy_rule_name and node["main_node"] or nil
local function gen_shunt_node(rule_name, _node_id)
if not rule_name then return nil, nil end
if not _node_id then _node_id = node[rule_name] end
local rule_outboundTag
if _node_id == "_direct" then
rule_outboundTag = "direct"
elseif _node_id == "_blackhole" then
rule_outboundTag = "block"
elseif _node_id == "_default" and rule_name ~= "default" then
rule_outboundTag = "default"
elseif _node_id and _node_id:find("Socks_") then
local socks_id = _node_id:sub(1 + #"Socks_")
local socks_node = uci:get_all(appname, socks_id) or nil
if socks_node then
local _node = {
type = "sing-box",
protocol = "socks",
address = "127.0.0.1",
port = socks_node.port,
uot = "1",
}
local _outbound = gen_outbound(flag, _node, rule_name)
if _outbound then
table.insert(outbounds, _outbound)
rule_outboundTag = _outbound.tag
end
end
elseif _node_id then
local _node = uci:get_all(appname, _node_id)
if not _node then return nil, nil end
if api.is_normal_node(_node) then
local use_proxy = preproxy_tag and node[rule_name .. "_proxy_tag"] == preproxy_rule_name and _node_id ~= preproxy_node_id
local copied_outbound
for index, value in ipairs(outbounds) do
if value["_id"] == _node_id and value["_flag_proxy_tag"] == (use_proxy and preproxy_tag or nil) then
copied_outbound = api.clone(value)
break
end
end
if copied_outbound then
copied_outbound.tag = rule_name .. ":" .. _node.remarks
table.insert(outbounds, copied_outbound)
rule_outboundTag = copied_outbound.tag
else
if use_proxy then
local pre_proxy = nil
if _node.type ~= "sing-box" then
pre_proxy = true
end
if pre_proxy then
new_port = get_new_port()
table.insert(inbounds, {
type = "direct",
tag = "proxy_" .. rule_name,
listen = "127.0.0.1",
listen_port = new_port,
override_address = _node.address,
override_port = tonumber(_node.port),
})
if _node.tls_serverName == nil then
_node.tls_serverName = _node.address
end
_node.address = "127.0.0.1"
_node.port = new_port
table.insert(rules, 1, {
inbound = {"proxy_" .. rule_name},
outbound = preproxy_tag,
})
end
end
local proxy_table = {
tag = use_proxy and preproxy_tag or nil,
run_socks_instance = not no_run
}
if not proxy_table.tag then
if singbox_settings.fragment == "1" then
proxy_table.fragment = true
end
if singbox_settings.record_fragment == "1" then
proxy_table.record_fragment = true
end
end
local _outbound = gen_outbound(flag, _node, rule_name, proxy_table)
if _outbound then
_outbound.tag = _outbound.tag .. ":" .. _node.remarks
rule_outboundTag, last_insert_outbound = set_outbound_detour(_node, _outbound, outbounds, rule_name)
table.insert(outbounds, _outbound)
if last_insert_outbound then
table.insert(outbounds, last_insert_outbound)
end
end
end
elseif _node.protocol == "_urltest" then
rule_outboundTag = gen_urltest(_node)
elseif _node.protocol == "_iface" then
if _node.iface then
local _outbound = {
type = "direct",
tag = rule_name .. ":" .. _node.remarks,
bind_interface = _node.iface,
routing_mark = 255,
}
table.insert(outbounds, _outbound)
rule_outboundTag = _outbound.tag
sys.call(string.format("mkdir -p %s && touch %s/%s", api.TMP_IFACE_PATH, api.TMP_IFACE_PATH, _node.iface))
end
end
end
return rule_outboundTag
end
if preproxy_tag and preproxy_node_id then
local preproxy_outboundTag = gen_shunt_node(preproxy_rule_name, preproxy_node_id)
if preproxy_outboundTag then
preproxy_tag = preproxy_outboundTag
end
end
--default_node
local default_node_id = node.default_node or "_direct"
COMMON.default_outbound_tag = gen_shunt_node("default", default_node_id)
--shunt rule
uci:foreach(appname, "shunt_rules", function(e)
local outboundTag = gen_shunt_node(e[".name"])
if outboundTag and e.remarks then
if outboundTag == "default" then
outboundTag = COMMON.default_outbound_tag
end
local protocols = nil
if e["protocol"] and e["protocol"] ~= "" then
protocols = {}
string.gsub(e["protocol"], '[^' .. " " .. ']+', function(w)
table.insert(protocols, w)
end)
end
local inboundTag = nil
if e["inbound"] and e["inbound"] ~= "" then
inboundTag = {}
if e["inbound"]:find("tproxy") then
if tcp_redir_port then
if tcp_proxy_way == "tproxy" then
table.insert(inboundTag, "tproxy_tcp")
else
table.insert(inboundTag, "redirect_tcp")
end
end
if udp_redir_port then
table.insert(inboundTag, "tproxy_udp")
end
end
if e["inbound"]:find("socks") then
if local_socks_port then
table.insert(inboundTag, "socks-in")
end
end
end
local rule = {
inbound = inboundTag,
outbound = outboundTag,
protocol = protocols
}
if e.network then
local network = {}
string.gsub(e.network, '[^' .. "," .. ']+', function(w)
table.insert(network, w)
end)
rule.network = network
end
if e.source then
local source_ip_cidr = {}
local is_private = false
string.gsub(e.source, '[^' .. " " .. ']+', function(w)
if w:find("geoip") == 1 then
local _geoip = w:sub(1 + #"geoip:") --适配srs
if _geoip == "private" then
is_private = true
end
else
table.insert(source_ip_cidr, w)
end
end)
rule.source_ip_is_private = is_private and true or nil
rule.source_ip_cidr = #source_ip_cidr > 0 and source_ip_cidr or nil
if is_private or #source_ip_cidr > 0 then rule.rule_set_ip_cidr_match_source = true end
end
if e.sourcePort then
local source_port = {}
local source_port_range = {}
string.gsub(e.sourcePort, '[^' .. "," .. ']+', function(w)
if tonumber(w) and tonumber(w) >= 1 and tonumber(w) <= 65535 then
table.insert(source_port, tonumber(w))
else
table.insert(source_port_range, w)
end
end)
rule.source_port = #source_port > 0 and source_port or nil
rule.source_port_range = #source_port_range > 0 and source_port_range or nil
end
if e.port then
local port = {}
local port_range = {}
string.gsub(e.port, '[^' .. "," .. ']+', function(w)
if tonumber(w) and tonumber(w) >= 1 and tonumber(w) <= 65535 then
table.insert(port, tonumber(w))
else
table.insert(port_range, w)
end
end)
rule.port = #port > 0 and port or nil
rule.port_range = #port_range > 0 and port_range or nil
end
local rule_set_tag = {}
if e.domain_list then
local domain_table = {
outboundTag = outboundTag,
domain = {},
domain_suffix = {},
domain_keyword = {},
domain_regex = {},
rule_set = {},
}
string.gsub(e.domain_list, '[^' .. "\r\n" .. ']+', function(w)
if w:find("#") == 1 then return end
if w:find("geosite:") == 1 then
local _geosite = w:sub(1 + #"geosite:") --适配srs
geosite_all_tag[_geosite] = true
table.insert(rule_set_tag, "geosite-" .. _geosite)
table.insert(domain_table.rule_set, "geosite-" .. _geosite)
elseif w:find("regexp:") == 1 then
table.insert(domain_table.domain_regex, w:sub(1 + #"regexp:"))
elseif w:find("full:") == 1 then
table.insert(domain_table.domain, w:sub(1 + #"full:"))
elseif w:find("domain:") == 1 then
table.insert(domain_table.domain_suffix, w:sub(1 + #"domain:"))
else
table.insert(domain_table.domain_keyword, w)
end
end)
rule.domain = #domain_table.domain > 0 and domain_table.domain or nil
rule.domain_suffix = #domain_table.domain_suffix > 0 and domain_table.domain_suffix or nil
rule.domain_keyword = #domain_table.domain_keyword > 0 and domain_table.domain_keyword or nil
rule.domain_regex = #domain_table.domain_regex > 0 and domain_table.domain_regex or nil
if outboundTag then
table.insert(dns_domain_rules, api.clone(domain_table))
end
end
if e.ip_list then
local ip_cidr = {}
local is_private = false
string.gsub(e.ip_list, '[^' .. "\r\n" .. ']+', function(w)
if w:find("#") == 1 then return end
if w:find("geoip:") == 1 then
local _geoip = w:sub(1 + #"geoip:") --适配srs
if _geoip == "private" then
is_private = true
else
geoip_all_tag[_geoip] = true
table.insert(rule_set_tag, "geoip-" .. _geoip)
end
else
table.insert(ip_cidr, w)
end
end)
rule.ip_is_private = is_private and true or nil
rule.ip_cidr = #ip_cidr > 0 and ip_cidr or nil
end
rule.rule_set = #rule_set_tag > 0 and rule_set_tag or nil --适配srs
table.insert(rules, rule)
end
end)
for index, value in ipairs(rules) do
table.insert(route.rules, rules[index])
end
local rule_set = {} --适配srs
if next(geosite_all_tag) then
for k,v in pairs(geosite_all_tag) do
local srs_file = srss_path .. "geosite-" .. k ..".srs"
local _rule_set = {
tag = "geosite-" .. k,
type = "local",
format = "binary",
path = srs_file
}
table.insert(rule_set, _rule_set)
end
end
if next(geoip_all_tag) then
for k,v in pairs(geoip_all_tag) do
local srs_file = srss_path .. "geoip-" .. k ..".srs"
local _rule_set = {
tag = "geoip-" .. k,
type = "local",
format = "binary",
path = srs_file
}
table.insert(rule_set, _rule_set)
end
end
route.rule_set = #rule_set >0 and rule_set or nil
elseif node.protocol == "_urltest" then
if node.urltest_node then
COMMON.default_outbound_tag = gen_urltest(node)
end
elseif node.protocol == "_iface" then
if node.iface then
local outbound = {
type = "direct",
tag = node.remarks or node_id,
bind_interface = node.iface,
routing_mark = 255,
}
table.insert(outbounds, outbound)
COMMON.default_outbound_tag = outbound.tag
sys.call(string.format("mkdir -p %s && touch %s/%s", api.TMP_IFACE_PATH, api.TMP_IFACE_PATH, node.iface))
end
else
local outbound = gen_outbound(flag, node, nil, { fragment = singbox_settings.fragment == "1" or nil, record_fragment = singbox_settings.record_fragment == "1" or nil, run_socks_instance = not no_run })
if outbound then
outbound.tag = outbound.tag .. ":" .. node.remarks
COMMON.default_outbound_tag, last_insert_outbound = set_outbound_detour(node, outbound, outbounds)
table.insert(outbounds, outbound)
if last_insert_outbound then
table.insert(outbounds, last_insert_outbound)
end
end
end
end
if COMMON.default_outbound_tag then
route.final = COMMON.default_outbound_tag
end
if dns_listen_port then
dns = {
servers = {},
rules = {},
disable_cache = (dns_cache and dns_cache == "0") and true or false,
disable_expire = false, --禁用 DNS 缓存过期。
independent_cache = false, --使每个 DNS 服务器的缓存独立,以满足特殊目的。如果启用,将轻微降低性能。
reverse_mapping = true, --在响应 DNS 查询后存储 IP 地址的反向映射以为路由目的提供域名。
fakeip = nil,
}
if not version_ge_1_12_0 then --Migrate to new DNS server formats
table.insert(dns.servers, {
tag = "block",
address = "rcode://success",
})
end
if dns_socks_address and dns_socks_port then
default_outTag = "dns_socks_out"
table.insert(outbounds, 1, {
type = "socks",
tag = default_outTag,
server = dns_socks_address,
server_port = tonumber(dns_socks_port)
})
else
default_outTag = COMMON.default_outbound_tag
end
local remote_strategy = "prefer_ipv6"
if remote_dns_query_strategy == "UseIPv4" then
remote_strategy = "ipv4_only"
elseif remote_dns_query_strategy == "UseIPv6" then
remote_strategy = "ipv6_only"
end
local remote_server = {}
local fakedns_tag = "remote_fakeip"
if not version_ge_1_12_0 then --Migrate to new DNS server formats
remote_server = {
tag = "remote",
address_strategy = "prefer_ipv4",
strategy = remote_strategy,
address_resolver = "direct",
detour = default_outTag,
client_subnet = (remote_dns_client_ip and remote_dns_client_ip ~= "") and remote_dns_client_ip or nil,
}
if remote_dns_udp_server then
local server_port = tonumber(remote_dns_port) or 53
remote_server.address = "udp://" .. remote_dns_udp_server .. ":" .. server_port
end
if remote_dns_tcp_server then
remote_server.address = remote_dns_tcp_server
end
if remote_dns_doh_url and remote_dns_doh_host then
remote_server.address = remote_dns_doh_url
end
if remote_server.address then
if api.is_local_ip(remote_server.address) then --dns为本地ip,不走代理
remote_server.detour = "direct"
end
table.insert(dns.servers, remote_server)
end
if remote_dns_fake then
dns.fakeip = {
enabled = true,
inet4_range = "198.18.0.0/15",
inet6_range = "fc00::/18",
}
table.insert(dns.servers, {
tag = fakedns_tag,
address = "fakeip",
strategy = remote_strategy,
})
if not experimental then
experimental = {}
end
experimental.cache_file = {
enabled = true,
store_fakeip = true,
path = api.CACHE_PATH .. "/singbox_" .. flag .. ".db"
}
end
else -- Migrate to 1.12 DNS
remote_server = {
tag = "remote",
domain_strategy = remote_strategy,
domain_resolver = "direct",
detour = default_outTag,
}
if remote_dns_udp_server then
local server_port = tonumber(remote_dns_port) or 53
remote_server.type = "udp"
remote_server.server = remote_dns_udp_server
remote_server.server_port = server_port
end
if remote_dns_tcp_server then
local server_port = tonumber(remote_dns_port) or 53
remote_server.type = "tcp"
remote_server.server = remote_dns_server
remote_server.server_port = server_port
end
if remote_dns_doh_url and remote_dns_doh_host then
local server_port = tonumber(remote_dns_port) or 443
remote_server.type = "https"
remote_server.server = remote_dns_doh_host
remote_server.server_port = server_port
end
if remote_server.server then
if api.is_local_ip(remote_server.server) then --dns为本地ip,不走代理
remote_server.detour = "direct"
end
table.insert(dns.servers, remote_server)
end
if remote_dns_fake then
table.insert(dns.servers, {
tag = fakedns_tag,
type = "fakeip",
inet4_range = "198.18.0.0/15",
inet6_range = "fc00::/18",
})
if not experimental then
experimental = {}
end
experimental.cache_file = {
enabled = true,
store_fakeip = true,
path = api.CACHE_PATH .. "/singbox_" .. flag .. ".db"
}
end
end
local direct_strategy = "prefer_ipv6"
if direct_dns_udp_server or direct_dns_tcp_server then
if direct_dns_query_strategy == "UseIPv4" then
direct_strategy = "ipv4_only"
elseif direct_dns_query_strategy == "UseIPv6" then
direct_strategy = "ipv6_only"
end
local domain = {}
local nodes_domain_text = sys.exec('uci show passwall | grep ".address=" | cut -d "\'" -f 2 | grep "[a-zA-Z]$" | sort -u')
string.gsub(nodes_domain_text, '[^' .. "\r\n" .. ']+', function(w)
table.insert(domain, w)
end)
if #domain > 0 then
table.insert(dns_domain_rules, 1, {
outboundTag = "direct",
domain = domain,
strategy = version_ge_1_12_0 and direct_strategy or nil
})
end
if not version_ge_1_12_0 then --Migrate to new DNS server formats
local direct_dns_server, port
if direct_dns_udp_server then
port = tonumber(direct_dns_port) or 53
direct_dns_server = "udp://" .. direct_dns_udp_server .. ":" .. port
elseif direct_dns_tcp_server then
port = tonumber(direct_dns_port) or 53
direct_dns_server = "tcp://" .. direct_dns_tcp_server .. ":" .. port
end
table.insert(dns.servers, {
tag = "direct",
address = direct_dns_server,
address_strategy = "prefer_ipv6",
strategy = direct_strategy,
detour = "direct",
})
else -- Migrate to 1.12 DNS
local direct_dns_server, port, type
if direct_dns_udp_server then
port = tonumber(direct_dns_port) or 53
direct_dns_server = direct_dns_udp_server
type = "udp"
elseif direct_dns_tcp_server then
port = tonumber(direct_dns_port) or 53
direct_dns_server = direct_dns_tcp_server
type = "tcp"
end
table.insert(dns.servers, {
tag = "direct",
type = type,
server = direct_dns_server,
server_port = port,
domain_strategy = direct_strategy,
detour = "direct",
})
end
end
local default_dns_flag = "remote"
if dns_socks_address and dns_socks_port then
else
if node_id and (tcp_redir_port or udp_redir_port) then
local node = uci:get_all(appname, node_id)
if node.protocol == "_shunt" then
if node.default_node == "_direct" then
default_dns_flag = "direct"
end
end
else default_dns_flag = "direct"
end
end
if default_dns_flag == "remote" then
if remote_dns_fake then
table.insert(dns.rules, {
query_type = { "A", "AAAA" },
server = fakedns_tag,
disable_cache = true
})
end
end
dns.final = default_dns_flag
if version_ge_1_12_0 then -- Migrate to 1.12 DNS
dns.strategy = (default_dns_flag == "direct") and direct_strategy or remote_strategy
end
--按分流顺序DNS
if dns_domain_rules and #dns_domain_rules > 0 then
for index, value in ipairs(dns_domain_rules) do
if value.outboundTag and (value.domain or value.domain_suffix or value.domain_keyword or value.domain_regex or value.rule_set) then
local dns_rule = {
server = value.outboundTag,
domain = (value.domain and #value.domain > 0) and value.domain or nil,
domain_suffix = (value.domain_suffix and #value.domain_suffix > 0) and value.domain_suffix or nil,
domain_keyword = (value.domain_keyword and #value.domain_keyword > 0) and value.domain_keyword or nil,
domain_regex = (value.domain_regex and #value.domain_regex > 0) and value.domain_regex or nil,
rule_set = (value.rule_set and #value.rule_set > 0) and value.rule_set or nil, --适配srs
disable_cache = false,
strategy = (version_ge_1_12_0 and value.outboundTag == "direct") and direct_strategy or nil --Migrate to 1.12 DNS
}
if version_ge_1_12_0 and value.outboundTag == "block" then --Migrate to 1.12 DNS
dns_rule.action = "predefined"
dns_rule.rcode = "NOERROR"
dns_rule.server = nil
dns_rule.disable_cache = nil
end
if value.outboundTag ~= "block" and value.outboundTag ~= "direct" then
dns_rule.server = "remote"
dns_rule.strategy = version_ge_1_12_0 and remote_strategy or nil --Migrate to 1.12 DNS
dns_rule.client_subnet = (version_ge_1_12_0 and remote_dns_client_ip and remote_dns_client_ip ~= "") and remote_dns_client_ip or nil --Migrate to 1.12 DNS
if value.outboundTag ~= COMMON.default_outbound_tag and (remote_server.address or remote_server.server) then
local remote_shunt_server = api.clone(remote_server)
remote_shunt_server.tag = value.outboundTag
local is_local = (remote_server.address and api.is_local_ip(remote_server.address)) or
(remote_server.server and api.is_local_ip(remote_server.server)) --dns为本地ip,不走代理
remote_shunt_server.detour = is_local and "direct" or value.outboundTag
table.insert(dns.servers, remote_shunt_server)
dns_rule.server = remote_shunt_server.tag
end
if remote_dns_fake then
local fakedns_dns_rule = api.clone(dns_rule)
fakedns_dns_rule.query_type = {
"A", "AAAA"
}
fakedns_dns_rule.server = fakedns_tag
fakedns_dns_rule.disable_cache = true
table.insert(dns.rules, fakedns_dns_rule)
end
end
table.insert(dns.rules, dns_rule)
end
end
end
table.insert(inbounds, {
type = "direct",
tag = "dns-in",
listen = "127.0.0.1",
listen_port = tonumber(dns_listen_port),
sniff = true,
})
table.insert(outbounds, {
type = "dns",
tag = "dns-out",
})
table.insert(route.rules, 1, {
protocol = "dns",
inbound = {
"dns-in"
},
outbound = "dns-out"
})
end
if inbounds or outbounds then
local config = {
log = {
disabled = log == "0" and true or false,
level = loglevel,
timestamp = true,
output = logfile,
},
-- DNS
dns = dns,
-- 传入连接
inbounds = inbounds,
-- 传出连接
outbounds = outbounds,
-- 路由
route = route,
--实验性
experimental = experimental,
}
local direct_outbound = {
type = "direct",
tag = "direct",
routing_mark = 255,
}
if not version_ge_1_12_0 then --Migrate to 1.12 DNS
direct_outbound.domain_strategy = "prefer_ipv6"
else
local domain_resolver = {
server = "direct",
strategy = "prefer_ipv6"
}
direct_outbound.domain_resolver = domain_resolver
-- 当没有 direct dns 服务器时添加 local
local hasDirect = false
if config.dns and config.dns.servers then
for _, server in ipairs(config.dns.servers) do
if server.tag == "direct" then
hasDirect = true
break
end
end
end
if not hasDirect then
config.dns = {
servers = {
{
type = "local",
tag = "direct",
detour = "direct"
}
},
}
end
end
table.insert(outbounds,direct_outbound)
table.insert(outbounds, {
type = "block",
tag = "block"
})
for index, value in ipairs(config.outbounds) do
if not value["_flag_proxy_tag"] and not value.detour and value["_id"] and value.server and value.server_port and not no_run then
sys.call(string.format("echo '%s' >> %s", value["_id"], api.TMP_PATH .. "/direct_node_list"))
end
for k, v in pairs(config.outbounds[index]) do
if k:find("_") == 1 then
config.outbounds[index][k] = nil
end
end
end
if version_ge_1_11_0 then
-- Migrate logics
-- https://sing-box.sagernet.org/migration/
local endpoints = {}
for i = #config.outbounds, 1, -1 do
local value = config.outbounds[i]
if value.type == "wireguard" then
-- https://sing-box.sagernet.org/migration/#migrate-wireguard-outbound-to-endpoint
local endpoint = {
type = "wireguard",
tag = value.tag,
system = value.system_interface,
name = value.interface_name,
mtu = value.mtu,
address = value.local_address,
private_key = value.private_key,
peers = {
{
address = value.server,
port = value.server_port,
public_key = value.peer_public_key,
pre_shared_key = value.pre_shared_key,
allowed_ips = {"0.0.0.0/0"},
reserved = value.reserved
}
},
domain_strategy = value.domain_strategy,
detour = value.detour
}
endpoints[#endpoints + 1] = endpoint
table.remove(config.outbounds, i)
end
if value.type == "block" or value.type == "dns" then
-- https://sing-box.sagernet.org/migration/#migrate-legacy-special-outbounds-to-rule-actions
table.remove(config.outbounds, i)
end
end
if #endpoints > 0 then
config.endpoints = endpoints
end
-- https://sing-box.sagernet.org/migration/#migrate-legacy-special-outbounds-to-rule-actions
for i = #config.route.rules, 1, -1 do
local value = config.route.rules[i]
if value.outbound == "block" then
value.action = "reject"
value.outbound = nil
elseif value.outbound == "dns-out" then
value.action = "hijack-dns"
value.outbound = nil
else
value.action = "route"
end
end
-- https://sing-box.sagernet.org/migration/#migrate-legacy-inbound-fields-to-rule-actions
for i = #config.inbounds, 1, -1 do
local value = config.inbounds[i]
if value.sniff == true then
table.insert(config.route.rules, 1, {
inbound = value.tag,
action = "sniff"
})
value.sniff = nil
value.sniff_override_destination = nil
end
if value.domain_strategy then
table.insert(config.route.rules, 1, {
inbound = value.tag,
action = "resolve",
strategy = value.domain_strategy,
--server = ""
})
value.domain_strategy = nil
end
end
if config.route.final == "block" then
config.route.final = nil
table.insert(config.route.rules, {
action = "reject"
})
end
end
return jsonc.stringify(config, 1)
end
end
function gen_proto_config(var)
local local_socks_address = var["-local_socks_address"] or "0.0.0.0"
local local_socks_port = var["-local_socks_port"]
local local_socks_username = var["-local_socks_username"]
local local_socks_password = var["-local_socks_password"]
local local_http_address = var["-local_http_address"] or "0.0.0.0"
local local_http_port = var["-local_http_port"]
local local_http_username = var["-local_http_username"]
local local_http_password = var["-local_http_password"]
local server_proto = var["-server_proto"]
local server_address = var["-server_address"]
local server_port = var["-server_port"]
local server_username = var["-server_username"]
local server_password = var["-server_password"]
local inbounds = {}
local outbounds = {}
if local_socks_address and local_socks_port then
local inbound = {
type = "socks",
tag = "socks-in",
listen = local_socks_address,
listen_port = tonumber(local_socks_port),
}
if local_socks_username and local_socks_password and local_socks_username ~= "" and local_socks_password ~= "" then
inbound.users = {
username = local_socks_username,
password = local_socks_password
}
end
table.insert(inbounds, inbound)
end
if local_http_address and local_http_port then
local inbound = {
type = "http",
tag = "http-in",
tls = nil,
listen = local_http_address,
listen_port = tonumber(local_http_port),
}
if local_http_username and local_http_password and local_http_username ~= "" and local_http_password ~= "" then
inbound.users = {
{
username = local_http_username,
password = local_http_password
}
}
end
table.insert(inbounds, inbound)
end
if server_proto ~= "nil" and server_address ~= "nil" and server_port ~= "nil" then
local outbound = {
type = server_proto,
tag = "out",
server = server_address,
server_port = tonumber(server_port),
username = (server_username and server_password) and server_username or nil,
password = (server_username and server_password) and server_password or nil,
}
if outbound then table.insert(outbounds, outbound) end
end
local config = {
log = {
disabled = true,
level = "warn",
timestamp = true,
},
-- 传入连接
inbounds = inbounds,
-- 传出连接
outbounds = outbounds,
}
return jsonc.stringify(config, 1)
end
_G.gen_config = gen_config
_G.gen_proto_config = gen_proto_config
if arg[1] then
local func =_G[arg[1]]
if func then
print(func(api.get_function_args(arg)))
if (next(geosite_all_tag) or next(geoip_all_tag)) and not no_run then
convert_geofile()
end
end
end
|
2951121599/Bili-Insight
| 3,714
|
chrome-extension/scripts/md5.js
|
!function(n){"use strict";function d(n,t){var r=(65535&n)+(65535&t);return(n>>16)+(t>>16)+(r>>16)<<16|65535&r}function f(n,t,r,e,o,u){return d((u=d(d(t,n),d(e,u)))<<o|u>>>32-o,r)}function l(n,t,r,e,o,u,c){return f(t&r|~t&e,n,t,o,u,c)}function g(n,t,r,e,o,u,c){return f(t&e|r&~e,n,t,o,u,c)}function v(n,t,r,e,o,u,c){return f(t^r^e,n,t,o,u,c)}function m(n,t,r,e,o,u,c){return f(r^(t|~e),n,t,o,u,c)}function c(n,t){var r,e,o,u;n[t>>5]|=128<<t%32,n[14+(t+64>>>9<<4)]=t;for(var c=1732584193,f=-271733879,i=-1732584194,a=271733878,h=0;h<n.length;h+=16)c=l(r=c,e=f,o=i,u=a,n[h],7,-680876936),a=l(a,c,f,i,n[h+1],12,-389564586),i=l(i,a,c,f,n[h+2],17,606105819),f=l(f,i,a,c,n[h+3],22,-1044525330),c=l(c,f,i,a,n[h+4],7,-176418897),a=l(a,c,f,i,n[h+5],12,1200080426),i=l(i,a,c,f,n[h+6],17,-1473231341),f=l(f,i,a,c,n[h+7],22,-45705983),c=l(c,f,i,a,n[h+8],7,1770035416),a=l(a,c,f,i,n[h+9],12,-1958414417),i=l(i,a,c,f,n[h+10],17,-42063),f=l(f,i,a,c,n[h+11],22,-1990404162),c=l(c,f,i,a,n[h+12],7,1804603682),a=l(a,c,f,i,n[h+13],12,-40341101),i=l(i,a,c,f,n[h+14],17,-1502002290),c=g(c,f=l(f,i,a,c,n[h+15],22,1236535329),i,a,n[h+1],5,-165796510),a=g(a,c,f,i,n[h+6],9,-1069501632),i=g(i,a,c,f,n[h+11],14,643717713),f=g(f,i,a,c,n[h],20,-373897302),c=g(c,f,i,a,n[h+5],5,-701558691),a=g(a,c,f,i,n[h+10],9,38016083),i=g(i,a,c,f,n[h+15],14,-660478335),f=g(f,i,a,c,n[h+4],20,-405537848),c=g(c,f,i,a,n[h+9],5,568446438),a=g(a,c,f,i,n[h+14],9,-1019803690),i=g(i,a,c,f,n[h+3],14,-187363961),f=g(f,i,a,c,n[h+8],20,1163531501),c=g(c,f,i,a,n[h+13],5,-1444681467),a=g(a,c,f,i,n[h+2],9,-51403784),i=g(i,a,c,f,n[h+7],14,1735328473),c=v(c,f=g(f,i,a,c,n[h+12],20,-1926607734),i,a,n[h+5],4,-378558),a=v(a,c,f,i,n[h+8],11,-2022574463),i=v(i,a,c,f,n[h+11],16,1839030562),f=v(f,i,a,c,n[h+14],23,-35309556),c=v(c,f,i,a,n[h+1],4,-1530992060),a=v(a,c,f,i,n[h+4],11,1272893353),i=v(i,a,c,f,n[h+7],16,-155497632),f=v(f,i,a,c,n[h+10],23,-1094730640),c=v(c,f,i,a,n[h+13],4,681279174),a=v(a,c,f,i,n[h],11,-358537222),i=v(i,a,c,f,n[h+3],16,-722521979),f=v(f,i,a,c,n[h+6],23,76029189),c=v(c,f,i,a,n[h+9],4,-640364487),a=v(a,c,f,i,n[h+12],11,-421815835),i=v(i,a,c,f,n[h+15],16,530742520),c=m(c,f=v(f,i,a,c,n[h+2],23,-995338651),i,a,n[h],6,-198630844),a=m(a,c,f,i,n[h+7],10,1126891415),i=m(i,a,c,f,n[h+14],15,-1416354905),f=m(f,i,a,c,n[h+5],21,-57434055),c=m(c,f,i,a,n[h+12],6,1700485571),a=m(a,c,f,i,n[h+3],10,-1894986606),i=m(i,a,c,f,n[h+10],15,-1051523),f=m(f,i,a,c,n[h+1],21,-2054922799),c=m(c,f,i,a,n[h+8],6,1873313359),a=m(a,c,f,i,n[h+15],10,-30611744),i=m(i,a,c,f,n[h+6],15,-1560198380),f=m(f,i,a,c,n[h+13],21,1309151649),c=m(c,f,i,a,n[h+4],6,-145523070),a=m(a,c,f,i,n[h+11],10,-1120210379),i=m(i,a,c,f,n[h+2],15,718787259),f=m(f,i,a,c,n[h+9],21,-343485551),c=d(c,r),f=d(f,e),i=d(i,o),a=d(a,u);return[c,f,i,a]}function i(n){for(var t="",r=32*n.length,e=0;e<r;e+=8)t+=String.fromCharCode(n[e>>5]>>>e%32&255);return t}function a(n){var t=[];for(t[(n.length>>2)-1]=void 0,e=0;e<t.length;e+=1)t[e]=0;for(var r=8*n.length,e=0;e<r;e+=8)t[e>>5]|=(255&n.charCodeAt(e/8))<<e%32;return t}function e(n){for(var t,r="0123456789abcdef",e="",o=0;o<n.length;o+=1)t=n.charCodeAt(o),e+=r.charAt(t>>>4&15)+r.charAt(15&t);return e}function r(n){return unescape(encodeURIComponent(n))}function o(n){return i(c(a(n=r(n)),8*n.length))}function u(n,t){return function(n,t){var r,e=a(n),o=[],u=[];for(o[15]=u[15]=void 0,16<e.length&&(e=c(e,8*n.length)),r=0;r<16;r+=1)o[r]=909522486^e[r],u[r]=1549556828^e[r];return t=c(o.concat(a(t)),512+8*t.length),i(c(u.concat(t),640))}(r(n),r(t))}function t(n,t,r){return t?r?u(t,n):e(u(t,n)):r?o(n):e(o(n))}"function"==typeof define&&define.amd?define(function(){return t}):"object"==typeof module&&module.exports?module.exports=t:n.md5=t}(this);
|
2977094657/ZsxqCrawler
| 4,967
|
frontend/src/components/ImageGallery.tsx
|
'use client';
import React, { useState } from 'react';
import Lightbox from 'yet-another-react-lightbox';
import Zoom from 'yet-another-react-lightbox/plugins/zoom';
import Fullscreen from 'yet-another-react-lightbox/plugins/fullscreen';
import { apiClient } from '@/lib/api';
interface ImageData {
image_id: string;
original?: { url: string };
large?: { url: string };
thumbnail?: { url: string };
}
interface ImageGalleryProps {
images: ImageData[];
className?: string;
size?: 'small' | 'medium' | 'large';
groupId?: string;
}
const ImageGallery: React.FC<ImageGalleryProps> = ({ images, className = '', size = 'medium', groupId }) => {
const [lightboxOpen, setLightboxOpen] = useState(false);
const [currentImageIndex, setCurrentImageIndex] = useState(0);
// 如果没有图片,不渲染组件
if (!images || images.length === 0) {
return null;
}
// 准备 lightbox 的图片数据
const lightboxSlides = images.map((image) => ({
src: apiClient.getProxyImageUrl(image.original?.url || image.large?.url || image.thumbnail?.url || '', groupId),
alt: '话题图片',
}));
// 处理缩略图点击
const handleThumbnailClick = (index: number) => {
setCurrentImageIndex(index);
setLightboxOpen(true);
};
// 获取缩略图URL,优先使用thumbnail,然后large,最后original
const getThumbnailUrl = (image: ImageData) => {
return apiClient.getProxyImageUrl(
image.thumbnail?.url || image.large?.url || image.original?.url || '',
groupId
);
};
// 获取预览图URL,优先使用original,然后large
const getPreviewUrl = (image: ImageData) => {
return apiClient.getProxyImageUrl(
image.original?.url || image.large?.url || image.thumbnail?.url || '',
groupId
);
};
// 根据size属性获取对应的样式类(固定缩略图盒子尺寸,避免加载时宽度抖动)
const getSizeClasses = () => {
switch (size) {
case 'small':
return 'w-16 h-16';
case 'large':
return 'w-40 h-40';
case 'medium':
default:
return 'w-32 h-32';
}
};
return (
<div className={`space-y-2 w-full max-w-full overflow-hidden ${className}`}>
{/* 缩略图网格 */}
<div className="flex gap-2 overflow-x-auto pb-2 w-full">
{images.map((image, index) => (
<div key={image.image_id} className={`relative flex-shrink-0 ${getSizeClasses()}`}>
<img
src={getThumbnailUrl(image)}
alt={`话题图片 ${index + 1}`}
className={`w-full h-full rounded-lg border border-gray-200 cursor-pointer hover:opacity-90 transition-opacity object-cover`}
loading="lazy"
decoding="async"
onClick={() => handleThumbnailClick(index)}
onError={(e) => {
// 图片加载失败时的处理
const target = e.currentTarget;
if (target.src.includes('thumbnail') && image.large?.url) {
target.src = apiClient.getProxyImageUrl(image.large.url, groupId);
} else if (target.src.includes('large') && image.original?.url) {
target.src = apiClient.getProxyImageUrl(image.original.url, groupId);
} else {
// 所有尺寸都失败时,显示占位符
target.style.display = 'none';
}
}}
/>
{/* 多图时显示图片数量标识 */}
{images.length > 1 && (
<div className="absolute top-1 right-1 bg-black bg-opacity-60 text-white text-xs px-1.5 py-0.5 rounded">
{index + 1}/{images.length}
</div>
)}
</div>
))}
</div>
{/* Lightbox 组件 */}
<Lightbox
open={lightboxOpen}
close={() => setLightboxOpen(false)}
slides={lightboxSlides}
index={currentImageIndex}
// 启用插件
plugins={[Zoom, Fullscreen]}
// 配置选项
carousel={{
finite: images.length <= 1, // 单图时不循环
}}
// 缩放配置
zoom={{
maxZoomPixelRatio: 3, // 最大缩放比例
zoomInMultiplier: 2, // 缩放倍数
doubleTapDelay: 300, // 双击延迟
doubleClickDelay: 300, // 双击延迟
doubleClickMaxStops: 2, // 双击最大停止次数
keyboardMoveDistance: 300, // 键盘移动距离(最大化)
wheelZoomDistanceFactor: 10, // 滚轮缩放距离因子(最小化以提高灵敏度)
pinchZoomDistanceFactor: 10, // 捏合缩放距离因子(最小化以提高灵敏度)
scrollToZoom: true, // 滚轮缩放
}}
render={{
buttonPrev: images.length <= 1 ? () => null : undefined,
buttonNext: images.length <= 1 ? () => null : undefined,
}}
// 样式配置
styles={{
container: {
backgroundColor: 'rgba(0, 0, 0, 0.9)',
zIndex: 9999,
position: 'fixed',
top: 0,
left: 0,
width: '100vw',
height: '100vh'
},
}}
// 动画配置
animation={{
fade: 300,
swipe: 500,
zoom: 200, // 缩放动画时间,减少以提高响应速度
}}
/>
</div>
);
};
export default ImageGallery;
|
281677160/openwrt-package
| 9,168
|
luci-app-passwall/luasrc/passwall/server_app.lua
|
#!/usr/bin/lua
local action = arg[1]
local api = require "luci.passwall.api"
local sys = api.sys
local uci = api.uci
local jsonc = api.jsonc
local CONFIG = "passwall_server"
local CONFIG_PATH = "/tmp/etc/" .. CONFIG
local NFT_INCLUDE_FILE = CONFIG_PATH .. "/" .. CONFIG .. ".nft"
local LOG_APP_FILE = "/tmp/log/" .. CONFIG .. ".log"
local TMP_BIN_PATH = CONFIG_PATH .. "/bin"
local require_dir = "luci.passwall."
local ipt_bin = sys.exec("echo -n $(/usr/share/passwall/iptables.sh get_ipt_bin)")
local ip6t_bin = sys.exec("echo -n $(/usr/share/passwall/iptables.sh get_ip6t_bin)")
local nft_flag = api.is_finded("fw4") and "1" or "0"
local function log(...)
local f, err = io.open(LOG_APP_FILE, "a")
if f and err == nil then
local str = os.date("%Y-%m-%d %H:%M:%S: ") .. table.concat({...}, " ")
f:write(str .. "\n")
f:close()
end
end
local function cmd(cmd)
sys.call(cmd)
end
local function ipt(arg)
if ipt_bin and #ipt_bin > 0 then
cmd(ipt_bin .. " -w " .. arg)
end
end
local function ip6t(arg)
if ip6t_bin and #ip6t_bin > 0 then
cmd(ip6t_bin .. " -w " .. arg)
end
end
local function ln_run(s, d, command, output)
if not output then
output = "/dev/null"
end
d = TMP_BIN_PATH .. "/" .. d
cmd(string.format('[ ! -f "%s" ] && ln -s %s %s 2>/dev/null', d, s, d))
return string.format("%s >%s 2>&1 &", d .. " " .. command, output)
end
local function gen_include()
cmd(string.format("echo '#!/bin/sh' > /tmp/etc/%s.include", CONFIG))
local function extract_rules(n, a)
local _ipt = ipt_bin
if n == "6" then
_ipt = ip6t_bin
end
local result = "*" .. a
result = result .. "\n" .. sys.exec(_ipt .. '-save -t ' .. a .. ' | grep "PSW-SERVER" | sed -e "s/^-A \\(INPUT\\)/-I \\1 1/"')
result = result .. "COMMIT"
return result
end
local f, err = io.open("/tmp/etc/" .. CONFIG .. ".include", "a")
if f and err == nil then
if nft_flag == "0" then
f:write(ipt_bin .. '-save -c | grep -v "PSW-SERVER" | ' .. ipt_bin .. '-restore -c' .. "\n")
f:write(ipt_bin .. '-restore -n <<-EOT' .. "\n")
f:write(extract_rules("4", "filter") .. "\n")
f:write("EOT" .. "\n")
f:write(ip6t_bin .. '-save -c | grep -v "PSW-SERVER" | ' .. ip6t_bin .. '-restore -c' .. "\n")
f:write(ip6t_bin .. '-restore -n <<-EOT' .. "\n")
f:write(extract_rules("6", "filter") .. "\n")
f:write("EOT" .. "\n")
f:close()
else
f:write("nft -f " .. NFT_INCLUDE_FILE .. "\n")
f:close()
end
end
end
local function start()
local enabled = tonumber(uci:get(CONFIG, "@global[0]", "enable") or 0)
if enabled == nil or enabled == 0 then
return
end
cmd(string.format("mkdir -p %s %s", CONFIG_PATH, TMP_BIN_PATH))
cmd(string.format("touch %s", LOG_APP_FILE))
if nft_flag == "0" then
ipt("-N PSW-SERVER")
ipt("-I INPUT -j PSW-SERVER")
ip6t("-N PSW-SERVER")
ip6t("-I INPUT -j PSW-SERVER")
else
nft_file, err = io.open(NFT_INCLUDE_FILE, "w")
nft_file:write('#!/usr/sbin/nft -f\n')
nft_file:write('add chain inet fw4 PSW-SERVER\n')
nft_file:write('flush chain inet fw4 PSW-SERVER\n')
nft_file:write('insert rule inet fw4 input position 0 jump PSW-SERVER comment "PSW-SERVER"\n')
end
uci:foreach(CONFIG, "user", function(user)
local id = user[".name"]
local enable = user.enable
if enable and tonumber(enable) == 1 then
local enable_log = user.log
local log_path = nil
if enable_log and enable_log == "1" then
log_path = CONFIG_PATH .. "/" .. id .. ".log"
else
log_path = nil
end
local remarks = user.remarks
local port = tonumber(user.port)
local bin
local config = {}
local config_file = CONFIG_PATH .. "/" .. id .. ".json"
local udp_forward = 1
local type = user.type or ""
if type == "Socks" then
local auth = ""
if user.auth and user.auth == "1" then
local username = user.username or ""
local password = user.password or ""
if username ~= "" and password ~= "" then
username = "-u " .. username
password = "-P " .. password
auth = username .. " " .. password
end
end
bin = ln_run("/usr/bin/microsocks", "microsocks_" .. id, string.format("-i :: -p %s %s", port, auth), log_path)
elseif type == "SS" or type == "SSR" then
if user.custom == "1" and user.config_str then
config = jsonc.parse(api.base64Decode(user.config_str))
else
config = require(require_dir .. "util_shadowsocks").gen_config_server(user)
end
local udp_param = ""
udp_forward = tonumber(user.udp_forward) or 1
if udp_forward == 1 then
udp_param = "-u"
end
type = type:lower()
bin = ln_run("/usr/bin/" .. type .. "-server", type .. "-server", "-c " .. config_file .. " " .. udp_param, log_path)
elseif type == "SS-Rust" then
if user.custom == "1" and user.config_str then
config = jsonc.parse(api.base64Decode(user.config_str))
else
config = require(require_dir .. "util_shadowsocks").gen_config_server(user)
end
bin = ln_run("/usr/bin/ssserver", "ssserver", "-c " .. config_file, log_path)
elseif type == "Xray" then
if user.custom == "1" and user.config_str then
config = jsonc.parse(api.base64Decode(user.config_str))
if log_path then
if not config.log then
config.log = {}
end
config.log.loglevel = user.loglevel
end
else
config = require(require_dir .. "util_xray").gen_config_server(user)
end
bin = ln_run(api.get_app_path("xray"), "xray", "run -c " .. config_file, log_path)
elseif type == "sing-box" then
if user.custom == "1" and user.config_str then
config = jsonc.parse(api.base64Decode(user.config_str))
if log_path then
if not config.log then
config.log = {}
end
config.log.timestamp = true
config.log.disabled = false
config.log.level = user.loglevel
config.log.output = log_path
end
else
config = require(require_dir .. "util_sing-box").gen_config_server(user)
end
bin = ln_run(api.get_app_path("sing-box"), "sing-box", "run -c " .. config_file, log_path)
elseif type == "Hysteria2" then
if user.custom == "1" and user.config_str then
config = jsonc.parse(api.base64Decode(user.config_str))
else
config = require(require_dir .. "util_hysteria2").gen_config_server(user)
end
bin = ln_run(api.get_app_path("hysteria"), "hysteria", "-c " .. config_file .. " server", log_path)
elseif type == "Trojan" then
config = require(require_dir .. "util_trojan").gen_config_server(user)
bin = ln_run("/usr/sbin/trojan", "trojan", "-c " .. config_file, log_path)
elseif type == "Trojan-Plus" then
config = require(require_dir .. "util_trojan").gen_config_server(user)
bin = ln_run("/usr/sbin/trojan-plus", "trojan-plus", "-c " .. config_file, log_path)
end
if next(config) then
local f, err = io.open(config_file, "w")
if f and err == nil then
f:write(jsonc.stringify(config, 1))
f:close()
end
log(string.format("%s 生成配置文件并运行 - %s", remarks, config_file))
end
if bin then
cmd(bin)
end
local bind_local = user.bind_local or 0
if bind_local and tonumber(bind_local) ~= 1 and port then
if nft_flag == "0" then
ipt(string.format('-A PSW-SERVER -p tcp --dport %s -m comment --comment "%s" -j ACCEPT', port, remarks))
ip6t(string.format('-A PSW-SERVER -p tcp --dport %s -m comment --comment "%s" -j ACCEPT', port, remarks))
if udp_forward == 1 then
ipt(string.format('-A PSW-SERVER -p udp --dport %s -m comment --comment "%s" -j ACCEPT', port, remarks))
ip6t(string.format('-A PSW-SERVER -p udp --dport %s -m comment --comment "%s" -j ACCEPT', port, remarks))
end
else
nft_file:write(string.format('add rule inet fw4 PSW-SERVER meta l4proto tcp tcp dport {%s} counter accept comment "%s"\n', port, remarks))
if udp_forward == 1 then
nft_file:write(string.format('add rule inet fw4 PSW-SERVER meta l4proto udp udp dport {%s} counter accept comment "%s"\n', port, remarks))
end
end
end
end
end)
if nft_flag == "1" then
nft_file:write("add rule inet fw4 PSW-SERVER return\n")
nft_file:close()
cmd("nft -f " .. NFT_INCLUDE_FILE)
end
gen_include()
end
local function stop()
cmd(string.format("/bin/busybox top -bn1 | grep -v 'grep' | grep '%s/' | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1", CONFIG_PATH))
if nft_flag == "0" then
ipt("-D INPUT -j PSW-SERVER 2>/dev/null")
ipt("-F PSW-SERVER 2>/dev/null")
ipt("-X PSW-SERVER 2>/dev/null")
ip6t("-D INPUT -j PSW-SERVER 2>/dev/null")
ip6t("-F PSW-SERVER 2>/dev/null")
ip6t("-X PSW-SERVER 2>/dev/null")
else
local nft_cmd = "handles=$(nft -a list chain inet fw4 input | grep -E \"PSW-SERVER\" | awk -F '# handle ' '{print$2}')\n for handle in $handles; do\n nft delete rule inet fw4 input handle ${handle} 2>/dev/null\n done"
cmd(nft_cmd)
cmd("nft flush chain inet fw4 PSW-SERVER 2>/dev/null")
cmd("nft delete chain inet fw4 PSW-SERVER 2>/dev/null")
end
cmd(string.format("rm -rf %s %s /tmp/etc/%s.include", CONFIG_PATH, LOG_APP_FILE, CONFIG))
end
if action then
if action == "start" then
start()
elseif action == "stop" then
stop()
end
end
|
2977094657/ZsxqCrawler
| 12,929
|
frontend/src/components/DownloadSettingsDialog.tsx
|
'use client';
import React, { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
interface DownloadSettingsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
downloadInterval: number;
longSleepInterval: number;
filesPerBatch: number;
onSettingsChange: (settings: {
downloadInterval: number;
longSleepInterval: number;
filesPerBatch: number;
downloadIntervalMin?: number;
downloadIntervalMax?: number;
longSleepIntervalMin?: number;
longSleepIntervalMax?: number;
}) => void;
}
export default function DownloadSettingsDialog({
open,
onOpenChange,
downloadInterval,
longSleepInterval,
filesPerBatch,
onSettingsChange,
}: DownloadSettingsDialogProps) {
const [localDownloadInterval, setLocalDownloadInterval] = useState(downloadInterval);
const [localLongSleepInterval, setLocalLongSleepInterval] = useState(longSleepInterval);
const [localFilesPerBatch, setLocalFilesPerBatch] = useState(filesPerBatch);
// 新增范围设置状态
const [downloadIntervalMin, setDownloadIntervalMin] = useState(15);
const [downloadIntervalMax, setDownloadIntervalMax] = useState(30);
const [longSleepIntervalMin, setLongSleepIntervalMin] = useState(30);
const [longSleepIntervalMax, setLongSleepIntervalMax] = useState(60);
const [useRandomInterval, setUseRandomInterval] = useState(true);
const [selectedPreset, setSelectedPreset] = useState<'fast' | 'standard' | 'safe' | null>('fast');
// 当对话框打开时,同步当前设置值
useEffect(() => {
if (open) {
setLocalDownloadInterval(downloadInterval);
setLocalLongSleepInterval(longSleepInterval);
setLocalFilesPerBatch(filesPerBatch);
// 如果是第一次打开,默认设置为快速配置
if (downloadInterval === 1.0 && longSleepInterval === 60.0 && filesPerBatch === 10) {
setPreset('fast');
}
}
}, [open, downloadInterval, longSleepInterval, filesPerBatch]);
const handleSave = () => {
// 确保所有值都有默认值
const finalDownloadIntervalMin = downloadIntervalMin || 15;
const finalDownloadIntervalMax = downloadIntervalMax || 30;
const finalLongSleepIntervalMin = longSleepIntervalMin || 30;
const finalLongSleepIntervalMax = longSleepIntervalMax || 60;
const finalFilesPerBatch = localFilesPerBatch || 10;
onSettingsChange({
downloadInterval: useRandomInterval
? (finalDownloadIntervalMin + finalDownloadIntervalMax) / 2
: Math.round((finalDownloadIntervalMin + finalDownloadIntervalMax) / 2),
longSleepInterval: useRandomInterval
? (finalLongSleepIntervalMin + finalLongSleepIntervalMax) / 2
: Math.round((finalLongSleepIntervalMin + finalLongSleepIntervalMax) / 2),
filesPerBatch: finalFilesPerBatch,
downloadIntervalMin: useRandomInterval ? finalDownloadIntervalMin : undefined,
downloadIntervalMax: useRandomInterval ? finalDownloadIntervalMax : undefined,
longSleepIntervalMin: useRandomInterval ? finalLongSleepIntervalMin : undefined,
longSleepIntervalMax: useRandomInterval ? finalLongSleepIntervalMax : undefined,
});
onOpenChange(false);
};
const handleCancel = () => {
// 重置为原始值
setLocalDownloadInterval(downloadInterval);
setLocalLongSleepInterval(longSleepInterval);
setLocalFilesPerBatch(filesPerBatch);
onOpenChange(false);
};
const setPreset = (preset: 'fast' | 'standard' | 'safe') => {
setUseRandomInterval(true);
setSelectedPreset(preset);
switch (preset) {
case 'fast':
setDownloadIntervalMin(15);
setDownloadIntervalMax(30);
setLongSleepIntervalMin(30);
setLongSleepIntervalMax(60);
setLocalFilesPerBatch(30);
break;
case 'standard':
setDownloadIntervalMin(30);
setDownloadIntervalMax(60);
setLongSleepIntervalMin(60);
setLongSleepIntervalMax(180);
setLocalFilesPerBatch(15);
break;
case 'safe':
setDownloadIntervalMin(60);
setDownloadIntervalMax(180);
setLongSleepIntervalMin(180);
setLongSleepIntervalMax(300);
setLocalFilesPerBatch(5);
break;
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>下载间隔设置</DialogTitle>
<DialogDescription>
调整文件下载的间隔时间和批次设置,以避免触发反爬虫机制。
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{/* 间隔模式选择 */}
<div className="space-y-2">
<Label>间隔模式</Label>
<div className="flex gap-2">
<Button
type="button"
variant={useRandomInterval ? "default" : "outline"}
size="sm"
onClick={() => setUseRandomInterval(true)}
className="flex-1"
>
随机间隔 (推荐)
</Button>
<Button
type="button"
variant={!useRandomInterval ? "default" : "outline"}
size="sm"
onClick={() => setUseRandomInterval(false)}
className="flex-1"
>
固定间隔
</Button>
</div>
</div>
{/* 下载间隔范围 */}
<div className="space-y-2">
<Label>下载间隔范围 (秒)</Label>
<div className="flex gap-2 items-center">
<Input
type="number"
min="1"
max="300"
value={downloadIntervalMin}
onChange={(e) => {
const value = e.target.value;
if (value === '') {
setDownloadIntervalMin('');
} else {
const num = parseInt(value);
if (!isNaN(num)) {
setDownloadIntervalMin(num);
}
}
}}
onBlur={(e) => {
if (e.target.value === '') {
setDownloadIntervalMin(15);
}
}}
placeholder="15"
className="flex-1"
/>
<span className="text-sm text-gray-500">-</span>
<Input
type="number"
min="1"
max="300"
value={downloadIntervalMax}
onChange={(e) => {
const value = e.target.value;
if (value === '') {
setDownloadIntervalMax('');
} else {
const num = parseInt(value);
if (!isNaN(num)) {
setDownloadIntervalMax(num);
}
}
}}
onBlur={(e) => {
if (e.target.value === '') {
setDownloadIntervalMax(30);
}
}}
placeholder="30"
className="flex-1"
/>
</div>
<p className="text-xs text-gray-500">
{useRandomInterval
? '每次下载文件后的随机等待时间范围'
: `每次下载文件后的固定等待时间 (取中间值: ${Math.round((downloadIntervalMin + downloadIntervalMax) / 2)}秒)`
}
</p>
</div>
{/* 长休眠间隔范围 */}
<div className="space-y-2">
<Label>长休眠间隔范围 (秒)</Label>
<div className="flex gap-2 items-center">
<Input
type="number"
min="10"
max="3600"
value={longSleepIntervalMin}
onChange={(e) => {
const value = e.target.value;
if (value === '') {
setLongSleepIntervalMin('');
} else {
const num = parseInt(value);
if (!isNaN(num)) {
setLongSleepIntervalMin(num);
}
}
}}
onBlur={(e) => {
if (e.target.value === '') {
setLongSleepIntervalMin(30);
}
}}
placeholder="30"
className="flex-1"
/>
<span className="text-sm text-gray-500">-</span>
<Input
type="number"
min="10"
max="3600"
value={longSleepIntervalMax}
onChange={(e) => {
const value = e.target.value;
if (value === '') {
setLongSleepIntervalMax('');
} else {
const num = parseInt(value);
if (!isNaN(num)) {
setLongSleepIntervalMax(num);
}
}
}}
onBlur={(e) => {
if (e.target.value === '') {
setLongSleepIntervalMax(60);
}
}}
placeholder="60"
className="flex-1"
/>
</div>
<p className="text-xs text-gray-500">
{useRandomInterval
? '达到批次大小后的随机长时间休眠范围'
: `达到批次大小后的固定长时间休眠 (取中间值: ${Math.round((longSleepIntervalMin + longSleepIntervalMax) / 2)}秒)`
}
</p>
</div>
{/* 批次大小 */}
<div className="space-y-2">
<Label htmlFor="filesPerBatch">批次大小 (个文件)</Label>
<Input
id="filesPerBatch"
type="number"
min="1"
max="100"
step="1"
value={localFilesPerBatch}
onChange={(e) => {
const value = e.target.value;
if (value === '') {
setLocalFilesPerBatch('');
} else {
const num = parseInt(value);
if (!isNaN(num)) {
setLocalFilesPerBatch(num);
}
}
}}
onBlur={(e) => {
if (e.target.value === '') {
setLocalFilesPerBatch(10);
}
}}
placeholder="10"
/>
<p className="text-xs text-gray-500">下载多少个文件后触发长休眠</p>
</div>
{/* 快速配置 */}
<div className="space-y-2">
<Label>快速配置</Label>
<div className="flex gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setPreset('fast')}
className={`flex-1 ${
selectedPreset === 'fast'
? 'bg-green-100 text-green-800 border-green-300 hover:bg-green-200'
: 'bg-gray-50 text-gray-500 border-gray-200 hover:bg-gray-100'
}`}
>
快速
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setPreset('standard')}
className={`flex-1 ${
selectedPreset === 'standard'
? 'bg-blue-100 text-blue-800 border-blue-300 hover:bg-blue-200'
: 'bg-gray-50 text-gray-500 border-gray-200 hover:bg-gray-100'
}`}
>
标准
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setPreset('safe')}
className={`flex-1 ${
selectedPreset === 'safe'
? 'bg-orange-100 text-orange-800 border-orange-300 hover:bg-orange-200'
: 'bg-gray-50 text-gray-500 border-gray-200 hover:bg-gray-100'
}`}
>
安全
</Button>
</div>
<div className="text-xs text-gray-500 space-y-1">
<div>• 快速: 15-30秒间隔, 30秒-1分钟长休眠, 30个文件/批次</div>
<div>• 标准: 30秒-1分钟间隔, 1-3分钟长休眠, 15个文件/批次</div>
<div>• 安全: 1-3分钟间隔, 3-5分钟长休眠, 5个文件/批次</div>
</div>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={handleCancel}>
取消
</Button>
<Button type="button" onClick={handleSave}>
保存设置
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
|
2977094657/ZsxqCrawler
| 16,991
|
frontend/src/components/TaskLogViewer.tsx
|
'use client';
import { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { X, Minimize2, Maximize2, Terminal, MessageSquare, Square, AlertTriangle } from 'lucide-react';
import {
AlertDialog,
AlertDialogAction,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
interface TaskLogViewerProps {
taskId: string | null;
onClose: () => void;
isMinimized?: boolean;
onToggleMinimize?: () => void;
inline?: boolean;
onTaskStop?: () => void;
}
interface LogMessage {
type: 'log' | 'status' | 'heartbeat';
message?: string;
status?: string;
}
export default function TaskLogViewer({
taskId,
onClose,
isMinimized = false,
onToggleMinimize,
inline = false,
onTaskStop
}: TaskLogViewerProps) {
const [logs, setLogs] = useState<string[]>([]);
const [status, setStatus] = useState<string>('pending');
const [isConnected, setIsConnected] = useState(false);
const [stopping, setStopping] = useState(false);
const [showExpiredDialog, setShowExpiredDialog] = useState(false);
const [expiredMessage, setExpiredMessage] = useState('');
const scrollAreaRef = useRef<HTMLDivElement>(null);
const eventSourceRef = useRef<EventSource | null>(null);
useEffect(() => {
if (!taskId) return;
// 建立SSE连接
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';
const eventSource = new EventSource(`${API_BASE_URL}/api/tasks/${taskId}/stream`);
eventSourceRef.current = eventSource;
eventSource.onopen = () => {
setIsConnected(true);
console.log('SSE连接已建立');
};
eventSource.onmessage = (event) => {
try {
const data: LogMessage = JSON.parse(event.data);
if (data.type === 'log' && data.message) {
setLogs(prev => [...prev, data.message!]);
// 检测过期相关的日志消息
if (data.message.includes('会员已过期') || data.message.includes('成员体验已到期')) {
setExpiredMessage(data.message);
setShowExpiredDialog(true);
}
} else if (data.type === 'status' && data.status) {
setStatus(data.status);
// 不再将状态信息添加到日志中,只更新状态
// 如果任务完成或失败,关闭SSE连接
if (data.status === 'completed' || data.status === 'failed') {
console.log(`任务${data.status},关闭SSE连接`);
eventSource.close();
setIsConnected(false);
// 调用任务停止回调
if (onTaskStop) {
onTaskStop();
}
}
}
// heartbeat 不需要处理
} catch (error) {
console.error('解析SSE消息失败:', error);
}
};
eventSource.onerror = (error) => {
console.error('SSE连接错误:', error);
setIsConnected(false);
};
return () => {
eventSource.close();
eventSourceRef.current = null;
};
}, [taskId]);
// 监听状态变化,确保任务完成时关闭连接
useEffect(() => {
if ((status === 'completed' || status === 'failed' || status === 'cancelled') && eventSourceRef.current) {
console.log(`状态变为${status},确保SSE连接已关闭`);
eventSourceRef.current.close();
eventSourceRef.current = null;
setIsConnected(false);
}
}, [status]);
// 自动滚动到底部
useEffect(() => {
if (scrollAreaRef.current) {
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
if (scrollContainer) {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
}
}, [logs]);
const getStatusColor = (status: string) => {
switch (status) {
case 'completed':
return 'bg-gradient-to-r from-emerald-100 to-green-100 text-emerald-800 border border-emerald-200';
case 'running':
return 'bg-gradient-to-r from-blue-100 to-indigo-100 text-blue-800 border border-blue-200';
case 'failed':
return 'bg-gradient-to-r from-red-100 to-rose-100 text-red-800 border border-red-200';
case 'pending':
return 'bg-gradient-to-r from-amber-100 to-yellow-100 text-amber-800 border border-amber-200';
case 'idle':
return 'bg-gradient-to-r from-gray-100 to-slate-100 text-gray-600 border border-gray-300';
default:
return 'bg-gradient-to-r from-gray-100 to-slate-100 text-gray-800 border border-gray-200';
}
};
const getStatusText = (status: string) => {
switch (status) {
case 'completed':
return '已完成';
case 'running':
return '运行中';
case 'failed':
return '失败';
case 'pending':
return '等待中';
default:
return status;
}
};
// 日志解析函数
const getLogType = (log: string): string => {
// 优先匹配具体的日志模式
if (log.includes('🚀') || log.includes('开始') || log.includes('初始化')) return 'start';
if (log.includes('✅') || log.includes('完成') || log.includes('成功')) return 'success';
if (log.includes('❌') || log.includes('失败') || log.includes('错误') || log.includes('异常')) return 'error';
if (log.includes('📊') || log.includes('累计') || log.includes('统计') || log.includes('进度报告')) return 'stats';
if (log.includes('💾') || log.includes('存储') || log.includes('数据库') || log.includes('页面存储')) return 'storage';
if (log.includes('⏰') || log.includes('时间') || log.includes('时间范围')) return 'time';
if (log.includes('🔍') || log.includes('调试') || log.includes('详细信息')) return 'debug';
if (log.includes('⚠️') || log.includes('警告') || log.includes('跳过')) return 'warning';
if (log.includes('📡') || log.includes('连接') || log.includes('API') || log.includes('请求')) return 'network';
if (log.includes('🎉') || log.includes('总结') || log.includes('最终状态')) return 'summary';
if (log.includes('📄') || log.includes('页数') || log.includes('话题')) return 'progress';
if (log.includes('[状态]')) return 'status';
return 'info';
};
const cleanLogContent = (log: string): string => {
// 移除时间戳前缀 [HH:MM:SS]
return log.replace(/^\[\d{2}:\d{2}:\d{2}\]\s*/, '');
};
const extractTimestamp = (log: string): string => {
// 提取时间戳 [HH:MM:SS]
const match = log.match(/^\[(\d{2}:\d{2}:\d{2})\]/);
return match ? match[1] : new Date().toLocaleTimeString();
};
const handleStopTask = async () => {
if (!taskId || stopping) return;
try {
setStopping(true);
const { apiClient } = await import('@/lib/api');
await apiClient.stopTask(taskId);
if (onTaskStop) {
onTaskStop();
}
} catch (error) {
console.error('停止任务失败:', error);
} finally {
setStopping(false);
}
};
const getLogIcon = (type: string): string => {
switch (type) {
case 'start': return '🚀';
case 'success': return '✅';
case 'error': return '❌';
case 'stats': return '📊';
case 'storage': return '💾';
case 'time': return '⏰';
case 'debug': return '🔍';
case 'warning': return '⚠️';
case 'network': return '📡';
case 'summary': return '🎉';
case 'progress': return '📄';
case 'status': return '🔄';
default: return 'ℹ️';
}
};
const getLogStyle = (type: string): string => {
switch (type) {
case 'start': return 'border-blue-400 bg-blue-50';
case 'success': return 'border-green-400 bg-green-50';
case 'error': return 'border-red-400 bg-red-50';
case 'stats': return 'border-purple-400 bg-purple-50';
case 'storage': return 'border-indigo-400 bg-indigo-50';
case 'time': return 'border-orange-400 bg-orange-50';
case 'debug': return 'border-gray-400 bg-gray-50';
case 'warning': return 'border-yellow-400 bg-yellow-50';
case 'network': return 'border-cyan-400 bg-cyan-50';
case 'summary': return 'border-emerald-400 bg-emerald-50';
case 'progress': return 'border-teal-400 bg-teal-50';
case 'status': return 'border-sky-400 bg-sky-50';
default: return 'border-gray-300 bg-gray-50';
}
};
// 移除这个检查,让组件在没有taskId时也能显示框架
// inline模式的渲染
if (inline) {
return (
<>
<div className="h-full flex flex-col p-3">
{/* 状态栏 */}
<div className="flex items-center justify-between p-3 bg-white rounded-lg border border-gray-200 mb-3">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<div className={`w-2 h-2 rounded-full ${
taskId && isConnected ? 'bg-green-500' : 'bg-gray-400'
}`} />
<span className="text-sm text-gray-600">状态:</span>
<Badge className={`text-xs px-2 py-1 ${getStatusColor(taskId ? status : 'idle')}`}>
{taskId ? getStatusText(status) : '空闲'}
</Badge>
</div>
{/* 停止按钮 */}
{taskId && status === 'running' && (
<Button
variant="destructive"
size="sm"
onClick={handleStopTask}
disabled={stopping}
className="h-6 px-2 text-xs"
>
<Square className="h-3 w-3 mr-1" />
{stopping ? '停止中' : '停止'}
</Button>
)}
</div>
<div className="text-xs text-gray-500 font-mono">
{taskId ? `${taskId.slice(0, 8)}...` : '无任务'}
</div>
</div>
{/* 日志内容 */}
<div className="flex-1 bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col">
<div className="bg-gray-50 px-3 py-2 border-b border-gray-200 flex-shrink-0">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Terminal className="h-3 w-3 text-gray-500" />
<span className="text-xs font-medium text-gray-600">日志</span>
</div>
<span className="text-xs text-gray-500">{taskId ? `${logs.length} 条` : '等待任务'}</span>
</div>
</div>
<ScrollArea className="flex-1 w-full" ref={scrollAreaRef}>
<div className="p-3 space-y-1">
{!taskId ? (
<div className="text-gray-500 text-center py-12">
<div className="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
<MessageSquare className="h-8 w-8 text-gray-400" />
</div>
<p className="font-medium text-gray-600 mb-1">暂无运行中的任务</p>
<p className="text-sm text-gray-500">执行爬取操作后将在此显示实时日志</p>
</div>
) : logs.length === 0 ? (
<div className="text-gray-500 text-center py-12">
<div className="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
<MessageSquare className="h-8 w-8 text-gray-400" />
</div>
<p className="font-medium text-gray-600 mb-1">等待任务开始</p>
<p className="text-sm text-gray-500">日志将在任务执行时实时显示</p>
</div>
) : (
logs.map((log, index) => {
// 解析日志类型和内容
const logType = getLogType(log);
const logContent = cleanLogContent(log);
const timestamp = extractTimestamp(log);
return (
<div key={index} className={`text-sm py-1 px-3 rounded border-l-2 ${getLogStyle(logType)} hover:bg-opacity-80 transition-colors`}>
<div className="flex items-center gap-3">
<div className="text-xs text-gray-500 font-mono flex-shrink-0 w-16">
{timestamp}
</div>
<div className="text-gray-900 flex-1 min-w-0">
{logContent}
</div>
</div>
</div>
);
})
)}
{taskId && status === 'running' && (
<div className="flex items-center gap-3 text-blue-600 py-1 px-3 bg-blue-50 rounded border-l-2 border-blue-400">
<div className="text-xs text-gray-500 font-mono flex-shrink-0 w-16">
{new Date().toLocaleTimeString()}
</div>
<div className="flex items-center gap-2 flex-1">
<div className="w-2 h-2 bg-blue-600 rounded-full animate-pulse"></div>
<span className="text-sm">任务正在执行中...</span>
</div>
</div>
)}
</div>
</ScrollArea>
</div>
{/* 过期提示对话框 */}
<AlertDialog open={showExpiredDialog} onOpenChange={setShowExpiredDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-amber-500" />
知识星球会员已过期
</AlertDialogTitle>
<AlertDialogDescription>
{expiredMessage || '您的知识星球会员体验已到期,无法继续进行数据采集操作。请续费后重试。'}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction onClick={() => setShowExpiredDialog(false)}>
我知道了
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</>
);
}
// 原有的浮动窗口模式
return (
<Card className={`fixed bottom-4 right-4 w-96 border border-gray-300 shadow-none z-50 ${
isMinimized ? 'h-12' : 'h-80'
} transition-all duration-200`}>
<CardHeader className="pb-2 px-3 py-2 bg-gray-900 text-white rounded-t-lg">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Terminal className="h-4 w-4" />
<CardTitle className="text-sm font-mono">
任务日志 - {taskId.slice(0, 8)}
</CardTitle>
</div>
<div className="flex items-center gap-2">
<Badge className={`text-xs px-2 py-0 ${getStatusColor(status)}`}>
{getStatusText(status)}
</Badge>
<div className={`w-2 h-2 rounded-full ${
isConnected ? 'bg-green-400' : 'bg-red-400'
}`} title={isConnected ? '已连接' : '未连接'} />
{onToggleMinimize && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-white hover:bg-gray-700"
onClick={onToggleMinimize}
>
{isMinimized ? <Maximize2 className="h-3 w-3" /> : <Minimize2 className="h-3 w-3" />}
</Button>
)}
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-white hover:bg-gray-700"
onClick={onClose}
>
<X className="h-3 w-3" />
</Button>
</div>
</div>
</CardHeader>
{!isMinimized && (
<CardContent className="p-0 bg-black text-green-400 font-mono text-xs">
<ScrollArea className="h-64 w-full" ref={scrollAreaRef}>
<div className="p-3 space-y-1">
{logs.length === 0 ? (
<div className="text-gray-500">等待日志输出...</div>
) : (
logs.map((log, index) => (
<div key={index} className="whitespace-pre-wrap break-words">
{log}
</div>
))
)}
{status === 'running' && (
<div className="flex items-center gap-1 text-blue-400">
<span className="animate-pulse">●</span>
<span>任务运行中...</span>
</div>
)}
</div>
</ScrollArea>
</CardContent>
)}
{/* 过期提示对话框 */}
<AlertDialog open={showExpiredDialog} onOpenChange={setShowExpiredDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-amber-500" />
知识星球会员已过期
</AlertDialogTitle>
<AlertDialogDescription>
{expiredMessage || '您的知识星球会员体验已到期,无法继续进行数据采集操作。请续费后重试。'}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction onClick={() => setShowExpiredDialog(false)}>
我知道了
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Card>
);
}
|
281677160/openwrt-package
| 4,913
|
luci-app-passwall/luasrc/passwall/util_shadowsocks.lua
|
module("luci.passwall.util_shadowsocks", package.seeall)
local api = require "luci.passwall.api"
local uci = api.uci
local jsonc = api.jsonc
function gen_config_server(node)
local config = {}
config.server_port = tonumber(node.port)
config.password = node.password
config.timeout = tonumber(node.timeout)
config.fast_open = (node.tcp_fast_open and node.tcp_fast_open == "1") and true or false
config.method = node.method
if node.type == "SS-Rust" then
config.server = "::"
config.mode = "tcp_and_udp"
else
config.server = {"[::0]", "0.0.0.0"}
end
if node.type == "SSR" then
config.protocol = node.protocol
config.protocol_param = node.protocol_param
config.obfs = node.obfs
config.obfs_param = node.obfs_param
end
return config
end
local plugin_sh, plugin_bin
function gen_config(var)
local node_id = var["-node"]
if not node_id then
print("-node 不能为空")
return
end
local node = uci:get_all("passwall", node_id)
local server_host = var["-server_host"] or node.address
local server_port = var["-server_port"] or node.port
local local_addr = var["-local_addr"]
local local_port = var["-local_port"]
local mode = var["-mode"]
local local_socks_address = var["-local_socks_address"] or "0.0.0.0"
local local_socks_port = var["-local_socks_port"]
local local_socks_username = var["-local_socks_username"]
local local_socks_password = var["-local_socks_password"]
local local_http_address = var["-local_http_address"] or "0.0.0.0"
local local_http_port = var["-local_http_port"]
local local_http_username = var["-local_http_username"]
local local_http_password = var["-local_http_password"]
local local_tcp_redir_port = var["-local_tcp_redir_port"]
local local_tcp_redir_address = var["-local_tcp_redir_address"] or "0.0.0.0"
local local_udp_redir_port = var["-local_udp_redir_port"]
local local_udp_redir_address = var["-local_udp_redir_address"] or "0.0.0.0"
if api.is_ipv6(server_host) then
server_host = api.get_ipv6_only(server_host)
end
local server = server_host
local plugin_file
if node.plugin and node.plugin ~= "" and node.plugin ~= "none" then
plugin_sh = var["-plugin_sh"] or ""
plugin_file = (plugin_sh ~="") and plugin_sh or node.plugin
plugin_bin = node.plugin
end
local config = {
server = server,
server_port = tonumber(server_port),
local_address = local_addr,
local_port = tonumber(local_port),
password = node.password,
method = node.method,
timeout = tonumber(node.timeout),
fast_open = (node.tcp_fast_open and node.tcp_fast_open == "true") and true or false,
reuse_port = true,
tcp_tproxy = var["-tcp_tproxy"] and true or nil
}
if node.type == "SS" then
config.plugin = plugin_file or nil
config.plugin_opts = (plugin_file) and node.plugin_opts or nil
config.mode = mode
elseif node.type == "SSR" then
config.protocol = node.protocol
config.protocol_param = node.protocol_param
config.obfs = node.obfs
config.obfs_param = node.obfs_param
elseif node.type == "SS-Rust" then
config = {
servers = {
{
address = server,
port = tonumber(server_port),
method = node.method,
password = node.password,
timeout = tonumber(node.timeout),
plugin = plugin_file or nil,
plugin_opts = (plugin_file) and node.plugin_opts or nil
}
},
locals = {},
fast_open = (node.tcp_fast_open and node.tcp_fast_open == "true") and true or false
}
if local_socks_address and local_socks_port then
table.insert(config.locals, {
local_address = local_socks_address,
local_port = tonumber(local_socks_port),
mode = "tcp_and_udp"
})
end
if local_http_address and local_http_port then
table.insert(config.locals, {
protocol = "http",
local_address = local_http_address,
local_port = tonumber(local_http_port)
})
end
if local_tcp_redir_address and local_tcp_redir_port then
table.insert(config.locals, {
protocol = "redir",
mode = "tcp_only",
tcp_redir = var["-tcp_tproxy"] and "tproxy" or nil,
local_address = local_tcp_redir_address,
local_port = tonumber(local_tcp_redir_port)
})
end
if local_udp_redir_address and local_udp_redir_port then
table.insert(config.locals, {
protocol = "redir",
mode = "udp_only",
local_address = local_udp_redir_address,
local_port = tonumber(local_udp_redir_port)
})
end
end
return jsonc.stringify(config, 1)
end
_G.gen_config = gen_config
if arg[1] then
local func =_G[arg[1]]
if func then
print(func(api.get_function_args(arg)))
if plugin_sh and plugin_sh ~="" and plugin_bin then
local f = io.open(plugin_sh, "w")
f:write("#!/bin/sh\n")
f:write("export PATH=/usr/sbin:/usr/bin:/sbin:/bin:/root/bin:$PATH\n")
f:write(plugin_bin .. " $@ &\n")
f:write("echo $! > " .. plugin_sh:gsub("%.sh$", ".pid") .. "\n")
f:write("wait\n")
f:close()
luci.sys.call("chmod +x " .. plugin_sh)
end
end
end
|
2951121599/Bili-Insight
| 146,705
|
chrome-extension/scripts/[email protected]
|
/**
* Combined by jsDelivr.
* Original files:
* - /npm/[email protected]/dist/browser/index.min.js
* - /npm/[email protected]/dist/index.min.js
*
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
*/
/*! markmap-lib v0.14.4 | MIT License */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("katex")):"function"==typeof define&&define.amd?define(["exports","katex"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).markmap=e.markmap||{},e.window.katex)}(this,(function(e,t){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var n=r(t);function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i.apply(this,arguments)}
/*! markmap-common v0.14.2 | MIT License */class o{constructor(){this.listeners=[]}tap(e){return this.listeners.push(e),()=>this.revoke(e)}revoke(e){const t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}revokeAll(){this.listeners.splice(0)}call(...e){for(const t of this.listeners)t(...e)}}function s(){return s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s.apply(this,arguments)}const a=["textContent"];function l(e){return e.replace(/[&<"]/g,(e=>({"&":"&","<":"<",'"':"""}[e])))}function c(e,t){return`<${e}${t?Object.entries(t).map((([e,t])=>{if(null!=t&&!1!==t)return e=` ${l(e)}`,!0===t?e:`${e}="${l(t)}"`})).filter(Boolean).join(""):""}>`}function p(e,t,r){return null==t?c(e,r):c(e,r)+(t||"")+function(e){return`</${e}>`}(e)}function u(e,t){return e.map((e=>{if("script"===e.type){const t=e.data,{textContent:r}=t,n=function(e,t){if(null==e)return{};var r,n,i={},o=Object.keys(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||(i[r]=e[r]);return i}(t,a);return p("script",r||"",n)}if("iife"===e.type){const{fn:n,getParams:i}=e.data;return p("script",(r=function(e,t){const r=t.map((e=>"function"==typeof e?e.toString():JSON.stringify(null!=e?e:null))).join(",");return`(${e.toString()})(${r})`}(n,(null==i?void 0:i(t))||[]),r.replace(/<(\/script>)/g,"\\x3c$2")))}var r;return""}))}function f(e,{before:t,after:r}){return function(...n){const i={args:n,thisObj:this};try{t&&t(i)}catch(e){}i.result=e.apply(i.thisObj,i.args);try{r&&r(i)}catch(e){}return i.result}}function h(e,t,r){const n=document.createElement(e);return t&&Object.entries(t).forEach((([e,t])=>{n[e]=t})),r&&Object.entries(r).forEach((([e,t])=>{n.setAttribute(e,t)})),n}Math.random().toString(36).slice(2,8);const d=function(e){const t={};return function(...r){const n=`${r[0]}`;let i=t[n];return i||(i={value:e(...r)},t[n]=i),i.value}}((e=>{document.head.append(h("link",{rel:"preload",as:"script",href:e}))}));async function g(e,t){if(!e.loaded&&("script"===e.type&&(e.loaded=new Promise(((t,r)=>{var n;document.head.append(h("script",s({},e.data,{onload:t,onerror:r}))),null!=(n=e.data)&&n.src||t(void 0)})).then((()=>{e.loaded=!0}))),"iife"===e.type)){const{fn:r,getParams:n}=e.data;r(...(null==n?void 0:n(t))||[]),e.loaded=!0}await e.loaded}async function m(e,t){const r=e.filter((e=>{var t;return"script"===e.type&&(null==(t=e.data)?void 0:t.src)}));r.length>1&&r.forEach((e=>d(e.data.src))),t=s({getMarkmap:()=>window.markmap},t);for(const r of e)await g(r,t)}const b=["https://cdn.jsdelivr.net/npm/[email protected]","https://cdn.jsdelivr.net/npm/[email protected]"].map((e=>({type:"script",data:{src:e}})));var v={Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",AMP:"&",amp:"&",And:"⩓",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",ap:"≈",apacir:"⩯",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",Barwed:"⌆",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",Because:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxDL:"╗",boxDl:"╖",boxdL:"╕",boxdl:"┐",boxDR:"╔",boxDr:"╓",boxdR:"╒",boxdr:"┌",boxH:"═",boxh:"─",boxHD:"╦",boxHd:"╤",boxhD:"╥",boxhd:"┬",boxHU:"╩",boxHu:"╧",boxhU:"╨",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxUL:"╝",boxUl:"╜",boxuL:"╛",boxul:"┘",boxUR:"╚",boxUr:"╙",boxuR:"╘",boxur:"└",boxV:"║",boxv:"│",boxVH:"╬",boxVh:"╫",boxvH:"╪",boxvh:"┼",boxVL:"╣",boxVl:"╢",boxvL:"╡",boxvl:"┤",boxVR:"╠",boxVr:"╟",boxvR:"╞",boxvr:"├",bprime:"‵",Breve:"˘",breve:"˘",brvbar:"¦",Bscr:"ℬ",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",Cap:"⋒",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",CenterDot:"·",centerdot:"·",Cfr:"ℭ",cfr:"𝔠",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",cir:"○",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",Colon:"∷",colon:":",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",Conint:"∯",conint:"∮",ContourIntegral:"∮",Copf:"ℂ",copf:"𝕔",coprod:"∐",Coproduct:"∐",COPY:"©",copy:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",Cross:"⨯",cross:"✗",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",Cup:"⋓",cup:"∪",cupbrcap:"⩈",CupCap:"≍",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",Dagger:"‡",dagger:"†",daleth:"ℸ",Darr:"↡",dArr:"⇓",darr:"↓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",DD:"ⅅ",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",Diamond:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",Downarrow:"⇓",downarrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",ecir:"≖",Ecirc:"Ê",ecirc:"ê",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",eDot:"≑",edot:"ė",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp:" ",emsp13:" ",emsp14:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",Escr:"ℰ",escr:"ℯ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",ExponentialE:"ⅇ",exponentiale:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",ForAll:"∀",forall:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",Fscr:"ℱ",fscr:"𝒻",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",gE:"≧",ge:"≥",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",Gg:"⋙",gg:"≫",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gl:"≷",gla:"⪥",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gnE:"≩",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",GT:">",Gt:"≫",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",hArr:"⇔",harr:"↔",harrcir:"⥈",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",Hfr:"ℌ",hfr:"𝔥",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",Hopf:"ℍ",hopf:"𝕙",horbar:"―",HorizontalLine:"─",Hscr:"ℋ",hscr:"𝒽",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",Ifr:"ℑ",ifr:"𝔦",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Im:"ℑ",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",Implies:"⇒",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",Int:"∬",int:"∫",intcal:"⊺",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"",InvisibleTimes:"",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",Iscr:"ℐ",iscr:"𝒾",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",Lang:"⟪",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",Larr:"↞",lArr:"⇐",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",lAtail:"⤛",latail:"⤙",late:"⪭",lates:"⪭︀",lBarr:"⤎",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",lE:"≦",le:"≤",LeftAngleBracket:"⟨",LeftArrow:"←",Leftarrow:"⇐",leftarrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",Ll:"⋘",ll:"≪",llarr:"⇇",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnap:"⪉",lnapprox:"⪉",lnE:"≨",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftarrow:"⟵",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longleftrightarrow:"⟷",longmapsto:"⟼",LongRightArrow:"⟶",Longrightarrow:"⟹",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"",lrtri:"⊿",lsaquo:"‹",Lscr:"ℒ",lscr:"𝓁",Lsh:"↰",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",LT:"<",Lt:"≪",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",Mscr:"ℳ",mscr:"𝓂",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",ne:"≠",nearhk:"⤤",neArr:"⇗",nearr:"↗",nearrow:"↗",nedot:"≐̸",NegativeMediumSpace:"",NegativeThickSpace:"",NegativeThinSpace:"",NegativeVeryThinSpace:"",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlArr:"⇍",nlarr:"↚",nldr:"‥",nlE:"≦̸",nle:"≰",nLeftarrow:"⇍",nleftarrow:"↚",nLeftrightarrow:"⇎",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"",NonBreakingSpace:" ",Nopf:"ℕ",nopf:"𝕟",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nRightarrow:"⇏",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nVDash:"⊯",nVdash:"⊮",nvDash:"⊭",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwArr:"⇖",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",ocir:"⊚",Ocirc:"Ô",ocirc:"ô",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",Or:"⩔",or:"∨",orarr:"↻",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",Otimes:"⨷",otimes:"⊗",otimesas:"⨶",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",par:"∥",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",Popf:"ℙ",popf:"𝕡",pound:"£",Pr:"⪻",pr:"≺",prap:"⪷",prcue:"≼",prE:"⪳",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",Prime:"″",prime:"′",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportion:"∷",Proportional:"∝",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",Qopf:"ℚ",qopf:"𝕢",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",QUOT:'"',quot:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",Rang:"⟫",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",Rarr:"↠",rArr:"⇒",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",rAtail:"⤜",ratail:"⤚",ratio:"∶",rationals:"ℚ",RBarr:"⤐",rBarr:"⤏",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",Re:"ℜ",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",REG:"®",reg:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",Rfr:"ℜ",rfr:"𝔯",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrow:"→",Rightarrow:"⇒",rightarrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",Ropf:"ℝ",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",Rscr:"ℛ",rscr:"𝓇",Rsh:"↱",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",Sc:"⪼",sc:"≻",scap:"⪸",Scaron:"Š",scaron:"š",sccue:"≽",scE:"⪴",sce:"⪰",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",searhk:"⤥",seArr:"⇘",searr:"↘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",Square:"□",square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",Sub:"⋐",sub:"⊂",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",Subset:"⋐",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",Sum:"∑",sum:"∑",sung:"♪",Sup:"⋑",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",Supset:"⋑",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swArr:"⇙",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:"\t",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",Therefore:"∴",therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:" ",thinsp:" ",ThinSpace:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",Tilde:"∼",tilde:"˜",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",TRADE:"™",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",Uarr:"↟",uArr:"⇑",uarr:"↑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrow:"↑",Uparrow:"⇑",uparrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",Updownarrow:"⇕",updownarrow:"↕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",upsi:"υ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTee:"⊥",UpTeeArrow:"↥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",vArr:"⇕",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",Vbar:"⫫",vBar:"⫨",vBarv:"⫩",Vcy:"В",vcy:"в",VDash:"⊫",Vdash:"⊩",vDash:"⊨",vdash:"⊢",Vdashl:"⫦",Vee:"⋁",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",Verbar:"‖",verbar:"|",Vert:"‖",vert:"|",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",Wedge:"⋀",wedge:"∧",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",Xi:"Ξ",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",Yuml:"Ÿ",yuml:"ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"",Zeta:"Ζ",zeta:"ζ",Zfr:"ℨ",zfr:"𝔷",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",Zopf:"ℤ",zopf:"𝕫",Zscr:"𝒵",zscr:"𝓏",zwj:"",zwnj:""},k=Object.prototype.hasOwnProperty;function y(e){return r=e,(t=v)&&k.call(t,r)?v[e]:e;var t,r}var A=Object.prototype.hasOwnProperty;function w(e){var t=[].slice.call(arguments,1);return t.forEach((function(t){if(t){if("object"!=typeof t)throw new TypeError(t+"must be object");Object.keys(t).forEach((function(r){e[r]=t[r]}))}})),e}var x=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function _(e){return e.indexOf("\\")<0?e:e.replace(x,"$1")}function C(e){return!(e>=55296&&e<=57343)&&(!(e>=64976&&e<=65007)&&(65535!=(65535&e)&&65534!=(65535&e)&&(!(e>=0&&e<=8)&&(11!==e&&(!(e>=14&&e<=31)&&(!(e>=127&&e<=159)&&!(e>1114111)))))))}function q(e){if(e>65535){var t=55296+((e-=65536)>>10),r=56320+(1023&e);return String.fromCharCode(t,r)}return String.fromCharCode(e)}var S=/&([a-z#][a-z0-9]{1,31});/gi,E=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function M(e,t){var r=0,n=y(t);return t!==n?n:35===t.charCodeAt(0)&&E.test(t)&&C(r="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10))?q(r):e}function L(e){return e.indexOf("&")<0?e:e.replace(S,M)}var T=/[&<>"]/,I=/[&<>"]/g,O={"&":"&","<":"<",">":">",'"':"""};function N(e){return O[e]}function j(e){return T.test(e)?e.replace(I,N):e}var D={};function R(e,t){return++t>=e.length-2?t:"paragraph_open"===e[t].type&&e[t].tight&&"inline"===e[t+1].type&&0===e[t+1].content.length&&"paragraph_close"===e[t+2].type&&e[t+2].tight?R(e,t+2):t}D.blockquote_open=function(){return"<blockquote>\n"},D.blockquote_close=function(e,t){return"</blockquote>"+U(e,t)},D.code=function(e,t){return e[t].block?"<pre><code>"+j(e[t].content)+"</code></pre>"+U(e,t):"<code>"+j(e[t].content)+"</code>"},D.fence=function(e,t,r,n,i){var o,s,a,l,c=e[t],p="",u=r.langPrefix;if(c.params){if(s=(o=c.params.split(/\s+/g)).join(" "),a=i.rules.fence_custom,l=o[0],a&&A.call(a,l))return i.rules.fence_custom[o[0]](e,t,r,n,i);p=' class="'+u+j(L(_(s)))+'"'}return"<pre><code"+p+">"+(r.highlight&&r.highlight.apply(r.highlight,[c.content].concat(o))||j(c.content))+"</code></pre>"+U(e,t)},D.fence_custom={},D.heading_open=function(e,t){return"<h"+e[t].hLevel+">"},D.heading_close=function(e,t){return"</h"+e[t].hLevel+">\n"},D.hr=function(e,t,r){return(r.xhtmlOut?"<hr />":"<hr>")+U(e,t)},D.bullet_list_open=function(){return"<ul>\n"},D.bullet_list_close=function(e,t){return"</ul>"+U(e,t)},D.list_item_open=function(){return"<li>"},D.list_item_close=function(){return"</li>\n"},D.ordered_list_open=function(e,t){var r=e[t];return"<ol"+(r.order>1?' start="'+r.order+'"':"")+">\n"},D.ordered_list_close=function(e,t){return"</ol>"+U(e,t)},D.paragraph_open=function(e,t){return e[t].tight?"":"<p>"},D.paragraph_close=function(e,t){var r=!(e[t].tight&&t&&"inline"===e[t-1].type&&!e[t-1].content);return(e[t].tight?"":"</p>")+(r?U(e,t):"")},D.link_open=function(e,t,r){var n=e[t].title?' title="'+j(L(e[t].title))+'"':"",i=r.linkTarget?' target="'+r.linkTarget+'"':"";return'<a href="'+j(e[t].href)+'"'+n+i+">"},D.link_close=function(){return"</a>"},D.image=function(e,t,r){var n=' src="'+j(e[t].src)+'"',i=e[t].title?' title="'+j(L(e[t].title))+'"':"";return"<img"+n+(' alt="'+(e[t].alt?j(L(_(e[t].alt))):"")+'"')+i+(r.xhtmlOut?" /":"")+">"},D.table_open=function(){return"<table>\n"},D.table_close=function(){return"</table>\n"},D.thead_open=function(){return"<thead>\n"},D.thead_close=function(){return"</thead>\n"},D.tbody_open=function(){return"<tbody>\n"},D.tbody_close=function(){return"</tbody>\n"},D.tr_open=function(){return"<tr>"},D.tr_close=function(){return"</tr>\n"},D.th_open=function(e,t){var r=e[t];return"<th"+(r.align?' style="text-align:'+r.align+'"':"")+">"},D.th_close=function(){return"</th>"},D.td_open=function(e,t){var r=e[t];return"<td"+(r.align?' style="text-align:'+r.align+'"':"")+">"},D.td_close=function(){return"</td>"},D.strong_open=function(){return"<strong>"},D.strong_close=function(){return"</strong>"},D.em_open=function(){return"<em>"},D.em_close=function(){return"</em>"},D.del_open=function(){return"<del>"},D.del_close=function(){return"</del>"},D.ins_open=function(){return"<ins>"},D.ins_close=function(){return"</ins>"},D.mark_open=function(){return"<mark>"},D.mark_close=function(){return"</mark>"},D.sub=function(e,t){return"<sub>"+j(e[t].content)+"</sub>"},D.sup=function(e,t){return"<sup>"+j(e[t].content)+"</sup>"},D.hardbreak=function(e,t,r){return r.xhtmlOut?"<br />\n":"<br>\n"},D.softbreak=function(e,t,r){return r.breaks?r.xhtmlOut?"<br />\n":"<br>\n":"\n"},D.text=function(e,t){return j(e[t].content)},D.htmlblock=function(e,t){return e[t].content},D.htmltag=function(e,t){return e[t].content},D.abbr_open=function(e,t){return'<abbr title="'+j(L(e[t].title))+'">'},D.abbr_close=function(){return"</abbr>"},D.footnote_ref=function(e,t){var r=Number(e[t].id+1).toString(),n="fnref"+r;return e[t].subId>0&&(n+=":"+e[t].subId),'<sup class="footnote-ref"><a href="#fn'+r+'" id="'+n+'">['+r+"]</a></sup>"},D.footnote_block_open=function(e,t,r){return(r.xhtmlOut?'<hr class="footnotes-sep" />\n':'<hr class="footnotes-sep">\n')+'<section class="footnotes">\n<ol class="footnotes-list">\n'},D.footnote_block_close=function(){return"</ol>\n</section>\n"},D.footnote_open=function(e,t){return'<li id="fn'+Number(e[t].id+1).toString()+'" class="footnote-item">'},D.footnote_close=function(){return"</li>\n"},D.footnote_anchor=function(e,t){var r="fnref"+Number(e[t].id+1).toString();return e[t].subId>0&&(r+=":"+e[t].subId),' <a href="#'+r+'" class="footnote-backref">↩</a>'},D.dl_open=function(){return"<dl>\n"},D.dt_open=function(){return"<dt>"},D.dd_open=function(){return"<dd>"},D.dl_close=function(){return"</dl>\n"},D.dt_close=function(){return"</dt>\n"},D.dd_close=function(){return"</dd>\n"};var U=D.getBreak=function(e,t){return(t=R(e,t))<e.length&&"list_item_close"===e[t].type?"":"\n"};function F(){this.rules=w({},D),this.getBreak=D.getBreak}function z(){this.__rules__=[],this.__cache__=null}function P(e,t,r,n,i){this.src=e,this.env=n,this.options=r,this.parser=t,this.tokens=i,this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache=[],this.isInLabel=!1,this.linkLevel=0,this.linkContent="",this.labelUnmatchedScopes=0}function B(e,t){var r,n,i,o=-1,s=e.posMax,a=e.pos,l=e.isInLabel;if(e.isInLabel)return-1;if(e.labelUnmatchedScopes)return e.labelUnmatchedScopes--,-1;for(e.pos=t+1,e.isInLabel=!0,r=1;e.pos<s;){if(91===(i=e.src.charCodeAt(e.pos)))r++;else if(93===i&&0===--r){n=!0;break}e.parser.skipToken(e)}return n?(o=e.pos,e.labelUnmatchedScopes=0):e.labelUnmatchedScopes=r-1,e.pos=a,e.isInLabel=l,o}function V(e,t,r,n){var i,o,s,a,l,c;if(42!==e.charCodeAt(0))return-1;if(91!==e.charCodeAt(1))return-1;if(-1===e.indexOf("]:"))return-1;if((o=B(i=new P(e,t,r,n,[]),1))<0||58!==e.charCodeAt(o+1))return-1;for(a=i.posMax,s=o+2;s<a&&10!==i.src.charCodeAt(s);s++);return l=e.slice(2,o),0===(c=e.slice(o+2,s).trim()).length?-1:(n.abbreviations||(n.abbreviations={}),void 0===n.abbreviations[":"+l]&&(n.abbreviations[":"+l]=c),s)}function $(e){var t=L(e);try{t=decodeURI(t)}catch(e){}return encodeURI(t)}function G(e,t){var r,n,i,o=t,s=e.posMax;if(60===e.src.charCodeAt(t)){for(t++;t<s;){if(10===(r=e.src.charCodeAt(t)))return!1;if(62===r)return i=$(_(e.src.slice(o+1,t))),!!e.parser.validateLink(i)&&(e.pos=t+1,e.linkContent=i,!0);92===r&&t+1<s?t+=2:t++}return!1}for(n=0;t<s&&32!==(r=e.src.charCodeAt(t))&&!(r<32||127===r);)if(92===r&&t+1<s)t+=2;else{if(40===r&&++n>1)break;if(41===r&&--n<0)break;t++}return o!==t&&(i=_(e.src.slice(o,t)),!!e.parser.validateLink(i)&&(e.linkContent=i,e.pos=t,!0))}function H(e,t){var r,n=t,i=e.posMax,o=e.src.charCodeAt(t);if(34!==o&&39!==o&&40!==o)return!1;for(t++,40===o&&(o=41);t<i;){if((r=e.src.charCodeAt(t))===o)return e.pos=t+1,e.linkContent=_(e.src.slice(n+1,t)),!0;92===r&&t+1<i?t+=2:t++}return!1}function Z(e){return e.trim().replace(/\s+/g," ").toUpperCase()}function Y(e,t,r,n){var i,o,s,a,l,c,p,u,f;if(91!==e.charCodeAt(0))return-1;if(-1===e.indexOf("]:"))return-1;if((o=B(i=new P(e,t,r,n,[]),0))<0||58!==e.charCodeAt(o+1))return-1;for(a=i.posMax,s=o+2;s<a&&(32===(l=i.src.charCodeAt(s))||10===l);s++);if(!G(i,s))return-1;for(p=i.linkContent,c=s=i.pos,s+=1;s<a&&(32===(l=i.src.charCodeAt(s))||10===l);s++);for(s<a&&c!==s&&H(i,s)?(u=i.linkContent,s=i.pos):(u="",s=c);s<a&&32===i.src.charCodeAt(s);)s++;return s<a&&10!==i.src.charCodeAt(s)?-1:(f=Z(e.slice(1,o)),void 0===n.references[f]&&(n.references[f]={title:u,href:p}),s)}F.prototype.renderInline=function(e,t,r){for(var n=this.rules,i=e.length,o=0,s="";i--;)s+=n[e[o].type](e,o++,t,r,this);return s},F.prototype.render=function(e,t,r){for(var n=this.rules,i=e.length,o=-1,s="";++o<i;)"inline"===e[o].type?s+=this.renderInline(e[o].children,t,r):s+=n[e[o].type](e,o,t,r,this);return s},z.prototype.__find__=function(e){for(var t=this.__rules__.length,r=-1;t--;)if(this.__rules__[++r].name===e)return r;return-1},z.prototype.__compile__=function(){var e=this,t=[""];e.__rules__.forEach((function(e){e.enabled&&e.alt.forEach((function(e){t.indexOf(e)<0&&t.push(e)}))})),e.__cache__={},t.forEach((function(t){e.__cache__[t]=[],e.__rules__.forEach((function(r){r.enabled&&(t&&r.alt.indexOf(t)<0||e.__cache__[t].push(r.fn))}))}))},z.prototype.at=function(e,t,r){var n=this.__find__(e),i=r||{};if(-1===n)throw new Error("Parser rule not found: "+e);this.__rules__[n].fn=t,this.__rules__[n].alt=i.alt||[],this.__cache__=null},z.prototype.before=function(e,t,r,n){var i=this.__find__(e),o=n||{};if(-1===i)throw new Error("Parser rule not found: "+e);this.__rules__.splice(i,0,{name:t,enabled:!0,fn:r,alt:o.alt||[]}),this.__cache__=null},z.prototype.after=function(e,t,r,n){var i=this.__find__(e),o=n||{};if(-1===i)throw new Error("Parser rule not found: "+e);this.__rules__.splice(i+1,0,{name:t,enabled:!0,fn:r,alt:o.alt||[]}),this.__cache__=null},z.prototype.push=function(e,t,r){var n=r||{};this.__rules__.push({name:e,enabled:!0,fn:t,alt:n.alt||[]}),this.__cache__=null},z.prototype.enable=function(e,t){e=Array.isArray(e)?e:[e],t&&this.__rules__.forEach((function(e){e.enabled=!1})),e.forEach((function(e){var t=this.__find__(e);if(t<0)throw new Error("Rules manager: invalid rule name "+e);this.__rules__[t].enabled=!0}),this),this.__cache__=null},z.prototype.disable=function(e){(e=Array.isArray(e)?e:[e]).forEach((function(e){var t=this.__find__(e);if(t<0)throw new Error("Rules manager: invalid rule name "+e);this.__rules__[t].enabled=!1}),this),this.__cache__=null},z.prototype.getRules=function(e){return null===this.__cache__&&this.__compile__(),this.__cache__[e]||[]},P.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},P.prototype.push=function(e){this.pending&&this.pushPending(),this.tokens.push(e),this.pendingLevel=this.level},P.prototype.cacheSet=function(e,t){for(var r=this.cache.length;r<=e;r++)this.cache.push(0);this.cache[e]=t},P.prototype.cacheGet=function(e){return e<this.cache.length?this.cache[e]:0};var K=" \n()[]'\".,!?-";function J(e){return e.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}var W=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,X=/\((c|tm|r|p)\)/gi,Q={c:"©",r:"®",p:"§",tm:"™"};function ee(e){return e.indexOf("(")<0?e:e.replace(X,(function(e,t){return Q[t.toLowerCase()]}))}var te=/['"]/,re=/['"]/g,ne=/[-\s()\[\]]/;function ie(e,t){return!(t<0||t>=e.length)&&!ne.test(e[t])}function oe(e,t,r){return e.substr(0,t)+r+e.substr(t+1)}var se=[["block",function(e){e.inlineMode?e.tokens.push({type:"inline",content:e.src.replace(/\n/g," ").trim(),level:0,lines:[0,1],children:[]}):e.block.parse(e.src,e.options,e.env,e.tokens)}],["abbr",function(e){var t,r,n,i,o=e.tokens;if(!e.inlineMode)for(t=1,r=o.length-1;t<r;t++)if("paragraph_open"===o[t-1].type&&"inline"===o[t].type&&"paragraph_close"===o[t+1].type){for(n=o[t].content;n.length&&!((i=V(n,e.inline,e.options,e.env))<0);)n=n.slice(i).trim();o[t].content=n,n.length||(o[t-1].tight=!0,o[t+1].tight=!0)}}],["references",function(e){var t,r,n,i,o=e.tokens;if(e.env.references=e.env.references||{},!e.inlineMode)for(t=1,r=o.length-1;t<r;t++)if("inline"===o[t].type&&"paragraph_open"===o[t-1].type&&"paragraph_close"===o[t+1].type){for(n=o[t].content;n.length&&!((i=Y(n,e.inline,e.options,e.env))<0);)n=n.slice(i).trim();o[t].content=n,n.length||(o[t-1].tight=!0,o[t+1].tight=!0)}}],["inline",function(e){var t,r,n,i=e.tokens;for(r=0,n=i.length;r<n;r++)"inline"===(t=i[r]).type&&e.inline.parse(t.content,e.options,e.env,t.children)}],["footnote_tail",function(e){var t,r,n,i,o,s,a,l,c,p=0,u=!1,f={};if(e.env.footnotes&&(e.tokens=e.tokens.filter((function(e){return"footnote_reference_open"===e.type?(u=!0,l=[],c=e.label,!1):"footnote_reference_close"===e.type?(u=!1,f[":"+c]=l,!1):(u&&l.push(e),!u)})),e.env.footnotes.list)){for(s=e.env.footnotes.list,e.tokens.push({type:"footnote_block_open",level:p++}),t=0,r=s.length;t<r;t++){for(e.tokens.push({type:"footnote_open",id:t,level:p++}),s[t].tokens?((a=[]).push({type:"paragraph_open",tight:!1,level:p++}),a.push({type:"inline",content:"",level:p,children:s[t].tokens}),a.push({type:"paragraph_close",tight:!1,level:--p})):s[t].label&&(a=f[":"+s[t].label]),e.tokens=e.tokens.concat(a),o="paragraph_close"===e.tokens[e.tokens.length-1].type?e.tokens.pop():null,i=s[t].count>0?s[t].count:1,n=0;n<i;n++)e.tokens.push({type:"footnote_anchor",id:t,subId:n,level:p});o&&e.tokens.push(o),e.tokens.push({type:"footnote_close",level:--p})}e.tokens.push({type:"footnote_block_close",level:--p})}}],["abbr2",function(e){var t,r,n,i,o,s,a,l,c,p,u,f,h=e.tokens;if(e.env.abbreviations)for(e.env.abbrRegExp||(f="(^|["+K.split("").map(J).join("")+"])("+Object.keys(e.env.abbreviations).map((function(e){return e.substr(1)})).sort((function(e,t){return t.length-e.length})).map(J).join("|")+")($|["+K.split("").map(J).join("")+"])",e.env.abbrRegExp=new RegExp(f,"g")),p=e.env.abbrRegExp,r=0,n=h.length;r<n;r++)if("inline"===h[r].type)for(t=(i=h[r].children).length-1;t>=0;t--)if("text"===(o=i[t]).type){for(l=0,s=o.content,p.lastIndex=0,c=o.level,a=[];u=p.exec(s);)p.lastIndex>l&&a.push({type:"text",content:s.slice(l,u.index+u[1].length),level:c}),a.push({type:"abbr_open",title:e.env.abbreviations[":"+u[2]],level:c++}),a.push({type:"text",content:u[2],level:c}),a.push({type:"abbr_close",level:--c}),l=p.lastIndex-u[3].length;a.length&&(l<s.length&&a.push({type:"text",content:s.slice(l),level:c}),h[r].children=i=[].concat(i.slice(0,t),a,i.slice(t+1)))}}],["replacements",function(e){var t,r,n,i,o;if(e.options.typographer)for(o=e.tokens.length-1;o>=0;o--)if("inline"===e.tokens[o].type)for(t=(i=e.tokens[o].children).length-1;t>=0;t--)"text"===(r=i[t]).type&&(n=ee(n=r.content),W.test(n)&&(n=n.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---([^-]|$)/gm,"$1—$2").replace(/(^|\s)--(\s|$)/gm,"$1–$2").replace(/(^|[^-\s])--([^-\s]|$)/gm,"$1–$2")),r.content=n)}],["smartquotes",function(e){var t,r,n,i,o,s,a,l,c,p,u,f,h,d,g,m,b;if(e.options.typographer)for(b=[],g=e.tokens.length-1;g>=0;g--)if("inline"===e.tokens[g].type)for(m=e.tokens[g].children,b.length=0,t=0;t<m.length;t++)if("text"===(r=m[t]).type&&!te.test(r.text)){for(a=m[t].level,h=b.length-1;h>=0&&!(b[h].level<=a);h--);b.length=h+1,o=0,s=(n=r.content).length;e:for(;o<s&&(re.lastIndex=o,i=re.exec(n));)if(l=!ie(n,i.index-1),o=i.index+1,d="'"===i[0],(c=!ie(n,o))||l){if(u=!c,f=!l)for(h=b.length-1;h>=0&&(p=b[h],!(b[h].level<a));h--)if(p.single===d&&b[h].level===a){p=b[h],d?(m[p.token].content=oe(m[p.token].content,p.pos,e.options.quotes[2]),r.content=oe(r.content,i.index,e.options.quotes[3])):(m[p.token].content=oe(m[p.token].content,p.pos,e.options.quotes[0]),r.content=oe(r.content,i.index,e.options.quotes[1])),b.length=h;continue e}u?b.push({token:t,pos:i.index,single:d,level:a}):f&&d&&(r.content=oe(r.content,i.index,"’"))}else d&&(r.content=oe(r.content,i.index,"’"))}}]];function ae(){this.options={},this.ruler=new z;for(var e=0;e<se.length;e++)this.ruler.push(se[e][0],se[e][1])}function le(e,t,r,n,i){var o,s,a,l,c,p,u;for(this.src=e,this.parser=t,this.options=r,this.env=n,this.tokens=i,this.bMarks=[],this.eMarks=[],this.tShift=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.parentType="root",this.ddIndent=-1,this.level=0,this.result="",p=0,u=!1,a=l=p=0,c=(s=this.src).length;l<c;l++){if(o=s.charCodeAt(l),!u){if(32===o){p++;continue}u=!0}10!==o&&l!==c-1||(10!==o&&l++,this.bMarks.push(a),this.eMarks.push(l),this.tShift.push(p),u=!1,p=0,a=l+1)}this.bMarks.push(s.length),this.eMarks.push(s.length),this.tShift.push(0),this.lineMax=this.bMarks.length-1}function ce(e,t){var r,n,i;return(n=e.bMarks[t]+e.tShift[t])>=(i=e.eMarks[t])||42!==(r=e.src.charCodeAt(n++))&&45!==r&&43!==r||n<i&&32!==e.src.charCodeAt(n)?-1:n}function pe(e,t){var r,n=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];if(n+1>=i)return-1;if((r=e.src.charCodeAt(n++))<48||r>57)return-1;for(;;){if(n>=i)return-1;if(!((r=e.src.charCodeAt(n++))>=48&&r<=57)){if(41===r||46===r)break;return-1}}return n<i&&32!==e.src.charCodeAt(n)?-1:n}ae.prototype.process=function(e){var t,r,n;for(t=0,r=(n=this.ruler.getRules("")).length;t<r;t++)n[t](e)},le.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]},le.prototype.skipEmptyLines=function(e){for(var t=this.lineMax;e<t&&!(this.bMarks[e]+this.tShift[e]<this.eMarks[e]);e++);return e},le.prototype.skipSpaces=function(e){for(var t=this.src.length;e<t&&32===this.src.charCodeAt(e);e++);return e},le.prototype.skipChars=function(e,t){for(var r=this.src.length;e<r&&this.src.charCodeAt(e)===t;e++);return e},le.prototype.skipCharsBack=function(e,t,r){if(e<=r)return e;for(;e>r;)if(t!==this.src.charCodeAt(--e))return e+1;return e},le.prototype.getLines=function(e,t,r,n){var i,o,s,a,l,c=e;if(e>=t)return"";if(c+1===t)return o=this.bMarks[c]+Math.min(this.tShift[c],r),s=n?this.eMarks[c]+1:this.eMarks[c],this.src.slice(o,s);for(a=new Array(t-e),i=0;c<t;c++,i++)(l=this.tShift[c])>r&&(l=r),l<0&&(l=0),o=this.bMarks[c]+l,s=c+1<t||n?this.eMarks[c]+1:this.eMarks[c],a[i]=this.src.slice(o,s);return a.join("")};var ue={};["article","aside","button","blockquote","body","canvas","caption","col","colgroup","dd","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","iframe","li","map","object","ol","output","p","pre","progress","script","section","style","table","tbody","td","textarea","tfoot","th","tr","thead","ul","video"].forEach((function(e){ue[e]=!0}));var fe=/^<([a-zA-Z]{1,15})[\s\/>]/,he=/^<\/([a-zA-Z]{1,15})[\s>]/;function de(e,t){var r=e.bMarks[t]+e.blkIndent,n=e.eMarks[t];return e.src.substr(r,n-r)}function ge(e,t){var r,n,i=e.bMarks[t]+e.tShift[t],o=e.eMarks[t];return i>=o||126!==(n=e.src.charCodeAt(i++))&&58!==n||i===(r=e.skipSpaces(i))||r>=o?-1:r}var me=[["code",function(e,t,r){var n,i;if(e.tShift[t]-e.blkIndent<4)return!1;for(i=n=t+1;n<r;)if(e.isEmpty(n))n++;else{if(!(e.tShift[n]-e.blkIndent>=4))break;i=++n}return e.line=n,e.tokens.push({type:"code",content:e.getLines(t,i,4+e.blkIndent,!0),block:!0,lines:[t,e.line],level:e.level}),!0}],["fences",function(e,t,r,n){var i,o,s,a,l,c=!1,p=e.bMarks[t]+e.tShift[t],u=e.eMarks[t];if(p+3>u)return!1;if(126!==(i=e.src.charCodeAt(p))&&96!==i)return!1;if(l=p,(o=(p=e.skipChars(p,i))-l)<3)return!1;if((s=e.src.slice(p,u).trim()).indexOf("`")>=0)return!1;if(n)return!0;for(a=t;!(++a>=r)&&!((p=l=e.bMarks[a]+e.tShift[a])<(u=e.eMarks[a])&&e.tShift[a]<e.blkIndent);)if(e.src.charCodeAt(p)===i&&!(e.tShift[a]-e.blkIndent>=4||(p=e.skipChars(p,i))-l<o||(p=e.skipSpaces(p))<u)){c=!0;break}return o=e.tShift[t],e.line=a+(c?1:0),e.tokens.push({type:"fence",params:s,content:e.getLines(t+1,a,o,!0),lines:[t,e.line],level:e.level}),!0},["paragraph","blockquote","list"]],["blockquote",function(e,t,r,n){var i,o,s,a,l,c,p,u,f,h,d,g=e.bMarks[t]+e.tShift[t],m=e.eMarks[t];if(g>m)return!1;if(62!==e.src.charCodeAt(g++))return!1;if(e.level>=e.options.maxNesting)return!1;if(n)return!0;for(32===e.src.charCodeAt(g)&&g++,l=e.blkIndent,e.blkIndent=0,a=[e.bMarks[t]],e.bMarks[t]=g,o=(g=g<m?e.skipSpaces(g):g)>=m,s=[e.tShift[t]],e.tShift[t]=g-e.bMarks[t],u=e.parser.ruler.getRules("blockquote"),i=t+1;i<r&&!((g=e.bMarks[i]+e.tShift[i])>=(m=e.eMarks[i]));i++)if(62!==e.src.charCodeAt(g++)){if(o)break;for(d=!1,f=0,h=u.length;f<h;f++)if(u[f](e,i,r,!0)){d=!0;break}if(d)break;a.push(e.bMarks[i]),s.push(e.tShift[i]),e.tShift[i]=-1337}else 32===e.src.charCodeAt(g)&&g++,a.push(e.bMarks[i]),e.bMarks[i]=g,o=(g=g<m?e.skipSpaces(g):g)>=m,s.push(e.tShift[i]),e.tShift[i]=g-e.bMarks[i];for(c=e.parentType,e.parentType="blockquote",e.tokens.push({type:"blockquote_open",lines:p=[t,0],level:e.level++}),e.parser.tokenize(e,t,i),e.tokens.push({type:"blockquote_close",level:--e.level}),e.parentType=c,p[1]=e.line,f=0;f<s.length;f++)e.bMarks[f+t]=a[f],e.tShift[f+t]=s[f];return e.blkIndent=l,!0},["paragraph","blockquote","list"]],["hr",function(e,t,r,n){var i,o,s,a=e.bMarks[t],l=e.eMarks[t];if((a+=e.tShift[t])>l)return!1;if(42!==(i=e.src.charCodeAt(a++))&&45!==i&&95!==i)return!1;for(o=1;a<l;){if((s=e.src.charCodeAt(a++))!==i&&32!==s)return!1;s===i&&o++}return!(o<3)&&(n||(e.line=t+1,e.tokens.push({type:"hr",lines:[t,e.line],level:e.level})),!0)},["paragraph","blockquote","list"]],["list",function(e,t,r,n){var i,o,s,a,l,c,p,u,f,h,d,g,m,b,v,k,y,A,w,x,_,C=!0;if((u=pe(e,t))>=0)g=!0;else{if(!((u=ce(e,t))>=0))return!1;g=!1}if(e.level>=e.options.maxNesting)return!1;if(d=e.src.charCodeAt(u-1),n)return!0;for(b=e.tokens.length,g?(p=e.bMarks[t]+e.tShift[t],h=Number(e.src.substr(p,u-p-1)),e.tokens.push({type:"ordered_list_open",order:h,lines:k=[t,0],level:e.level++})):e.tokens.push({type:"bullet_list_open",lines:k=[t,0],level:e.level++}),i=t,v=!1,A=e.parser.ruler.getRules("list");!(!(i<r)||((f=(m=e.skipSpaces(u))>=e.eMarks[i]?1:m-u)>4&&(f=1),f<1&&(f=1),o=u-e.bMarks[i]+f,e.tokens.push({type:"list_item_open",lines:y=[t,0],level:e.level++}),a=e.blkIndent,l=e.tight,s=e.tShift[t],c=e.parentType,e.tShift[t]=m-e.bMarks[t],e.blkIndent=o,e.tight=!0,e.parentType="list",e.parser.tokenize(e,t,r,!0),e.tight&&!v||(C=!1),v=e.line-t>1&&e.isEmpty(e.line-1),e.blkIndent=a,e.tShift[t]=s,e.tight=l,e.parentType=c,e.tokens.push({type:"list_item_close",level:--e.level}),i=t=e.line,y[1]=i,m=e.bMarks[t],i>=r)||e.isEmpty(i)||e.tShift[i]<e.blkIndent);){for(_=!1,w=0,x=A.length;w<x;w++)if(A[w](e,i,r,!0)){_=!0;break}if(_)break;if(g){if((u=pe(e,i))<0)break}else if((u=ce(e,i))<0)break;if(d!==e.src.charCodeAt(u-1))break}return e.tokens.push({type:g?"ordered_list_close":"bullet_list_close",level:--e.level}),k[1]=i,e.line=i,C&&function(e,t){var r,n,i=e.level+2;for(r=t+2,n=e.tokens.length-2;r<n;r++)e.tokens[r].level===i&&"paragraph_open"===e.tokens[r].type&&(e.tokens[r+2].tight=!0,e.tokens[r].tight=!0,r+=2)}(e,b),!0},["paragraph","blockquote"]],["footnote",function(e,t,r,n){var i,o,s,a,l,c=e.bMarks[t]+e.tShift[t],p=e.eMarks[t];if(c+4>p)return!1;if(91!==e.src.charCodeAt(c))return!1;if(94!==e.src.charCodeAt(c+1))return!1;if(e.level>=e.options.maxNesting)return!1;for(a=c+2;a<p;a++){if(32===e.src.charCodeAt(a))return!1;if(93===e.src.charCodeAt(a))break}return a!==c+2&&(!(a+1>=p||58!==e.src.charCodeAt(++a))&&(n||(a++,e.env.footnotes||(e.env.footnotes={}),e.env.footnotes.refs||(e.env.footnotes.refs={}),l=e.src.slice(c+2,a-2),e.env.footnotes.refs[":"+l]=-1,e.tokens.push({type:"footnote_reference_open",label:l,level:e.level++}),i=e.bMarks[t],o=e.tShift[t],s=e.parentType,e.tShift[t]=e.skipSpaces(a)-a,e.bMarks[t]=a,e.blkIndent+=4,e.parentType="footnote",e.tShift[t]<e.blkIndent&&(e.tShift[t]+=e.blkIndent,e.bMarks[t]-=e.blkIndent),e.parser.tokenize(e,t,r,!0),e.parentType=s,e.blkIndent-=4,e.tShift[t]=o,e.bMarks[t]=i,e.tokens.push({type:"footnote_reference_close",level:--e.level})),!0))},["paragraph"]],["heading",function(e,t,r,n){var i,o,s,a=e.bMarks[t]+e.tShift[t],l=e.eMarks[t];if(a>=l)return!1;if(35!==(i=e.src.charCodeAt(a))||a>=l)return!1;for(o=1,i=e.src.charCodeAt(++a);35===i&&a<l&&o<=6;)o++,i=e.src.charCodeAt(++a);return!(o>6||a<l&&32!==i)&&(n||(l=e.skipCharsBack(l,32,a),(s=e.skipCharsBack(l,35,a))>a&&32===e.src.charCodeAt(s-1)&&(l=s),e.line=t+1,e.tokens.push({type:"heading_open",hLevel:o,lines:[t,e.line],level:e.level}),a<l&&e.tokens.push({type:"inline",content:e.src.slice(a,l).trim(),level:e.level+1,lines:[t,e.line],children:[]}),e.tokens.push({type:"heading_close",hLevel:o,level:e.level})),!0)},["paragraph","blockquote"]],["lheading",function(e,t,r){var n,i,o,s=t+1;return!(s>=r)&&(!(e.tShift[s]<e.blkIndent)&&(!(e.tShift[s]-e.blkIndent>3)&&(!((i=e.bMarks[s]+e.tShift[s])>=(o=e.eMarks[s]))&&((45===(n=e.src.charCodeAt(i))||61===n)&&(i=e.skipChars(i,n),!((i=e.skipSpaces(i))<o)&&(i=e.bMarks[t]+e.tShift[t],e.line=s+1,e.tokens.push({type:"heading_open",hLevel:61===n?1:2,lines:[t,e.line],level:e.level}),e.tokens.push({type:"inline",content:e.src.slice(i,e.eMarks[t]).trim(),level:e.level+1,lines:[t,e.line-1],children:[]}),e.tokens.push({type:"heading_close",hLevel:61===n?1:2,level:e.level}),!0))))))}],["htmlblock",function(e,t,r,n){var i,o,s,a=e.bMarks[t],l=e.eMarks[t],c=e.tShift[t];if(a+=c,!e.options.html)return!1;if(c>3||a+2>=l)return!1;if(60!==e.src.charCodeAt(a))return!1;if(33===(i=e.src.charCodeAt(a+1))||63===i){if(n)return!0}else{if(47!==i&&!function(e){var t=32|e;return t>=97&&t<=122}(i))return!1;if(47===i){if(!(o=e.src.slice(a,l).match(he)))return!1}else if(!(o=e.src.slice(a,l).match(fe)))return!1;if(!0!==ue[o[1].toLowerCase()])return!1;if(n)return!0}for(s=t+1;s<e.lineMax&&!e.isEmpty(s);)s++;return e.line=s,e.tokens.push({type:"htmlblock",level:e.level,lines:[t,e.line],content:e.getLines(t,s,0,!0)}),!0},["paragraph","blockquote"]],["table",function(e,t,r,n){var i,o,s,a,l,c,p,u,f,h,d;if(t+2>r)return!1;if(l=t+1,e.tShift[l]<e.blkIndent)return!1;if((s=e.bMarks[l]+e.tShift[l])>=e.eMarks[l])return!1;if(124!==(i=e.src.charCodeAt(s))&&45!==i&&58!==i)return!1;if(o=de(e,t+1),!/^[-:| ]+$/.test(o))return!1;if((c=o.split("|"))<=2)return!1;for(u=[],a=0;a<c.length;a++){if(!(f=c[a].trim())){if(0===a||a===c.length-1)continue;return!1}if(!/^:?-+:?$/.test(f))return!1;58===f.charCodeAt(f.length-1)?u.push(58===f.charCodeAt(0)?"center":"right"):58===f.charCodeAt(0)?u.push("left"):u.push("")}if(-1===(o=de(e,t).trim()).indexOf("|"))return!1;if(c=o.replace(/^\||\|$/g,"").split("|"),u.length!==c.length)return!1;if(n)return!0;for(e.tokens.push({type:"table_open",lines:h=[t,0],level:e.level++}),e.tokens.push({type:"thead_open",lines:[t,t+1],level:e.level++}),e.tokens.push({type:"tr_open",lines:[t,t+1],level:e.level++}),a=0;a<c.length;a++)e.tokens.push({type:"th_open",align:u[a],lines:[t,t+1],level:e.level++}),e.tokens.push({type:"inline",content:c[a].trim(),lines:[t,t+1],level:e.level,children:[]}),e.tokens.push({type:"th_close",level:--e.level});for(e.tokens.push({type:"tr_close",level:--e.level}),e.tokens.push({type:"thead_close",level:--e.level}),e.tokens.push({type:"tbody_open",lines:d=[t+2,0],level:e.level++}),l=t+2;l<r&&!(e.tShift[l]<e.blkIndent)&&-1!==(o=de(e,l).trim()).indexOf("|");l++){for(c=o.replace(/^\||\|$/g,"").split("|"),e.tokens.push({type:"tr_open",level:e.level++}),a=0;a<c.length;a++)e.tokens.push({type:"td_open",align:u[a],level:e.level++}),p=c[a].substring(124===c[a].charCodeAt(0)?1:0,124===c[a].charCodeAt(c[a].length-1)?c[a].length-1:c[a].length).trim(),e.tokens.push({type:"inline",content:p,level:e.level,children:[]}),e.tokens.push({type:"td_close",level:--e.level});e.tokens.push({type:"tr_close",level:--e.level})}return e.tokens.push({type:"tbody_close",level:--e.level}),e.tokens.push({type:"table_close",level:--e.level}),h[1]=d[1]=l,e.line=l,!0},["paragraph"]],["deflist",function(e,t,r,n){var i,o,s,a,l,c,p,u,f,h,d,g,m,b;if(n)return!(e.ddIndent<0)&&ge(e,t)>=0;if(p=t+1,e.isEmpty(p)&&++p>r)return!1;if(e.tShift[p]<e.blkIndent)return!1;if((i=ge(e,p))<0)return!1;if(e.level>=e.options.maxNesting)return!1;c=e.tokens.length,e.tokens.push({type:"dl_open",lines:l=[t,0],level:e.level++}),s=t,o=p;e:for(;;){for(b=!0,m=!1,e.tokens.push({type:"dt_open",lines:[s,s],level:e.level++}),e.tokens.push({type:"inline",content:e.getLines(s,s+1,e.blkIndent,!1).trim(),level:e.level+1,lines:[s,s],children:[]}),e.tokens.push({type:"dt_close",level:--e.level});;){if(e.tokens.push({type:"dd_open",lines:a=[p,0],level:e.level++}),g=e.tight,f=e.ddIndent,u=e.blkIndent,d=e.tShift[o],h=e.parentType,e.blkIndent=e.ddIndent=e.tShift[o]+2,e.tShift[o]=i-e.bMarks[o],e.tight=!0,e.parentType="deflist",e.parser.tokenize(e,o,r,!0),e.tight&&!m||(b=!1),m=e.line-o>1&&e.isEmpty(e.line-1),e.tShift[o]=d,e.tight=g,e.parentType=h,e.blkIndent=u,e.ddIndent=f,e.tokens.push({type:"dd_close",level:--e.level}),a[1]=p=e.line,p>=r)break e;if(e.tShift[p]<e.blkIndent)break e;if((i=ge(e,p))<0)break;o=p}if(p>=r)break;if(s=p,e.isEmpty(s))break;if(e.tShift[s]<e.blkIndent)break;if((o=s+1)>=r)break;if(e.isEmpty(o)&&o++,o>=r)break;if(e.tShift[o]<e.blkIndent)break;if((i=ge(e,o))<0)break}return e.tokens.push({type:"dl_close",level:--e.level}),l[1]=p,e.line=p,b&&function(e,t){var r,n,i=e.level+2;for(r=t+2,n=e.tokens.length-2;r<n;r++)e.tokens[r].level===i&&"paragraph_open"===e.tokens[r].type&&(e.tokens[r+2].tight=!0,e.tokens[r].tight=!0,r+=2)}(e,c),!0},["paragraph"]],["paragraph",function(e,t){var r,n,i,o,s,a,l=t+1;if(l<(r=e.lineMax)&&!e.isEmpty(l))for(a=e.parser.ruler.getRules("paragraph");l<r&&!e.isEmpty(l);l++)if(!(e.tShift[l]-e.blkIndent>3)){for(i=!1,o=0,s=a.length;o<s;o++)if(a[o](e,l,r,!0)){i=!0;break}if(i)break}return n=e.getLines(t,l,e.blkIndent,!1).trim(),e.line=l,n.length&&(e.tokens.push({type:"paragraph_open",tight:!1,lines:[t,e.line],level:e.level}),e.tokens.push({type:"inline",content:n,level:e.level+1,lines:[t,e.line],children:[]}),e.tokens.push({type:"paragraph_close",tight:!1,level:e.level})),!0}]];function be(){this.ruler=new z;for(var e=0;e<me.length;e++)this.ruler.push(me[e][0],me[e][1],{alt:(me[e][2]||[]).slice()})}be.prototype.tokenize=function(e,t,r){for(var n,i=this.ruler.getRules(""),o=i.length,s=t,a=!1;s<r&&(e.line=s=e.skipEmptyLines(s),!(s>=r))&&!(e.tShift[s]<e.blkIndent);){for(n=0;n<o&&!i[n](e,s,r,!1);n++);if(e.tight=!a,e.isEmpty(e.line-1)&&(a=!0),(s=e.line)<r&&e.isEmpty(s)){if(a=!0,++s<r&&"list"===e.parentType&&e.isEmpty(s))break;e.line=s}}};var ve=/[\n\t]/g,ke=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,ye=/\u00a0/g;function Ae(e){switch(e){case 10:case 92:case 96:case 42:case 95:case 94:case 91:case 93:case 33:case 38:case 60:case 62:case 123:case 125:case 36:case 37:case 64:case 126:case 43:case 61:case 58:return!0;default:return!1}}be.prototype.parse=function(e,t,r,n){var i,o=0,s=0;if(!e)return[];(e=(e=e.replace(ye," ")).replace(ke,"\n")).indexOf("\t")>=0&&(e=e.replace(ve,(function(t,r){var n;return 10===e.charCodeAt(r)?(o=r+1,s=0,t):(n=" ".slice((r-o-s)%4),s=r-o+1,n)}))),i=new le(e,this,t,r,n),this.tokenize(i,i.line,i.lineMax)};for(var we=[],xe=0;xe<256;xe++)we.push(0);function _e(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122}function Ce(e,t){var r,n,i,o=t,s=!0,a=!0,l=e.posMax,c=e.src.charCodeAt(t);for(r=t>0?e.src.charCodeAt(t-1):-1;o<l&&e.src.charCodeAt(o)===c;)o++;return o>=l&&(s=!1),(i=o-t)>=4?s=a=!1:(32!==(n=o<l?e.src.charCodeAt(o):-1)&&10!==n||(s=!1),32!==r&&10!==r||(a=!1),95===c&&(_e(r)&&(s=!1),_e(n)&&(a=!1))),{can_open:s,can_close:a,delims:i}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach((function(e){we[e.charCodeAt(0)]=1}));var qe=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Se=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Ee=["coap","doi","javascript","aaa","aaas","about","acap","cap","cid","crid","data","dav","dict","dns","file","ftp","geo","go","gopher","h323","http","https","iax","icap","im","imap","info","ipp","iris","iris.beep","iris.xpc","iris.xpcs","iris.lwz","ldap","mailto","mid","msrp","msrps","mtqp","mupdate","news","nfs","ni","nih","nntp","opaquelocktoken","pop","pres","rtsp","service","session","shttp","sieve","sip","sips","sms","snmp","soap.beep","soap.beeps","tag","tel","telnet","tftp","thismessage","tn3270","tip","tv","urn","vemmi","ws","wss","xcon","xcon-userid","xmlrpc.beep","xmlrpc.beeps","xmpp","z39.50r","z39.50s","adiumxtra","afp","afs","aim","apt","attachment","aw","beshare","bitcoin","bolo","callto","chrome","chrome-extension","com-eventbrite-attendee","content","cvs","dlna-playsingle","dlna-playcontainer","dtn","dvb","ed2k","facetime","feed","finger","fish","gg","git","gizmoproject","gtalk","hcp","icon","ipn","irc","irc6","ircs","itms","jar","jms","keyparc","lastfm","ldaps","magnet","maps","market","message","mms","ms-help","msnim","mumble","mvn","notes","oid","palm","paparazzi","platform","proxy","psyc","query","res","resource","rmi","rsync","rtmp","secondlife","sftp","sgn","skype","smb","soldat","spotify","ssh","steam","svn","teamspeak","things","udp","unreal","ut2004","ventrilo","view-source","webcal","wtai","wyciwyg","xfire","xri","ymsgr"],Me=/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/,Le=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function Te(e,t){return e=e.source,t=t||"",function r(n,i){return n?(i=i.source||i,e=e.replace(n,i),r):new RegExp(e,t)}}var Ie=Te(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),Oe=Te(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",Ie)(),Ne=Te(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",Oe)(),je=Te(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",Ne)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/)("processing",/<[?].*?[?]>/)("declaration",/<![A-Z]+\s+[^>]*>/)("cdata",/<!\[CDATA\[[\s\S]*?\]\]>/)();var De=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,Re=/^&([a-z][a-z0-9]{1,31});/i;var Ue=[["text",function(e,t){for(var r=e.pos;r<e.posMax&&!Ae(e.src.charCodeAt(r));)r++;return r!==e.pos&&(t||(e.pending+=e.src.slice(e.pos,r)),e.pos=r,!0)}],["newline",function(e,t){var r,n,i=e.pos;if(10!==e.src.charCodeAt(i))return!1;if(r=e.pending.length-1,n=e.posMax,!t)if(r>=0&&32===e.pending.charCodeAt(r))if(r>=1&&32===e.pending.charCodeAt(r-1)){for(var o=r-2;o>=0;o--)if(32!==e.pending.charCodeAt(o)){e.pending=e.pending.substring(0,o+1);break}e.push({type:"hardbreak",level:e.level})}else e.pending=e.pending.slice(0,-1),e.push({type:"softbreak",level:e.level});else e.push({type:"softbreak",level:e.level});for(i++;i<n&&32===e.src.charCodeAt(i);)i++;return e.pos=i,!0}],["escape",function(e,t){var r,n=e.pos,i=e.posMax;if(92!==e.src.charCodeAt(n))return!1;if(++n<i){if((r=e.src.charCodeAt(n))<256&&0!==we[r])return t||(e.pending+=e.src[n]),e.pos+=2,!0;if(10===r){for(t||e.push({type:"hardbreak",level:e.level}),n++;n<i&&32===e.src.charCodeAt(n);)n++;return e.pos=n,!0}}return t||(e.pending+="\\"),e.pos++,!0}],["backticks",function(e,t){var r,n,i,o,s,a=e.pos;if(96!==e.src.charCodeAt(a))return!1;for(r=a,a++,n=e.posMax;a<n&&96===e.src.charCodeAt(a);)a++;for(i=e.src.slice(r,a),o=s=a;-1!==(o=e.src.indexOf("`",s));){for(s=o+1;s<n&&96===e.src.charCodeAt(s);)s++;if(s-o===i.length)return t||e.push({type:"code",content:e.src.slice(a,o).replace(/[ \n]+/g," ").trim(),block:!1,level:e.level}),e.pos=s,!0}return t||(e.pending+=i),e.pos+=i.length,!0}],["del",function(e,t){var r,n,i,o,s,a=e.posMax,l=e.pos;if(126!==e.src.charCodeAt(l))return!1;if(t)return!1;if(l+4>=a)return!1;if(126!==e.src.charCodeAt(l+1))return!1;if(e.level>=e.options.maxNesting)return!1;if(o=l>0?e.src.charCodeAt(l-1):-1,s=e.src.charCodeAt(l+2),126===o)return!1;if(126===s)return!1;if(32===s||10===s)return!1;for(n=l+2;n<a&&126===e.src.charCodeAt(n);)n++;if(n>l+3)return e.pos+=n-l,t||(e.pending+=e.src.slice(l,n)),!0;for(e.pos=l+2,i=1;e.pos+1<a;){if(126===e.src.charCodeAt(e.pos)&&126===e.src.charCodeAt(e.pos+1)&&(o=e.src.charCodeAt(e.pos-1),126!==(s=e.pos+2<a?e.src.charCodeAt(e.pos+2):-1)&&126!==o&&(32!==o&&10!==o?i--:32!==s&&10!==s&&i++,i<=0))){r=!0;break}e.parser.skipToken(e)}return r?(e.posMax=e.pos,e.pos=l+2,t||(e.push({type:"del_open",level:e.level++}),e.parser.tokenize(e),e.push({type:"del_close",level:--e.level})),e.pos=e.posMax+2,e.posMax=a,!0):(e.pos=l,!1)}],["ins",function(e,t){var r,n,i,o,s,a=e.posMax,l=e.pos;if(43!==e.src.charCodeAt(l))return!1;if(t)return!1;if(l+4>=a)return!1;if(43!==e.src.charCodeAt(l+1))return!1;if(e.level>=e.options.maxNesting)return!1;if(o=l>0?e.src.charCodeAt(l-1):-1,s=e.src.charCodeAt(l+2),43===o)return!1;if(43===s)return!1;if(32===s||10===s)return!1;for(n=l+2;n<a&&43===e.src.charCodeAt(n);)n++;if(n!==l+2)return e.pos+=n-l,t||(e.pending+=e.src.slice(l,n)),!0;for(e.pos=l+2,i=1;e.pos+1<a;){if(43===e.src.charCodeAt(e.pos)&&43===e.src.charCodeAt(e.pos+1)&&(o=e.src.charCodeAt(e.pos-1),43!==(s=e.pos+2<a?e.src.charCodeAt(e.pos+2):-1)&&43!==o&&(32!==o&&10!==o?i--:32!==s&&10!==s&&i++,i<=0))){r=!0;break}e.parser.skipToken(e)}return r?(e.posMax=e.pos,e.pos=l+2,t||(e.push({type:"ins_open",level:e.level++}),e.parser.tokenize(e),e.push({type:"ins_close",level:--e.level})),e.pos=e.posMax+2,e.posMax=a,!0):(e.pos=l,!1)}],["mark",function(e,t){var r,n,i,o,s,a=e.posMax,l=e.pos;if(61!==e.src.charCodeAt(l))return!1;if(t)return!1;if(l+4>=a)return!1;if(61!==e.src.charCodeAt(l+1))return!1;if(e.level>=e.options.maxNesting)return!1;if(o=l>0?e.src.charCodeAt(l-1):-1,s=e.src.charCodeAt(l+2),61===o)return!1;if(61===s)return!1;if(32===s||10===s)return!1;for(n=l+2;n<a&&61===e.src.charCodeAt(n);)n++;if(n!==l+2)return e.pos+=n-l,t||(e.pending+=e.src.slice(l,n)),!0;for(e.pos=l+2,i=1;e.pos+1<a;){if(61===e.src.charCodeAt(e.pos)&&61===e.src.charCodeAt(e.pos+1)&&(o=e.src.charCodeAt(e.pos-1),61!==(s=e.pos+2<a?e.src.charCodeAt(e.pos+2):-1)&&61!==o&&(32!==o&&10!==o?i--:32!==s&&10!==s&&i++,i<=0))){r=!0;break}e.parser.skipToken(e)}return r?(e.posMax=e.pos,e.pos=l+2,t||(e.push({type:"mark_open",level:e.level++}),e.parser.tokenize(e),e.push({type:"mark_close",level:--e.level})),e.pos=e.posMax+2,e.posMax=a,!0):(e.pos=l,!1)}],["emphasis",function(e,t){var r,n,i,o,s,a,l,c=e.posMax,p=e.pos,u=e.src.charCodeAt(p);if(95!==u&&42!==u)return!1;if(t)return!1;if(r=(l=Ce(e,p)).delims,!l.can_open)return e.pos+=r,t||(e.pending+=e.src.slice(p,e.pos)),!0;if(e.level>=e.options.maxNesting)return!1;for(e.pos=p+r,a=[r];e.pos<c;)if(e.src.charCodeAt(e.pos)!==u)e.parser.skipToken(e);else{if(n=(l=Ce(e,e.pos)).delims,l.can_close){for(o=a.pop(),s=n;o!==s;){if(s<o){a.push(o-s);break}if(s-=o,0===a.length)break;e.pos+=o,o=a.pop()}if(0===a.length){r=o,i=!0;break}e.pos+=n;continue}l.can_open&&a.push(n),e.pos+=n}return i?(e.posMax=e.pos,e.pos=p+r,t||(2!==r&&3!==r||e.push({type:"strong_open",level:e.level++}),1!==r&&3!==r||e.push({type:"em_open",level:e.level++}),e.parser.tokenize(e),1!==r&&3!==r||e.push({type:"em_close",level:--e.level}),2!==r&&3!==r||e.push({type:"strong_close",level:--e.level})),e.pos=e.posMax+r,e.posMax=c,!0):(e.pos=p,!1)}],["sub",function(e,t){var r,n,i=e.posMax,o=e.pos;if(126!==e.src.charCodeAt(o))return!1;if(t)return!1;if(o+2>=i)return!1;if(e.level>=e.options.maxNesting)return!1;for(e.pos=o+1;e.pos<i;){if(126===e.src.charCodeAt(e.pos)){r=!0;break}e.parser.skipToken(e)}return r&&o+1!==e.pos?(n=e.src.slice(o+1,e.pos)).match(/(^|[^\\])(\\\\)*\s/)?(e.pos=o,!1):(e.posMax=e.pos,e.pos=o+1,t||e.push({type:"sub",level:e.level,content:n.replace(qe,"$1")}),e.pos=e.posMax+1,e.posMax=i,!0):(e.pos=o,!1)}],["sup",function(e,t){var r,n,i=e.posMax,o=e.pos;if(94!==e.src.charCodeAt(o))return!1;if(t)return!1;if(o+2>=i)return!1;if(e.level>=e.options.maxNesting)return!1;for(e.pos=o+1;e.pos<i;){if(94===e.src.charCodeAt(e.pos)){r=!0;break}e.parser.skipToken(e)}return r&&o+1!==e.pos?(n=e.src.slice(o+1,e.pos)).match(/(^|[^\\])(\\\\)*\s/)?(e.pos=o,!1):(e.posMax=e.pos,e.pos=o+1,t||e.push({type:"sup",level:e.level,content:n.replace(Se,"$1")}),e.pos=e.posMax+1,e.posMax=i,!0):(e.pos=o,!1)}],["links",function(e,t){var r,n,i,o,s,a,l,c,p=!1,u=e.pos,f=e.posMax,h=e.pos,d=e.src.charCodeAt(h);if(33===d&&(p=!0,d=e.src.charCodeAt(++h)),91!==d)return!1;if(e.level>=e.options.maxNesting)return!1;if(r=h+1,(n=B(e,h))<0)return!1;if((a=n+1)<f&&40===e.src.charCodeAt(a)){for(a++;a<f&&(32===(c=e.src.charCodeAt(a))||10===c);a++);if(a>=f)return!1;for(h=a,G(e,a)?(o=e.linkContent,a=e.pos):o="",h=a;a<f&&(32===(c=e.src.charCodeAt(a))||10===c);a++);if(a<f&&h!==a&&H(e,a))for(s=e.linkContent,a=e.pos;a<f&&(32===(c=e.src.charCodeAt(a))||10===c);a++);else s="";if(a>=f||41!==e.src.charCodeAt(a))return e.pos=u,!1;a++}else{if(e.linkLevel>0)return!1;for(;a<f&&(32===(c=e.src.charCodeAt(a))||10===c);a++);if(a<f&&91===e.src.charCodeAt(a)&&(h=a+1,(a=B(e,a))>=0?i=e.src.slice(h,a++):a=h-1),i||(void 0===i&&(a=n+1),i=e.src.slice(r,n)),!(l=e.env.references[Z(i)]))return e.pos=u,!1;o=l.href,s=l.title}return t||(e.pos=r,e.posMax=n,p?e.push({type:"image",src:o,title:s,alt:e.src.substr(r,n-r),level:e.level}):(e.push({type:"link_open",href:o,title:s,level:e.level++}),e.linkLevel++,e.parser.tokenize(e),e.linkLevel--,e.push({type:"link_close",level:--e.level}))),e.pos=a,e.posMax=f,!0}],["footnote_inline",function(e,t){var r,n,i,o,s=e.posMax,a=e.pos;return!(a+2>=s)&&(94===e.src.charCodeAt(a)&&(91===e.src.charCodeAt(a+1)&&(!(e.level>=e.options.maxNesting)&&(r=a+2,!((n=B(e,a+1))<0)&&(t||(e.env.footnotes||(e.env.footnotes={}),e.env.footnotes.list||(e.env.footnotes.list=[]),i=e.env.footnotes.list.length,e.pos=r,e.posMax=n,e.push({type:"footnote_ref",id:i,level:e.level}),e.linkLevel++,o=e.tokens.length,e.parser.tokenize(e),e.env.footnotes.list[i]={tokens:e.tokens.splice(o)},e.linkLevel--),e.pos=n+1,e.posMax=s,!0)))))}],["footnote_ref",function(e,t){var r,n,i,o,s=e.posMax,a=e.pos;if(a+3>s)return!1;if(!e.env.footnotes||!e.env.footnotes.refs)return!1;if(91!==e.src.charCodeAt(a))return!1;if(94!==e.src.charCodeAt(a+1))return!1;if(e.level>=e.options.maxNesting)return!1;for(n=a+2;n<s;n++){if(32===e.src.charCodeAt(n))return!1;if(10===e.src.charCodeAt(n))return!1;if(93===e.src.charCodeAt(n))break}return n!==a+2&&(!(n>=s)&&(n++,r=e.src.slice(a+2,n-1),void 0!==e.env.footnotes.refs[":"+r]&&(t||(e.env.footnotes.list||(e.env.footnotes.list=[]),e.env.footnotes.refs[":"+r]<0?(i=e.env.footnotes.list.length,e.env.footnotes.list[i]={label:r,count:0},e.env.footnotes.refs[":"+r]=i):i=e.env.footnotes.refs[":"+r],o=e.env.footnotes.list[i].count,e.env.footnotes.list[i].count++,e.push({type:"footnote_ref",id:i,subId:o,level:e.level})),e.pos=n,e.posMax=s,!0)))}],["autolink",function(e,t){var r,n,i,o,s,a=e.pos;return 60===e.src.charCodeAt(a)&&(!((r=e.src.slice(a)).indexOf(">")<0)&&((n=r.match(Le))?!(Ee.indexOf(n[1].toLowerCase())<0)&&(s=$(o=n[0].slice(1,-1)),!!e.parser.validateLink(o)&&(t||(e.push({type:"link_open",href:s,level:e.level}),e.push({type:"text",content:o,level:e.level+1}),e.push({type:"link_close",level:e.level})),e.pos+=n[0].length,!0)):!!(i=r.match(Me))&&(s=$("mailto:"+(o=i[0].slice(1,-1))),!!e.parser.validateLink(s)&&(t||(e.push({type:"link_open",href:s,level:e.level}),e.push({type:"text",content:o,level:e.level+1}),e.push({type:"link_close",level:e.level})),e.pos+=i[0].length,!0))))}],["htmltag",function(e,t){var r,n,i,o=e.pos;return!!e.options.html&&(i=e.posMax,!(60!==e.src.charCodeAt(o)||o+2>=i)&&(!(33!==(r=e.src.charCodeAt(o+1))&&63!==r&&47!==r&&!function(e){var t=32|e;return t>=97&&t<=122}(r))&&(!!(n=e.src.slice(o).match(je))&&(t||e.push({type:"htmltag",content:e.src.slice(o,o+n[0].length),level:e.level}),e.pos+=n[0].length,!0))))}],["entity",function(e,t){var r,n,i=e.pos,o=e.posMax;if(38!==e.src.charCodeAt(i))return!1;if(i+1<o)if(35===e.src.charCodeAt(i+1)){if(n=e.src.slice(i).match(De))return t||(r="x"===n[1][0].toLowerCase()?parseInt(n[1].slice(1),16):parseInt(n[1],10),e.pending+=C(r)?q(r):q(65533)),e.pos+=n[0].length,!0}else if(n=e.src.slice(i).match(Re)){var s=y(n[1]);if(n[1]!==s)return t||(e.pending+=s),e.pos+=n[0].length,!0}return t||(e.pending+="&"),e.pos++,!0}]];function Fe(){this.ruler=new z;for(var e=0;e<Ue.length;e++)this.ruler.push(Ue[e][0],Ue[e][1]);this.validateLink=ze}function ze(e){var t=e.trim().toLowerCase();return-1===(t=L(t)).indexOf(":")||-1===["vbscript","javascript","file","data"].indexOf(t.split(":")[0])}Fe.prototype.skipToken=function(e){var t,r,n=this.ruler.getRules(""),i=n.length,o=e.pos;if((r=e.cacheGet(o))>0)e.pos=r;else{for(t=0;t<i;t++)if(n[t](e,!0))return void e.cacheSet(o,e.pos);e.pos++,e.cacheSet(o,e.pos)}},Fe.prototype.tokenize=function(e){for(var t,r,n=this.ruler.getRules(""),i=n.length,o=e.posMax;e.pos<o;){for(r=0;r<i&&!(t=n[r](e,!1));r++);if(t){if(e.pos>=o)break}else e.pending+=e.src[e.pos++]}e.pending&&e.pushPending()},Fe.prototype.parse=function(e,t,r,n){var i=new P(e,this,t,r,n);this.tokenize(i)};var Pe={default:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["block","inline","references","replacements","smartquotes","references","abbr2","footnote_tail"]},block:{rules:["blockquote","code","fences","footnote","heading","hr","htmlblock","lheading","list","paragraph","table"]},inline:{rules:["autolink","backticks","del","emphasis","entity","escape","footnote_ref","htmltag","links","newline","text"]}}},full:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{},block:{},inline:{}}},commonmark:{options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["block","inline","references","abbr2"]},block:{rules:["blockquote","code","fences","heading","hr","htmlblock","lheading","list","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","htmltag","links","newline","text"]}}}};function Be(e,t,r){this.src=t,this.env=r,this.options=e.options,this.tokens=[],this.inlineMode=!1,this.inline=e.inline,this.block=e.block,this.renderer=e.renderer,this.typographer=e.typographer}function Ve(e,t){"string"!=typeof e&&(t=e,e="default"),t&&null!=t.linkify&&console.warn("linkify option is removed. Use linkify plugin instead:\n\nimport Remarkable from 'remarkable';\nimport linkify from 'remarkable/linkify';\nnew Remarkable().use(linkify)\n"),this.inline=new Fe,this.block=new be,this.core=new ae,this.renderer=new F,this.ruler=new z,this.options={},this.configure(Pe[e]),this.set(t||{})}Ve.prototype.set=function(e){w(this.options,e)},Ve.prototype.configure=function(e){var t=this;if(!e)throw new Error("Wrong `remarkable` preset, check name/content");e.options&&t.set(e.options),e.components&&Object.keys(e.components).forEach((function(r){e.components[r].rules&&t[r].ruler.enable(e.components[r].rules,!0)}))},Ve.prototype.use=function(e,t){return e(this,t),this},Ve.prototype.parse=function(e,t){var r=new Be(this,e,t);return this.core.process(r),r.tokens},Ve.prototype.render=function(e,t){return t=t||{},this.renderer.render(this.parse(e,t),this.options,t)},Ve.prototype.parseInline=function(e,t){var r=new Be(this,e,t);return r.inlineMode=!0,this.core.process(r),r.tokens},Ve.prototype.renderInline=function(e,t){return t=t||{},this.renderer.render(this.parseInline(e,t),this.options,t)};var $e=(e,t)=>{const r=(t||{}).delimiter||"$";if(1!==r.length)throw new Error("invalid delimiter");const i=n;e.inline.ruler.push("katex",((e,t)=>{const n=e.pos,i=e.posMax;let o=n;if(e.src.charAt(o)!==r)return!1;for(++o;o<i&&e.src.charAt(o)===r;)++o;const s=e.src.slice(n,o);if(s.length>2)return!1;const a=o;let l=0;for(;o<i;){const n=e.src.charAt(o);if("{"!==n||0!=o&&"\\"==e.src.charAt(o-1)){if("}"!==n||0!=o&&"\\"==e.src.charAt(o-1)){if(n===r&&0===l){const n=o;let l=o+1;for(;l<i&&e.src.charAt(l)===r;)++l;if(l-n===s.length){if(!t){const t=e.src.slice(a,n).replace(/[ \n]+/g," ").trim();e.push({type:"katex",content:t,block:s.length>1,level:e.level})}return e.pos=l,!0}}}else if(l-=1,l<0)return!1}else l+=1;o+=1}return t||(e.pending+=s),e.pos+=s.length,!0}),t),e.block.ruler.push("katex",((e,t,n)=>{let i=!1,o=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];if(o+1>s)return!1;const a=e.src.charAt(o);if(a!==r)return!1;let l=o;o=e.skipChars(o,a);let c=o-l;if(2!==c)return!1;let p=t;for(;(++p,!(p>=n))&&(o=l=e.bMarks[p]+e.tShift[p],s=e.eMarks[p],!(o<s&&e.tShift[p]<e.blkIndent));)if(e.src.charAt(o)===r&&!(e.tShift[p]-e.blkIndent>=4||(o=e.skipChars(o,a),o-l<c||(o=e.skipSpaces(o),o<s)))){i=!0;break}c=e.tShift[t],e.line=p+(i?1:0);const u=e.getLines(t+1,p,c,!0).replace(/[ \n]+/g," ").trim();return e.tokens.push({type:"katex",params:null,content:u,lines:[t,e.line],level:e.level,block:!0}),!0}),t),e.renderer.rules.katex=(e,t)=>{return r=e[t].content,n=e[t].block,i.renderToString(r,{displayMode:n,throwOnError:!1});var r,n},e.renderer.rules.katex.delimiter=r},Ge={versions:{katex:"0.16.0",webfontloader:"1.6.28"},preloadScripts:[{type:"script",data:{src:"https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"}}],scripts:[{type:"iife",data:{fn:e=>{window.WebFontConfig={custom:{families:["KaTeX_AMS","KaTeX_Caligraphic:n4,n7","KaTeX_Fraktur:n4,n7","KaTeX_Main:n4,n7,i4,i7","KaTeX_Math:i4,i7","KaTeX_Script","KaTeX_SansSerif:n4,n7,i4","KaTeX_Size1","KaTeX_Size2","KaTeX_Size3","KaTeX_Size4","KaTeX_Typewriter"]},active:()=>{e().refreshHook.call()}}},getParams:({getMarkmap:e})=>[e]}},{type:"script",data:{src:"https://cdn.jsdelivr.net/npm/[email protected]/webfontloader.js",defer:!0}}],styles:[{type:"stylesheet",data:{href:"https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"}}]};const He="https://cdn.jsdelivr.net/npm/";let Ze;const Ye="katex";var Ke={name:Ye,config:Ge,transform(e){const t=(t,r)=>{const{katex:n}=window;return n?n.renderToString(t,{displayMode:r,throwOnError:!1}):((Ze||(Ze=m(Ge.preloadScripts)),Ze).then((()=>{e.retransform.call()})),t)};let r=()=>{};return e.parser.tap((e=>{e.use($e),e.renderer.rules.katex=(e,n)=>{r();return t(e[n].content,e[n].block)}})),e.beforeParse.tap(((e,t)=>{r=()=>{t.features.katex=!0}})),e.afterParse.tap(((e,t)=>{const{frontmatter:r}=t;null!=r&&r.markmap&&["extraJs","extraCss"].forEach((e=>{r.markmap[e]&&(r.markmap[e]=function(e,t,r){return e.map((e=>("string"==typeof e&&(e.startsWith(`${t}/`)?e=`${He}${t}@${r}${e.slice(t.length)}`:e.startsWith(`${t}@`)&&(e=`${He}${e}`)),e)))}(r.markmap[e],Ye,Ge.versions.katex))}))})),{styles:Ge.styles,scripts:Ge.scripts}}},Je={versions:{prismjs:"1.28.0"},preloadScripts:[{type:"script",data:{src:"https://cdn.jsdelivr.net/npm/[email protected]/components/prism-core.min.js"}},{type:"script",data:{src:"https://cdn.jsdelivr.net/npm/[email protected]/plugins/autoloader/prism-autoloader.min.js"}}],styles:[{type:"stylesheet",data:{href:"https://cdn.jsdelivr.net/npm/[email protected]/themes/prism.css"}}]};let We;function Xe(e,t){(We||(We=m(Je.preloadScripts)),We).then((()=>{window.Prism.plugins.autoloader.loadLanguages([e],(()=>{t.retransform.call()}))}))}const Qe="prism";var et={name:Qe,config:Je,transform(e){let t=()=>{};return e.parser.tap((r=>{r.set({highlight:(r,n)=>{var i;t();const{Prism:o}=window,s=null==o||null==(i=o.languages)?void 0:i[n];return s?o.highlight(r,s,n):(Xe(n,e),"")}})})),e.beforeParse.tap(((e,r)=>{t=()=>{r.features.prism=!0}})),{styles:Je.styles}}};
/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */function tt(e){return null==e}var rt={isNothing:tt,isObject:function(e){return"object"==typeof e&&null!==e},toArray:function(e){return Array.isArray(e)?e:tt(e)?[]:[e]},repeat:function(e,t){var r,n="";for(r=0;r<t;r+=1)n+=e;return n},isNegativeZero:function(e){return 0===e&&Number.NEGATIVE_INFINITY===1/e},extend:function(e,t){var r,n,i,o;if(t)for(r=0,n=(o=Object.keys(t)).length;r<n;r+=1)e[i=o[r]]=t[i];return e}};function nt(e,t){var r="",n=e.reason||"(unknown reason)";return e.mark?(e.mark.name&&(r+='in "'+e.mark.name+'" '),r+="("+(e.mark.line+1)+":"+(e.mark.column+1)+")",!t&&e.mark.snippet&&(r+="\n\n"+e.mark.snippet),n+" "+r):n}function it(e,t){Error.call(this),this.name="YAMLException",this.reason=e,this.mark=t,this.message=nt(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack||""}it.prototype=Object.create(Error.prototype),it.prototype.constructor=it,it.prototype.toString=function(e){return this.name+": "+nt(this,e)};var ot=it;function st(e,t,r,n,i){var o="",s="",a=Math.floor(i/2)-1;return n-t>a&&(t=n-a+(o=" ... ").length),r-n>a&&(r=n+a-(s=" ...").length),{str:o+e.slice(t,r).replace(/\t/g,"→")+s,pos:n-t+o.length}}function at(e,t){return rt.repeat(" ",t-e.length)+e}var lt=function(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),"number"!=typeof t.indent&&(t.indent=1),"number"!=typeof t.linesBefore&&(t.linesBefore=3),"number"!=typeof t.linesAfter&&(t.linesAfter=2);for(var r,n=/\r?\n|\r|\0/g,i=[0],o=[],s=-1;r=n.exec(e.buffer);)o.push(r.index),i.push(r.index+r[0].length),e.position<=r.index&&s<0&&(s=i.length-2);s<0&&(s=i.length-1);var a,l,c="",p=Math.min(e.line+t.linesAfter,o.length).toString().length,u=t.maxLength-(t.indent+p+3);for(a=1;a<=t.linesBefore&&!(s-a<0);a++)l=st(e.buffer,i[s-a],o[s-a],e.position-(i[s]-i[s-a]),u),c=rt.repeat(" ",t.indent)+at((e.line-a+1).toString(),p)+" | "+l.str+"\n"+c;for(l=st(e.buffer,i[s],o[s],e.position,u),c+=rt.repeat(" ",t.indent)+at((e.line+1).toString(),p)+" | "+l.str+"\n",c+=rt.repeat("-",t.indent+p+3+l.pos)+"^\n",a=1;a<=t.linesAfter&&!(s+a>=o.length);a++)l=st(e.buffer,i[s+a],o[s+a],e.position-(i[s]-i[s+a]),u),c+=rt.repeat(" ",t.indent)+at((e.line+a+1).toString(),p)+" | "+l.str+"\n";return c.replace(/\n$/,"")},ct=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],pt=["scalar","sequence","mapping"];var ut=function(e,t){if(t=t||{},Object.keys(t).forEach((function(t){if(-1===ct.indexOf(t))throw new ot('Unknown option "'+t+'" is met in definition of "'+e+'" YAML type.')})),this.options=t,this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.representName=t.representName||null,this.defaultStyle=t.defaultStyle||null,this.multi=t.multi||!1,this.styleAliases=function(e){var t={};return null!==e&&Object.keys(e).forEach((function(r){e[r].forEach((function(e){t[String(e)]=r}))})),t}(t.styleAliases||null),-1===pt.indexOf(this.kind))throw new ot('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')};function ft(e,t){var r=[];return e[t].forEach((function(e){var t=r.length;r.forEach((function(r,n){r.tag===e.tag&&r.kind===e.kind&&r.multi===e.multi&&(t=n)})),r[t]=e})),r}function ht(e){return this.extend(e)}ht.prototype.extend=function(e){var t=[],r=[];if(e instanceof ut)r.push(e);else if(Array.isArray(e))r=r.concat(e);else{if(!e||!Array.isArray(e.implicit)&&!Array.isArray(e.explicit))throw new ot("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");e.implicit&&(t=t.concat(e.implicit)),e.explicit&&(r=r.concat(e.explicit))}t.forEach((function(e){if(!(e instanceof ut))throw new ot("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(e.loadKind&&"scalar"!==e.loadKind)throw new ot("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(e.multi)throw new ot("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")})),r.forEach((function(e){if(!(e instanceof ut))throw new ot("Specified list of YAML types (or a single Type object) contains a non-Type object.")}));var n=Object.create(ht.prototype);return n.implicit=(this.implicit||[]).concat(t),n.explicit=(this.explicit||[]).concat(r),n.compiledImplicit=ft(n,"implicit"),n.compiledExplicit=ft(n,"explicit"),n.compiledTypeMap=function(){var e,t,r={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function n(e){e.multi?(r.multi[e.kind].push(e),r.multi.fallback.push(e)):r[e.kind][e.tag]=r.fallback[e.tag]=e}for(e=0,t=arguments.length;e<t;e+=1)arguments[e].forEach(n);return r}(n.compiledImplicit,n.compiledExplicit),n};var dt=ht,gt=new ut("tag:yaml.org,2002:str",{kind:"scalar",construct:function(e){return null!==e?e:""}}),mt=new ut("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(e){return null!==e?e:[]}}),bt=new ut("tag:yaml.org,2002:map",{kind:"mapping",construct:function(e){return null!==e?e:{}}}),vt=new dt({explicit:[gt,mt,bt]});var kt=new ut("tag:yaml.org,2002:null",{kind:"scalar",resolve:function(e){if(null===e)return!0;var t=e.length;return 1===t&&"~"===e||4===t&&("null"===e||"Null"===e||"NULL"===e)},construct:function(){return null},predicate:function(e){return null===e},represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"});var yt=new ut("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"});function At(e){return 48<=e&&e<=55}function wt(e){return 48<=e&&e<=57}var xt=new ut("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,r,n=e.length,i=0,o=!1;if(!n)return!1;if("-"!==(t=e[i])&&"+"!==t||(t=e[++i]),"0"===t){if(i+1===n)return!0;if("b"===(t=e[++i])){for(i++;i<n;i++)if("_"!==(t=e[i])){if("0"!==t&&"1"!==t)return!1;o=!0}return o&&"_"!==t}if("x"===t){for(i++;i<n;i++)if("_"!==(t=e[i])){if(!(48<=(r=e.charCodeAt(i))&&r<=57||65<=r&&r<=70||97<=r&&r<=102))return!1;o=!0}return o&&"_"!==t}if("o"===t){for(i++;i<n;i++)if("_"!==(t=e[i])){if(!At(e.charCodeAt(i)))return!1;o=!0}return o&&"_"!==t}}if("_"===t)return!1;for(;i<n;i++)if("_"!==(t=e[i])){if(!wt(e.charCodeAt(i)))return!1;o=!0}return!(!o||"_"===t)},construct:function(e){var t,r=e,n=1;if(-1!==r.indexOf("_")&&(r=r.replace(/_/g,"")),"-"!==(t=r[0])&&"+"!==t||("-"===t&&(n=-1),t=(r=r.slice(1))[0]),"0"===r)return 0;if("0"===t){if("b"===r[1])return n*parseInt(r.slice(2),2);if("x"===r[1])return n*parseInt(r.slice(2),16);if("o"===r[1])return n*parseInt(r.slice(2),8)}return n*parseInt(r,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&e%1==0&&!rt.isNegativeZero(e)},represent:{binary:function(e){return e>=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0o"+e.toString(8):"-0o"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),_t=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var Ct=/^[-+]?[0-9]+e/;var qt=new ut("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!_t.test(e)||"_"===e[e.length-1])},construct:function(e){var t,r;return r="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,"+-".indexOf(t[0])>=0&&(t=t.slice(1)),".inf"===t?1===r?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:r*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||rt.isNegativeZero(e))},represent:function(e,t){var r;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(rt.isNegativeZero(e))return"-0.0";return r=e.toString(10),Ct.test(r)?r.replace("e",".e"):r},defaultStyle:"lowercase"}),St=vt.extend({implicit:[kt,yt,xt,qt]}),Et=St,Mt=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),Lt=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");var Tt=new ut("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:function(e){return null!==e&&(null!==Mt.exec(e)||null!==Lt.exec(e))},construct:function(e){var t,r,n,i,o,s,a,l,c=0,p=null;if(null===(t=Mt.exec(e))&&(t=Lt.exec(e)),null===t)throw new Error("Date resolve error");if(r=+t[1],n=+t[2]-1,i=+t[3],!t[4])return new Date(Date.UTC(r,n,i));if(o=+t[4],s=+t[5],a=+t[6],t[7]){for(c=t[7].slice(0,3);c.length<3;)c+="0";c=+c}return t[9]&&(p=6e4*(60*+t[10]+ +(t[11]||0)),"-"===t[9]&&(p=-p)),l=new Date(Date.UTC(r,n,i,o,s,a,c)),p&&l.setTime(l.getTime()-p),l},instanceOf:Date,represent:function(e){return e.toISOString()}});var It=new ut("tag:yaml.org,2002:merge",{kind:"scalar",resolve:function(e){return"<<"===e||null===e}}),Ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";var Nt=new ut("tag:yaml.org,2002:binary",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,r,n=0,i=e.length,o=Ot;for(r=0;r<i;r++)if(!((t=o.indexOf(e.charAt(r)))>64)){if(t<0)return!1;n+=6}return n%8==0},construct:function(e){var t,r,n=e.replace(/[\r\n=]/g,""),i=n.length,o=Ot,s=0,a=[];for(t=0;t<i;t++)t%4==0&&t&&(a.push(s>>16&255),a.push(s>>8&255),a.push(255&s)),s=s<<6|o.indexOf(n.charAt(t));return 0===(r=i%4*6)?(a.push(s>>16&255),a.push(s>>8&255),a.push(255&s)):18===r?(a.push(s>>10&255),a.push(s>>2&255)):12===r&&a.push(s>>4&255),new Uint8Array(a)},predicate:function(e){return"[object Uint8Array]"===Object.prototype.toString.call(e)},represent:function(e){var t,r,n="",i=0,o=e.length,s=Ot;for(t=0;t<o;t++)t%3==0&&t&&(n+=s[i>>18&63],n+=s[i>>12&63],n+=s[i>>6&63],n+=s[63&i]),i=(i<<8)+e[t];return 0===(r=o%3)?(n+=s[i>>18&63],n+=s[i>>12&63],n+=s[i>>6&63],n+=s[63&i]):2===r?(n+=s[i>>10&63],n+=s[i>>4&63],n+=s[i<<2&63],n+=s[64]):1===r&&(n+=s[i>>2&63],n+=s[i<<4&63],n+=s[64],n+=s[64]),n}}),jt=Object.prototype.hasOwnProperty,Dt=Object.prototype.toString;var Rt=new ut("tag:yaml.org,2002:omap",{kind:"sequence",resolve:function(e){if(null===e)return!0;var t,r,n,i,o,s=[],a=e;for(t=0,r=a.length;t<r;t+=1){if(n=a[t],o=!1,"[object Object]"!==Dt.call(n))return!1;for(i in n)if(jt.call(n,i)){if(o)return!1;o=!0}if(!o)return!1;if(-1!==s.indexOf(i))return!1;s.push(i)}return!0},construct:function(e){return null!==e?e:[]}}),Ut=Object.prototype.toString;var Ft=new ut("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:function(e){if(null===e)return!0;var t,r,n,i,o,s=e;for(o=new Array(s.length),t=0,r=s.length;t<r;t+=1){if(n=s[t],"[object Object]"!==Ut.call(n))return!1;if(1!==(i=Object.keys(n)).length)return!1;o[t]=[i[0],n[i[0]]]}return!0},construct:function(e){if(null===e)return[];var t,r,n,i,o,s=e;for(o=new Array(s.length),t=0,r=s.length;t<r;t+=1)n=s[t],i=Object.keys(n),o[t]=[i[0],n[i[0]]];return o}}),zt=Object.prototype.hasOwnProperty;var Pt=new ut("tag:yaml.org,2002:set",{kind:"mapping",resolve:function(e){if(null===e)return!0;var t,r=e;for(t in r)if(zt.call(r,t)&&null!==r[t])return!1;return!0},construct:function(e){return null!==e?e:{}}}),Bt=Et.extend({implicit:[Tt,It],explicit:[Nt,Rt,Ft,Pt]}),Vt=Object.prototype.hasOwnProperty,$t=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,Gt=/[\x85\u2028\u2029]/,Ht=/[,\[\]\{\}]/,Zt=/^(?:!|!!|![a-z\-]+!)$/i,Yt=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function Kt(e){return Object.prototype.toString.call(e)}function Jt(e){return 10===e||13===e}function Wt(e){return 9===e||32===e}function Xt(e){return 9===e||32===e||10===e||13===e}function Qt(e){return 44===e||91===e||93===e||123===e||125===e}function er(e){var t;return 48<=e&&e<=57?e-48:97<=(t=32|e)&&t<=102?t-97+10:-1}function tr(e){return 48===e?"\0":97===e?"":98===e?"\b":116===e||9===e?"\t":110===e?"\n":118===e?"\v":102===e?"\f":114===e?"\r":101===e?"":32===e?" ":34===e?'"':47===e?"/":92===e?"\\":78===e?"
":95===e?" ":76===e?"\u2028":80===e?"\u2029":""}function rr(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10),56320+(e-65536&1023))}for(var nr=new Array(256),ir=new Array(256),or=0;or<256;or++)nr[or]=tr(or)?1:0,ir[or]=tr(or);function sr(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||Bt,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function ar(e,t){var r={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return r.snippet=lt(r),new ot(t,r)}function lr(e,t){throw ar(e,t)}function cr(e,t){e.onWarning&&e.onWarning.call(null,ar(e,t))}var pr={YAML:function(e,t,r){var n,i,o;null!==e.version&&lr(e,"duplication of %YAML directive"),1!==r.length&&lr(e,"YAML directive accepts exactly one argument"),null===(n=/^([0-9]+)\.([0-9]+)$/.exec(r[0]))&&lr(e,"ill-formed argument of the YAML directive"),i=parseInt(n[1],10),o=parseInt(n[2],10),1!==i&&lr(e,"unacceptable YAML version of the document"),e.version=r[0],e.checkLineBreaks=o<2,1!==o&&2!==o&&cr(e,"unsupported YAML version of the document")},TAG:function(e,t,r){var n,i;2!==r.length&&lr(e,"TAG directive accepts exactly two arguments"),n=r[0],i=r[1],Zt.test(n)||lr(e,"ill-formed tag handle (first argument) of the TAG directive"),Vt.call(e.tagMap,n)&&lr(e,'there is a previously declared suffix for "'+n+'" tag handle'),Yt.test(i)||lr(e,"ill-formed tag prefix (second argument) of the TAG directive");try{i=decodeURIComponent(i)}catch(t){lr(e,"tag prefix is malformed: "+i)}e.tagMap[n]=i}};function ur(e,t,r,n){var i,o,s,a;if(t<r){if(a=e.input.slice(t,r),n)for(i=0,o=a.length;i<o;i+=1)9===(s=a.charCodeAt(i))||32<=s&&s<=1114111||lr(e,"expected valid JSON character");else $t.test(a)&&lr(e,"the stream contains non-printable characters");e.result+=a}}function fr(e,t,r,n){var i,o,s,a;for(rt.isObject(r)||lr(e,"cannot merge mappings; the provided source object is unacceptable"),s=0,a=(i=Object.keys(r)).length;s<a;s+=1)o=i[s],Vt.call(t,o)||(t[o]=r[o],n[o]=!0)}function hr(e,t,r,n,i,o,s,a,l){var c,p;if(Array.isArray(i))for(c=0,p=(i=Array.prototype.slice.call(i)).length;c<p;c+=1)Array.isArray(i[c])&&lr(e,"nested arrays are not supported inside keys"),"object"==typeof i&&"[object Object]"===Kt(i[c])&&(i[c]="[object Object]");if("object"==typeof i&&"[object Object]"===Kt(i)&&(i="[object Object]"),i=String(i),null===t&&(t={}),"tag:yaml.org,2002:merge"===n)if(Array.isArray(o))for(c=0,p=o.length;c<p;c+=1)fr(e,t,o[c],r);else fr(e,t,o,r);else e.json||Vt.call(r,i)||!Vt.call(t,i)||(e.line=s||e.line,e.lineStart=a||e.lineStart,e.position=l||e.position,lr(e,"duplicated mapping key")),"__proto__"===i?Object.defineProperty(t,i,{configurable:!0,enumerable:!0,writable:!0,value:o}):t[i]=o,delete r[i];return t}function dr(e){var t;10===(t=e.input.charCodeAt(e.position))?e.position++:13===t?(e.position++,10===e.input.charCodeAt(e.position)&&e.position++):lr(e,"a line break is expected"),e.line+=1,e.lineStart=e.position,e.firstTabInLine=-1}function gr(e,t,r){for(var n=0,i=e.input.charCodeAt(e.position);0!==i;){for(;Wt(i);)9===i&&-1===e.firstTabInLine&&(e.firstTabInLine=e.position),i=e.input.charCodeAt(++e.position);if(t&&35===i)do{i=e.input.charCodeAt(++e.position)}while(10!==i&&13!==i&&0!==i);if(!Jt(i))break;for(dr(e),i=e.input.charCodeAt(e.position),n++,e.lineIndent=0;32===i;)e.lineIndent++,i=e.input.charCodeAt(++e.position)}return-1!==r&&0!==n&&e.lineIndent<r&&cr(e,"deficient indentation"),n}function mr(e){var t,r=e.position;return!(45!==(t=e.input.charCodeAt(r))&&46!==t||t!==e.input.charCodeAt(r+1)||t!==e.input.charCodeAt(r+2)||(r+=3,0!==(t=e.input.charCodeAt(r))&&!Xt(t)))}function br(e,t){1===t?e.result+=" ":t>1&&(e.result+=rt.repeat("\n",t-1))}function vr(e,t){var r,n,i=e.tag,o=e.anchor,s=[],a=!1;if(-1!==e.firstTabInLine)return!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=s),n=e.input.charCodeAt(e.position);0!==n&&(-1!==e.firstTabInLine&&(e.position=e.firstTabInLine,lr(e,"tab characters must not be used in indentation")),45===n)&&Xt(e.input.charCodeAt(e.position+1));)if(a=!0,e.position++,gr(e,!0,-1)&&e.lineIndent<=t)s.push(null),n=e.input.charCodeAt(e.position);else if(r=e.line,Ar(e,t,3,!1,!0),s.push(e.result),gr(e,!0,-1),n=e.input.charCodeAt(e.position),(e.line===r||e.lineIndent>t)&&0!==n)lr(e,"bad indentation of a sequence entry");else if(e.lineIndent<t)break;return!!a&&(e.tag=i,e.anchor=o,e.kind="sequence",e.result=s,!0)}function kr(e){var t,r,n,i,o=!1,s=!1;if(33!==(i=e.input.charCodeAt(e.position)))return!1;if(null!==e.tag&&lr(e,"duplication of a tag property"),60===(i=e.input.charCodeAt(++e.position))?(o=!0,i=e.input.charCodeAt(++e.position)):33===i?(s=!0,r="!!",i=e.input.charCodeAt(++e.position)):r="!",t=e.position,o){do{i=e.input.charCodeAt(++e.position)}while(0!==i&&62!==i);e.position<e.length?(n=e.input.slice(t,e.position),i=e.input.charCodeAt(++e.position)):lr(e,"unexpected end of the stream within a verbatim tag")}else{for(;0!==i&&!Xt(i);)33===i&&(s?lr(e,"tag suffix cannot contain exclamation marks"):(r=e.input.slice(t-1,e.position+1),Zt.test(r)||lr(e,"named tag handle cannot contain such characters"),s=!0,t=e.position+1)),i=e.input.charCodeAt(++e.position);n=e.input.slice(t,e.position),Ht.test(n)&&lr(e,"tag suffix cannot contain flow indicator characters")}n&&!Yt.test(n)&&lr(e,"tag name cannot contain such characters: "+n);try{n=decodeURIComponent(n)}catch(t){lr(e,"tag name is malformed: "+n)}return o?e.tag=n:Vt.call(e.tagMap,r)?e.tag=e.tagMap[r]+n:"!"===r?e.tag="!"+n:"!!"===r?e.tag="tag:yaml.org,2002:"+n:lr(e,'undeclared tag handle "'+r+'"'),!0}function yr(e){var t,r;if(38!==(r=e.input.charCodeAt(e.position)))return!1;for(null!==e.anchor&&lr(e,"duplication of an anchor property"),r=e.input.charCodeAt(++e.position),t=e.position;0!==r&&!Xt(r)&&!Qt(r);)r=e.input.charCodeAt(++e.position);return e.position===t&&lr(e,"name of an anchor node must contain at least one character"),e.anchor=e.input.slice(t,e.position),!0}function Ar(e,t,r,n,i){var o,s,a,l,c,p,u,f,h,d=1,g=!1,m=!1;if(null!==e.listener&&e.listener("open",e),e.tag=null,e.anchor=null,e.kind=null,e.result=null,o=s=a=4===r||3===r,n&&gr(e,!0,-1)&&(g=!0,e.lineIndent>t?d=1:e.lineIndent===t?d=0:e.lineIndent<t&&(d=-1)),1===d)for(;kr(e)||yr(e);)gr(e,!0,-1)?(g=!0,a=o,e.lineIndent>t?d=1:e.lineIndent===t?d=0:e.lineIndent<t&&(d=-1)):a=!1;if(a&&(a=g||i),1!==d&&4!==r||(f=1===r||2===r?t:t+1,h=e.position-e.lineStart,1===d?a&&(vr(e,h)||function(e,t,r){var n,i,o,s,a,l,c,p=e.tag,u=e.anchor,f={},h=Object.create(null),d=null,g=null,m=null,b=!1,v=!1;if(-1!==e.firstTabInLine)return!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=f),c=e.input.charCodeAt(e.position);0!==c;){if(b||-1===e.firstTabInLine||(e.position=e.firstTabInLine,lr(e,"tab characters must not be used in indentation")),n=e.input.charCodeAt(e.position+1),o=e.line,63!==c&&58!==c||!Xt(n)){if(s=e.line,a=e.lineStart,l=e.position,!Ar(e,r,2,!1,!0))break;if(e.line===o){for(c=e.input.charCodeAt(e.position);Wt(c);)c=e.input.charCodeAt(++e.position);if(58===c)Xt(c=e.input.charCodeAt(++e.position))||lr(e,"a whitespace character is expected after the key-value separator within a block mapping"),b&&(hr(e,f,h,d,g,null,s,a,l),d=g=m=null),v=!0,b=!1,i=!1,d=e.tag,g=e.result;else{if(!v)return e.tag=p,e.anchor=u,!0;lr(e,"can not read an implicit mapping pair; a colon is missed")}}else{if(!v)return e.tag=p,e.anchor=u,!0;lr(e,"can not read a block mapping entry; a multiline key may not be an implicit key")}}else 63===c?(b&&(hr(e,f,h,d,g,null,s,a,l),d=g=m=null),v=!0,b=!0,i=!0):b?(b=!1,i=!0):lr(e,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),e.position+=1,c=n;if((e.line===o||e.lineIndent>t)&&(b&&(s=e.line,a=e.lineStart,l=e.position),Ar(e,t,4,!0,i)&&(b?g=e.result:m=e.result),b||(hr(e,f,h,d,g,m,s,a,l),d=g=m=null),gr(e,!0,-1),c=e.input.charCodeAt(e.position)),(e.line===o||e.lineIndent>t)&&0!==c)lr(e,"bad indentation of a mapping entry");else if(e.lineIndent<t)break}return b&&hr(e,f,h,d,g,null,s,a,l),v&&(e.tag=p,e.anchor=u,e.kind="mapping",e.result=f),v}(e,h,f))||function(e,t){var r,n,i,o,s,a,l,c,p,u,f,h,d=!0,g=e.tag,m=e.anchor,b=Object.create(null);if(91===(h=e.input.charCodeAt(e.position)))s=93,c=!1,o=[];else{if(123!==h)return!1;s=125,c=!0,o={}}for(null!==e.anchor&&(e.anchorMap[e.anchor]=o),h=e.input.charCodeAt(++e.position);0!==h;){if(gr(e,!0,t),(h=e.input.charCodeAt(e.position))===s)return e.position++,e.tag=g,e.anchor=m,e.kind=c?"mapping":"sequence",e.result=o,!0;d?44===h&&lr(e,"expected the node content, but found ','"):lr(e,"missed comma between flow collection entries"),f=null,a=l=!1,63===h&&Xt(e.input.charCodeAt(e.position+1))&&(a=l=!0,e.position++,gr(e,!0,t)),r=e.line,n=e.lineStart,i=e.position,Ar(e,t,1,!1,!0),u=e.tag,p=e.result,gr(e,!0,t),h=e.input.charCodeAt(e.position),!l&&e.line!==r||58!==h||(a=!0,h=e.input.charCodeAt(++e.position),gr(e,!0,t),Ar(e,t,1,!1,!0),f=e.result),c?hr(e,o,b,u,p,f,r,n,i):a?o.push(hr(e,null,b,u,p,f,r,n,i)):o.push(p),gr(e,!0,t),44===(h=e.input.charCodeAt(e.position))?(d=!0,h=e.input.charCodeAt(++e.position)):d=!1}lr(e,"unexpected end of the stream within a flow collection")}(e,f)?m=!0:(s&&function(e,t){var r,n,i,o,s,a=1,l=!1,c=!1,p=t,u=0,f=!1;if(124===(o=e.input.charCodeAt(e.position)))n=!1;else{if(62!==o)return!1;n=!0}for(e.kind="scalar",e.result="";0!==o;)if(43===(o=e.input.charCodeAt(++e.position))||45===o)1===a?a=43===o?3:2:lr(e,"repeat of a chomping mode identifier");else{if(!((i=48<=(s=o)&&s<=57?s-48:-1)>=0))break;0===i?lr(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):c?lr(e,"repeat of an indentation width identifier"):(p=t+i-1,c=!0)}if(Wt(o)){do{o=e.input.charCodeAt(++e.position)}while(Wt(o));if(35===o)do{o=e.input.charCodeAt(++e.position)}while(!Jt(o)&&0!==o)}for(;0!==o;){for(dr(e),e.lineIndent=0,o=e.input.charCodeAt(e.position);(!c||e.lineIndent<p)&&32===o;)e.lineIndent++,o=e.input.charCodeAt(++e.position);if(!c&&e.lineIndent>p&&(p=e.lineIndent),Jt(o))u++;else{if(e.lineIndent<p){3===a?e.result+=rt.repeat("\n",l?1+u:u):1===a&&l&&(e.result+="\n");break}for(n?Wt(o)?(f=!0,e.result+=rt.repeat("\n",l?1+u:u)):f?(f=!1,e.result+=rt.repeat("\n",u+1)):0===u?l&&(e.result+=" "):e.result+=rt.repeat("\n",u):e.result+=rt.repeat("\n",l?1+u:u),l=!0,c=!0,u=0,r=e.position;!Jt(o)&&0!==o;)o=e.input.charCodeAt(++e.position);ur(e,r,e.position,!1)}}return!0}(e,f)||function(e,t){var r,n,i;if(39!==(r=e.input.charCodeAt(e.position)))return!1;for(e.kind="scalar",e.result="",e.position++,n=i=e.position;0!==(r=e.input.charCodeAt(e.position));)if(39===r){if(ur(e,n,e.position,!0),39!==(r=e.input.charCodeAt(++e.position)))return!0;n=e.position,e.position++,i=e.position}else Jt(r)?(ur(e,n,i,!0),br(e,gr(e,!1,t)),n=i=e.position):e.position===e.lineStart&&mr(e)?lr(e,"unexpected end of the document within a single quoted scalar"):(e.position++,i=e.position);lr(e,"unexpected end of the stream within a single quoted scalar")}(e,f)||function(e,t){var r,n,i,o,s,a,l;if(34!==(a=e.input.charCodeAt(e.position)))return!1;for(e.kind="scalar",e.result="",e.position++,r=n=e.position;0!==(a=e.input.charCodeAt(e.position));){if(34===a)return ur(e,r,e.position,!0),e.position++,!0;if(92===a){if(ur(e,r,e.position,!0),Jt(a=e.input.charCodeAt(++e.position)))gr(e,!1,t);else if(a<256&&nr[a])e.result+=ir[a],e.position++;else if((s=120===(l=a)?2:117===l?4:85===l?8:0)>0){for(i=s,o=0;i>0;i--)(s=er(a=e.input.charCodeAt(++e.position)))>=0?o=(o<<4)+s:lr(e,"expected hexadecimal character");e.result+=rr(o),e.position++}else lr(e,"unknown escape sequence");r=n=e.position}else Jt(a)?(ur(e,r,n,!0),br(e,gr(e,!1,t)),r=n=e.position):e.position===e.lineStart&&mr(e)?lr(e,"unexpected end of the document within a double quoted scalar"):(e.position++,n=e.position)}lr(e,"unexpected end of the stream within a double quoted scalar")}(e,f)?m=!0:!function(e){var t,r,n;if(42!==(n=e.input.charCodeAt(e.position)))return!1;for(n=e.input.charCodeAt(++e.position),t=e.position;0!==n&&!Xt(n)&&!Qt(n);)n=e.input.charCodeAt(++e.position);return e.position===t&&lr(e,"name of an alias node must contain at least one character"),r=e.input.slice(t,e.position),Vt.call(e.anchorMap,r)||lr(e,'unidentified alias "'+r+'"'),e.result=e.anchorMap[r],gr(e,!0,-1),!0}(e)?function(e,t,r){var n,i,o,s,a,l,c,p,u=e.kind,f=e.result;if(Xt(p=e.input.charCodeAt(e.position))||Qt(p)||35===p||38===p||42===p||33===p||124===p||62===p||39===p||34===p||37===p||64===p||96===p)return!1;if((63===p||45===p)&&(Xt(n=e.input.charCodeAt(e.position+1))||r&&Qt(n)))return!1;for(e.kind="scalar",e.result="",i=o=e.position,s=!1;0!==p;){if(58===p){if(Xt(n=e.input.charCodeAt(e.position+1))||r&&Qt(n))break}else if(35===p){if(Xt(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&mr(e)||r&&Qt(p))break;if(Jt(p)){if(a=e.line,l=e.lineStart,c=e.lineIndent,gr(e,!1,-1),e.lineIndent>=t){s=!0,p=e.input.charCodeAt(e.position);continue}e.position=o,e.line=a,e.lineStart=l,e.lineIndent=c;break}}s&&(ur(e,i,o,!1),br(e,e.line-a),i=o=e.position,s=!1),Wt(p)||(o=e.position+1),p=e.input.charCodeAt(++e.position)}return ur(e,i,o,!1),!!e.result||(e.kind=u,e.result=f,!1)}(e,f,1===r)&&(m=!0,null===e.tag&&(e.tag="?")):(m=!0,null===e.tag&&null===e.anchor||lr(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===d&&(m=a&&vr(e,h))),null===e.tag)null!==e.anchor&&(e.anchorMap[e.anchor]=e.result);else if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&lr(e,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+e.kind+'"'),l=0,c=e.implicitTypes.length;l<c;l+=1)if((u=e.implicitTypes[l]).resolve(e.result)){e.result=u.construct(e.result),e.tag=u.tag,null!==e.anchor&&(e.anchorMap[e.anchor]=e.result);break}}else if("!"!==e.tag){if(Vt.call(e.typeMap[e.kind||"fallback"],e.tag))u=e.typeMap[e.kind||"fallback"][e.tag];else for(u=null,l=0,c=(p=e.typeMap.multi[e.kind||"fallback"]).length;l<c;l+=1)if(e.tag.slice(0,p[l].tag.length)===p[l].tag){u=p[l];break}u||lr(e,"unknown tag !<"+e.tag+">"),null!==e.result&&u.kind!==e.kind&&lr(e,"unacceptable node kind for !<"+e.tag+'> tag; it should be "'+u.kind+'", not "'+e.kind+'"'),u.resolve(e.result,e.tag)?(e.result=u.construct(e.result,e.tag),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):lr(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")}return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||m}function wr(e){var t,r,n,i,o=e.position,s=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);0!==(i=e.input.charCodeAt(e.position))&&(gr(e,!0,-1),i=e.input.charCodeAt(e.position),!(e.lineIndent>0||37!==i));){for(s=!0,i=e.input.charCodeAt(++e.position),t=e.position;0!==i&&!Xt(i);)i=e.input.charCodeAt(++e.position);for(n=[],(r=e.input.slice(t,e.position)).length<1&&lr(e,"directive name must not be less than one character in length");0!==i;){for(;Wt(i);)i=e.input.charCodeAt(++e.position);if(35===i){do{i=e.input.charCodeAt(++e.position)}while(0!==i&&!Jt(i));break}if(Jt(i))break;for(t=e.position;0!==i&&!Xt(i);)i=e.input.charCodeAt(++e.position);n.push(e.input.slice(t,e.position))}0!==i&&dr(e),Vt.call(pr,r)?pr[r](e,r,n):cr(e,'unknown document directive "'+r+'"')}gr(e,!0,-1),0===e.lineIndent&&45===e.input.charCodeAt(e.position)&&45===e.input.charCodeAt(e.position+1)&&45===e.input.charCodeAt(e.position+2)?(e.position+=3,gr(e,!0,-1)):s&&lr(e,"directives end mark is expected"),Ar(e,e.lineIndent-1,4,!1,!0),gr(e,!0,-1),e.checkLineBreaks&&Gt.test(e.input.slice(o,e.position))&&cr(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&mr(e)?46===e.input.charCodeAt(e.position)&&(e.position+=3,gr(e,!0,-1)):e.position<e.length-1&&lr(e,"end of the stream or a document separator is expected")}function xr(e,t){t=t||{},0!==(e=String(e)).length&&(10!==e.charCodeAt(e.length-1)&&13!==e.charCodeAt(e.length-1)&&(e+="\n"),65279===e.charCodeAt(0)&&(e=e.slice(1)));var r=new sr(e,t),n=e.indexOf("\0");for(-1!==n&&(r.position=n,lr(r,"null byte is not allowed in input")),r.input+="\0";32===r.input.charCodeAt(r.position);)r.lineIndent+=1,r.position+=1;for(;r.position<r.length-1;)wr(r);return r.documents}var _r={loadAll:function(e,t,r){null!==t&&"object"==typeof t&&void 0===r&&(r=t,t=null);var n=xr(e,r);if("function"!=typeof t)return n;for(var i=0,o=n.length;i<o;i+=1)t(n[i])},load:function(e,t){var r=xr(e,t);if(0!==r.length){if(1===r.length)return r[0];throw new ot("expected a single document in the stream, but found more")}}},Cr=Object.prototype.toString,qr=Object.prototype.hasOwnProperty,Sr=65279,Er={0:"\\0",7:"\\a",8:"\\b",9:"\\t",10:"\\n",11:"\\v",12:"\\f",13:"\\r",27:"\\e",34:'\\"',92:"\\\\",133:"\\N",160:"\\_",8232:"\\L",8233:"\\P"},Mr=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],Lr=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Tr(e){var t,r,n;if(t=e.toString(16).toUpperCase(),e<=255)r="x",n=2;else if(e<=65535)r="u",n=4;else{if(!(e<=4294967295))throw new ot("code point within a string may not be greater than 0xFFFFFFFF");r="U",n=8}return"\\"+r+rt.repeat("0",n-t.length)+t}function Ir(e){this.schema=e.schema||Bt,this.indent=Math.max(1,e.indent||2),this.noArrayIndent=e.noArrayIndent||!1,this.skipInvalid=e.skipInvalid||!1,this.flowLevel=rt.isNothing(e.flowLevel)?-1:e.flowLevel,this.styleMap=function(e,t){var r,n,i,o,s,a,l;if(null===t)return{};for(r={},i=0,o=(n=Object.keys(t)).length;i<o;i+=1)s=n[i],a=String(t[s]),"!!"===s.slice(0,2)&&(s="tag:yaml.org,2002:"+s.slice(2)),(l=e.compiledTypeMap.fallback[s])&&qr.call(l.styleAliases,a)&&(a=l.styleAliases[a]),r[s]=a;return r}(this.schema,e.styles||null),this.sortKeys=e.sortKeys||!1,this.lineWidth=e.lineWidth||80,this.noRefs=e.noRefs||!1,this.noCompatMode=e.noCompatMode||!1,this.condenseFlow=e.condenseFlow||!1,this.quotingType='"'===e.quotingType?2:1,this.forceQuotes=e.forceQuotes||!1,this.replacer="function"==typeof e.replacer?e.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function Or(e,t){for(var r,n=rt.repeat(" ",t),i=0,o=-1,s="",a=e.length;i<a;)-1===(o=e.indexOf("\n",i))?(r=e.slice(i),i=a):(r=e.slice(i,o+1),i=o+1),r.length&&"\n"!==r&&(s+=n),s+=r;return s}function Nr(e,t){return"\n"+rt.repeat(" ",e.indent*t)}function jr(e){return 32===e||9===e}function Dr(e){return 32<=e&&e<=126||161<=e&&e<=55295&&8232!==e&&8233!==e||57344<=e&&e<=65533&&e!==Sr||65536<=e&&e<=1114111}function Rr(e){return Dr(e)&&e!==Sr&&13!==e&&10!==e}function Ur(e,t,r){var n=Rr(e),i=n&&!jr(e);return(r?n:n&&44!==e&&91!==e&&93!==e&&123!==e&&125!==e)&&35!==e&&!(58===t&&!i)||Rr(t)&&!jr(t)&&35===e||58===t&&i}function Fr(e,t){var r,n=e.charCodeAt(t);return n>=55296&&n<=56319&&t+1<e.length&&(r=e.charCodeAt(t+1))>=56320&&r<=57343?1024*(n-55296)+r-56320+65536:n}function zr(e){return/^\n* /.test(e)}function Pr(e,t,r,n,i,o,s,a){var l,c,p=0,u=null,f=!1,h=!1,d=-1!==n,g=-1,m=Dr(c=Fr(e,0))&&c!==Sr&&!jr(c)&&45!==c&&63!==c&&58!==c&&44!==c&&91!==c&&93!==c&&123!==c&&125!==c&&35!==c&&38!==c&&42!==c&&33!==c&&124!==c&&61!==c&&62!==c&&39!==c&&34!==c&&37!==c&&64!==c&&96!==c&&function(e){return!jr(e)&&58!==e}(Fr(e,e.length-1));if(t||s)for(l=0;l<e.length;p>=65536?l+=2:l++){if(!Dr(p=Fr(e,l)))return 5;m=m&&Ur(p,u,a),u=p}else{for(l=0;l<e.length;p>=65536?l+=2:l++){if(10===(p=Fr(e,l)))f=!0,d&&(h=h||l-g-1>n&&" "!==e[g+1],g=l);else if(!Dr(p))return 5;m=m&&Ur(p,u,a),u=p}h=h||d&&l-g-1>n&&" "!==e[g+1]}return f||h?r>9&&zr(e)?5:s?2===o?5:2:h?4:3:!m||s||i(e)?2===o?5:2:1}function Br(e,t,r,n,i){e.dump=function(){if(0===t.length)return 2===e.quotingType?'""':"''";if(!e.noCompatMode&&(-1!==Mr.indexOf(t)||Lr.test(t)))return 2===e.quotingType?'"'+t+'"':"'"+t+"'";var o=e.indent*Math.max(1,r),s=-1===e.lineWidth?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-o),a=n||e.flowLevel>-1&&r>=e.flowLevel;switch(Pr(t,a,e.indent,s,(function(t){return function(e,t){var r,n;for(r=0,n=e.implicitTypes.length;r<n;r+=1)if(e.implicitTypes[r].resolve(t))return!0;return!1}(e,t)}),e.quotingType,e.forceQuotes&&!n,i)){case 1:return t;case 2:return"'"+t.replace(/'/g,"''")+"'";case 3:return"|"+Vr(t,e.indent)+$r(Or(t,o));case 4:return">"+Vr(t,e.indent)+$r(Or(function(e,t){var r,n,i=/(\n+)([^\n]*)/g,o=(a=e.indexOf("\n"),a=-1!==a?a:e.length,i.lastIndex=a,Gr(e.slice(0,a),t)),s="\n"===e[0]||" "===e[0];var a;for(;n=i.exec(e);){var l=n[1],c=n[2];r=" "===c[0],o+=l+(s||r||""===c?"":"\n")+Gr(c,t),s=r}return o}(t,s),o));case 5:return'"'+function(e){for(var t,r="",n=0,i=0;i<e.length;n>=65536?i+=2:i++)n=Fr(e,i),!(t=Er[n])&&Dr(n)?(r+=e[i],n>=65536&&(r+=e[i+1])):r+=t||Tr(n);return r}(t)+'"';default:throw new ot("impossible error: invalid scalar style")}}()}function Vr(e,t){var r=zr(e)?String(t):"",n="\n"===e[e.length-1];return r+(n&&("\n"===e[e.length-2]||"\n"===e)?"+":n?"":"-")+"\n"}function $r(e){return"\n"===e[e.length-1]?e.slice(0,-1):e}function Gr(e,t){if(""===e||" "===e[0])return e;for(var r,n,i=/ [^ ]/g,o=0,s=0,a=0,l="";r=i.exec(e);)(a=r.index)-o>t&&(n=s>o?s:a,l+="\n"+e.slice(o,n),o=n+1),s=a;return l+="\n",e.length-o>t&&s>o?l+=e.slice(o,s)+"\n"+e.slice(s+1):l+=e.slice(o),l.slice(1)}function Hr(e,t,r,n){var i,o,s,a="",l=e.tag;for(i=0,o=r.length;i<o;i+=1)s=r[i],e.replacer&&(s=e.replacer.call(r,String(i),s)),(Yr(e,t+1,s,!0,!0,!1,!0)||void 0===s&&Yr(e,t+1,null,!0,!0,!1,!0))&&(n&&""===a||(a+=Nr(e,t)),e.dump&&10===e.dump.charCodeAt(0)?a+="-":a+="- ",a+=e.dump);e.tag=l,e.dump=a||"[]"}function Zr(e,t,r){var n,i,o,s,a,l;for(o=0,s=(i=r?e.explicitTypes:e.implicitTypes).length;o<s;o+=1)if(((a=i[o]).instanceOf||a.predicate)&&(!a.instanceOf||"object"==typeof t&&t instanceof a.instanceOf)&&(!a.predicate||a.predicate(t))){if(r?a.multi&&a.representName?e.tag=a.representName(t):e.tag=a.tag:e.tag="?",a.represent){if(l=e.styleMap[a.tag]||a.defaultStyle,"[object Function]"===Cr.call(a.represent))n=a.represent(t,l);else{if(!qr.call(a.represent,l))throw new ot("!<"+a.tag+'> tag resolver accepts not "'+l+'" style');n=a.represent[l](t,l)}e.dump=n}return!0}return!1}function Yr(e,t,r,n,i,o,s){e.tag=null,e.dump=r,Zr(e,r,!1)||Zr(e,r,!0);var a,l=Cr.call(e.dump),c=n;n&&(n=e.flowLevel<0||e.flowLevel>t);var p,u,f="[object Object]"===l||"[object Array]"===l;if(f&&(u=-1!==(p=e.duplicates.indexOf(r))),(null!==e.tag&&"?"!==e.tag||u||2!==e.indent&&t>0)&&(i=!1),u&&e.usedDuplicates[p])e.dump="*ref_"+p;else{if(f&&u&&!e.usedDuplicates[p]&&(e.usedDuplicates[p]=!0),"[object Object]"===l)n&&0!==Object.keys(e.dump).length?(!function(e,t,r,n){var i,o,s,a,l,c,p="",u=e.tag,f=Object.keys(r);if(!0===e.sortKeys)f.sort();else if("function"==typeof e.sortKeys)f.sort(e.sortKeys);else if(e.sortKeys)throw new ot("sortKeys must be a boolean or a function");for(i=0,o=f.length;i<o;i+=1)c="",n&&""===p||(c+=Nr(e,t)),a=r[s=f[i]],e.replacer&&(a=e.replacer.call(r,s,a)),Yr(e,t+1,s,!0,!0,!0)&&((l=null!==e.tag&&"?"!==e.tag||e.dump&&e.dump.length>1024)&&(e.dump&&10===e.dump.charCodeAt(0)?c+="?":c+="? "),c+=e.dump,l&&(c+=Nr(e,t)),Yr(e,t+1,a,!0,l)&&(e.dump&&10===e.dump.charCodeAt(0)?c+=":":c+=": ",p+=c+=e.dump));e.tag=u,e.dump=p||"{}"}(e,t,e.dump,i),u&&(e.dump="&ref_"+p+e.dump)):(!function(e,t,r){var n,i,o,s,a,l="",c=e.tag,p=Object.keys(r);for(n=0,i=p.length;n<i;n+=1)a="",""!==l&&(a+=", "),e.condenseFlow&&(a+='"'),s=r[o=p[n]],e.replacer&&(s=e.replacer.call(r,o,s)),Yr(e,t,o,!1,!1)&&(e.dump.length>1024&&(a+="? "),a+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),Yr(e,t,s,!1,!1)&&(l+=a+=e.dump));e.tag=c,e.dump="{"+l+"}"}(e,t,e.dump),u&&(e.dump="&ref_"+p+" "+e.dump));else if("[object Array]"===l)n&&0!==e.dump.length?(e.noArrayIndent&&!s&&t>0?Hr(e,t-1,e.dump,i):Hr(e,t,e.dump,i),u&&(e.dump="&ref_"+p+e.dump)):(!function(e,t,r){var n,i,o,s="",a=e.tag;for(n=0,i=r.length;n<i;n+=1)o=r[n],e.replacer&&(o=e.replacer.call(r,String(n),o)),(Yr(e,t,o,!1,!1)||void 0===o&&Yr(e,t,null,!1,!1))&&(""!==s&&(s+=","+(e.condenseFlow?"":" ")),s+=e.dump);e.tag=a,e.dump="["+s+"]"}(e,t,e.dump),u&&(e.dump="&ref_"+p+" "+e.dump));else{if("[object String]"!==l){if("[object Undefined]"===l)return!1;if(e.skipInvalid)return!1;throw new ot("unacceptable kind of an object to dump "+l)}"?"!==e.tag&&Br(e,e.dump,t,o,c)}null!==e.tag&&"?"!==e.tag&&(a=encodeURI("!"===e.tag[0]?e.tag.slice(1):e.tag).replace(/!/g,"%21"),a="!"===e.tag[0]?"!"+a:"tag:yaml.org,2002:"===a.slice(0,18)?"!!"+a.slice(18):"!<"+a+">",e.dump=a+" "+e.dump)}return!0}function Kr(e,t){var r,n,i=[],o=[];for(Jr(e,i,o),r=0,n=o.length;r<n;r+=1)t.duplicates.push(i[o[r]]);t.usedDuplicates=new Array(n)}function Jr(e,t,r){var n,i,o;if(null!==e&&"object"==typeof e)if(-1!==(i=t.indexOf(e)))-1===r.indexOf(i)&&r.push(i);else if(t.push(e),Array.isArray(e))for(i=0,o=e.length;i<o;i+=1)Jr(e[i],t,r);else for(i=0,o=(n=Object.keys(e)).length;i<o;i+=1)Jr(e[n[i]],t,r)}function Wr(e,t){return function(){throw new Error("Function yaml."+e+" is removed in js-yaml 4. Use yaml."+t+" instead, which is now safe by default.")}}var Xr={Type:ut,Schema:dt,FAILSAFE_SCHEMA:vt,JSON_SCHEMA:St,CORE_SCHEMA:Et,DEFAULT_SCHEMA:Bt,load:_r.load,loadAll:_r.loadAll,dump:{dump:function(e,t){var r=new Ir(t=t||{});r.noRefs||Kr(e,r);var n=e;return r.replacer&&(n=r.replacer.call({"":n},"",n)),Yr(r,0,n,!0,!0)?r.dump+"\n":""}}.dump,YAMLException:ot,types:{binary:Nt,float:qt,map:bt,null:kt,pairs:Ft,set:Pt,timestamp:Tt,bool:yt,int:xt,merge:It,omap:Rt,seq:mt,str:gt},safeLoad:Wr("safeLoad","load"),safeLoadAll:Wr("safeLoadAll","loadAll"),safeDump:Wr("safeDump","dump")};const Qr=[{name:"frontmatter",transform:e=>(e.beforeParse.tap(((e,t)=>{const r=e.parse;e.parse=f(r,{before(e){const[r]=e.args;if(!r.startsWith("---\n"))return;const n=r.indexOf("\n---\n");if(n<0)return;const i=r.slice(4,n);let o;try{var s;o=Xr.load(i),null!=(s=o)&&s.markmap&&(o.markmap=function(e){if(!e)return;return["color","extraJs","extraCss"].forEach((t=>{null!=e[t]&&(e[t]=function(e){var t;let r;"string"==typeof e?r=[e]:Array.isArray(e)&&(r=e.filter((e=>e&&"string"==typeof e)));return null!=(t=r)&&t.length?r:void 0}(e[t]))})),["duration","maxWidth","initialExpandLevel"].forEach((t=>{null!=e[t]&&(e[t]=function(e){if(isNaN(+e))return;return+e}(e[t]))})),e}(o.markmap))}catch(e){return}t.frontmatter=o;const a=n+5;e.args[0]=r.slice(a)},after(){e.parse=r}})})),{})},Ke,et];function en(e){if("heading"===e.type)e.children=e.children.filter((e=>"paragraph"!==e.type));else if("list_item"===e.type){var t;e.children=e.children.filter((t=>!["paragraph","fence"].includes(t.type)||(e.content||(e.content=t.content,e.payload=i({},e.payload,t.payload)),!1))),null!=(null==(t=e.payload)?void 0:t.index)&&(e.content=`${e.payload.index}. ${e.content}`)}else if("ordered_list"===e.type){var r,n;let t=null!=(r=null==(n=e.payload)?void 0:n.startIndex)?r:1;e.children.forEach((e=>{"list_item"===e.type&&(e.payload=i({},e.payload,{index:t}),t+=1)}))}0===e.children.length?delete e.children:(e.children.forEach((e=>en(e))),1!==e.children.length||e.children[0].content||(e.children=e.children[0].children))}function tn(e,t=0){var r;e.depth=t,null==(r=e.children)||r.forEach((e=>{tn(e,t+1)}))}e.Transformer=class{constructor(e=Qr){this.assetsMap={},this.plugins=e,this.hooks={parser:new o,beforeParse:new o,afterParse:new o,htmltag:new o,retransform:new o};const t={};for(const{name:r,transform:n}of e)t[r]=n(this.hooks);this.assetsMap=t;const r=new Ve("full",{html:!0,breaks:!0,maxNesting:1/0});r.renderer.rules.htmltag=f(r.renderer.rules.htmltag,{after:e=>{this.hooks.htmltag.call(e)}}),this.md=r,this.hooks.parser.call(r)}buildTree(e){const{md:t}=this,r={type:"root",depth:0,content:"",children:[],payload:{}},n=[r];let i=0;for(const r of e){let e=n[n.length-1];if(r.type.endsWith("_open")){const t=r.type.slice(0,-5),a={};var o;if(r.lines&&(a.lines=r.lines),"heading"===t)for(i=r.hLevel;(null==(s=e)?void 0:s.depth)>=i;){var s;n.pop(),e=n[n.length-1]}else i=Math.max(i,(null==(o=e)?void 0:o.depth)||0)+1,"ordered_list"===t&&(a.startIndex=r.order);const l={type:t,depth:i,payload:a,content:"",children:[]};e.children.push(l),n.push(l)}else{if(!e)continue;if(r.type===`${e.type}_close`)"heading"===e.type?i=e.depth:(n.pop(),i=0);else if("inline"===r.type){const n=this.hooks.htmltag.tap((t=>{const r=t.result.match(/^<!--([\s\S]*?)-->$/),n=null==r?void 0:r[1].trim().split(" ");"fold"===n[0]&&(e.payload.fold=["all","recursively"].includes(n[1])?2:1,t.result="")})),i=t.renderer.render([r],t.options,{});n(),e.content=`${e.content||""}${i}`}else if("fence"===r.type){let n=t.renderer.render([r],t.options,{});const o=n.match(/<code( class="[^"]*")>/);o&&(n=n.replace("<pre>",`<pre${o[1]}>`)),e.children.push({type:r.type,depth:i+1,content:n,children:[]})}}}return r}transform(e){var t;const r={features:{}};this.hooks.beforeParse.call(this.md,r);const n=this.md.parse(e,{});this.hooks.afterParse.call(this.md,r);let o=this.buildTree(n);return en(o),1===(null==(t=o.children)?void 0:t.length)&&(o=o.children[0]),tn(o),i({},r,{root:o})}getAssets(e){const t=[],r=[];null!=e||(e=this.plugins.map((e=>e.name)));for(const n of e.map((e=>this.assetsMap[e])))n&&(n.styles&&t.push(...n.styles),n.scripts&&r.push(...n.scripts));return{styles:t,scripts:r}}getUsedAssets(e){const t=this.plugins.map((e=>e.name)).filter((t=>e[t]));return this.getAssets(t)}},e.builtInPlugins=Qr,e.fillTemplate=function(e,t,r){r=i({baseJs:b},r);const{scripts:n,styles:o}=t,a=[...o?(l=o,l.map((e=>"stylesheet"===e.type?p("link",null,s({rel:"stylesheet"},e.data)):p("style",e.data)))):[]];var l;const c={getMarkmap:()=>window.markmap,getOptions:r.getOptions,jsonOptions:r.jsonOptions,root:e},f=[...u([...r.baseJs,...n||[],{type:"iife",data:{fn:(e,t,r,n)=>{const i=e();window.mm=i.Markmap.create("svg#mindmap",(t||i.deriveOptions)(n),r)},getParams:({getMarkmap:e,getOptions:t,root:r,jsonOptions:n})=>[e,t,r,n]}}],c)];return'<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<meta name="viewport" content="width=device-width, initial-scale=1.0">\n<meta http-equiv="X-UA-Compatible" content="ie=edge">\n<title>Markmap</title>\n<style>\n* {\n margin: 0;\n padding: 0;\n}\n#mindmap {\n display: block;\n width: 100vw;\n height: 100vh;\n}\n</style>\n\x3c!--CSS--\x3e\n</head>\n<body>\n<svg id="mindmap"></svg>\n\x3c!--JS--\x3e\n</body>\n</html>\n'.replace("\x3c!--CSS--\x3e",(()=>a.join(""))).replace("\x3c!--JS--\x3e",(()=>f.join("")))},e.transformerVersions={"markmap-lib":"0.14.4",d3:"6.7.0"}}));
;
/*! markmap-view v0.14.4 | MIT License */
!function(t,e){"use strict";function n(t){if(t&&t.__esModule)return t;var e=Object.create(null);if(t)for(var n in t)e[n]=t[n];return e.default=t,Object.freeze(e)}var r=n(e);
/*! markmap-common v0.14.2 | MIT License */class i{constructor(){this.listeners=[]}tap(t){return this.listeners.push(t),()=>this.revoke(t)}revoke(t){const e=this.listeners.indexOf(t);e>=0&&this.listeners.splice(e,1)}revokeAll(){this.listeners.splice(0)}call(...t){for(const e of this.listeners)e(...t)}}function a(){return a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},a.apply(this,arguments)}const o=Math.random().toString(36).slice(2,8);let s=0;function l(){}function c(t,e,n="children"){const r=(t,i)=>e(t,(()=>{var e;null==(e=t[n])||e.forEach((e=>{r(e,t)}))}),i);r(t)}function h(t){if(Array.from)return Array.from(t);const e=[];for(let n=0;n<t.length;n+=1)e.push(t[n]);return e}function d(t){if("string"==typeof t){const e=t;t=t=>t.tagName===e}const e=t;return function(){let t=h(this.childNodes);return e&&(t=t.filter((t=>e(t)))),t}}function u(t,e,n){const r=document.createElement(t);return e&&Object.entries(e).forEach((([t,e])=>{r[t]=e})),n&&Object.entries(n).forEach((([t,e])=>{r.setAttribute(t,e)})),r}const p=function(t){const e={};return function(...n){const r=`${n[0]}`;let i=e[r];return i||(i={value:t(...n)},e[r]=i),i.value}}((t=>{document.head.append(u("link",{rel:"preload",as:"script",href:t}))}));async function f(t,e){if(!t.loaded&&("script"===t.type&&(t.loaded=new Promise(((e,n)=>{var r;document.head.append(u("script",a({},t.data,{onload:e,onerror:n}))),null!=(r=t.data)&&r.src||e(void 0)})).then((()=>{t.loaded=!0}))),"iife"===t.type)){const{fn:n,getParams:r}=t.data;n(...(null==r?void 0:r(e))||[]),t.loaded=!0}await t.loaded}function m(t){t.loaded||(t.loaded=!0,"style"===t.type?document.head.append(u("style",{textContent:t.data})):"stylesheet"===t.type&&document.head.append(u("link",a({rel:"stylesheet"},t.data))))}function g(){return g=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},g.apply(this,arguments)}function y(t){var e=0,n=t.children,r=n&&n.length;if(r)for(;--r>=0;)e+=n[r].value;else e=1;t.value=e}function v(t,e){var n,r,i,a,o,s=new b(t),l=+t.value&&(s.value=t.value),c=[s];for(null==e&&(e=x);n=c.pop();)if(l&&(n.value=+n.data.value),(i=e(n.data))&&(o=i.length))for(n.children=new Array(o),a=o-1;a>=0;--a)c.push(r=n.children[a]=new b(i[a])),r.parent=n,r.depth=n.depth+1;return s.eachBefore(z)}function x(t){return t.children}function k(t){t.data=t.data.data}function z(t){var e=0;do{t.height=e}while((t=t.parent)&&t.height<++e)}function b(t){this.data=t,this.depth=this.height=0,this.parent=null}b.prototype=v.prototype={constructor:b,count:function(){return this.eachAfter(y)},each:function(t){var e,n,r,i,a=this,o=[a];do{for(e=o.reverse(),o=[];a=e.pop();)if(t(a),n=a.children)for(r=0,i=n.length;r<i;++r)o.push(n[r])}while(o.length);return this},eachAfter:function(t){for(var e,n,r,i=this,a=[i],o=[];i=a.pop();)if(o.push(i),e=i.children)for(n=0,r=e.length;n<r;++n)a.push(e[n]);for(;i=o.pop();)t(i);return this},eachBefore:function(t){for(var e,n,r=this,i=[r];r=i.pop();)if(t(r),e=r.children)for(n=e.length-1;n>=0;--n)i.push(e[n]);return this},sum:function(t){return this.eachAfter((function(e){for(var n=+t(e.data)||0,r=e.children,i=r&&r.length;--i>=0;)n+=r[i].value;e.value=n}))},sort:function(t){return this.eachBefore((function(e){e.children&&e.children.sort(t)}))},path:function(t){for(var e=this,n=function(t,e){if(t===e)return t;var n=t.ancestors(),r=e.ancestors(),i=null;t=n.pop(),e=r.pop();for(;t===e;)i=t,t=n.pop(),e=r.pop();return i}(e,t),r=[e];e!==n;)e=e.parent,r.push(e);for(var i=r.length;t!==n;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,e=[t];t=t.parent;)e.push(t);return e},descendants:function(){var t=[];return this.each((function(e){t.push(e)})),t},leaves:function(){var t=[];return this.eachBefore((function(e){e.children||t.push(e)})),t},links:function(){var t=this,e=[];return t.each((function(n){n!==t&&e.push({source:n.parent,target:n})})),e},copy:function(){return v(this).eachBefore(k)}};var S={name:"d3-flextree",version:"2.1.2",main:"build/d3-flextree.js",module:"index","jsnext:main":"index",author:{name:"Chris Maloney",url:"http://chrismaloney.org"},description:"Flexible tree layout algorithm that allows for variable node sizes.",keywords:["d3","d3-module","layout","tree","hierarchy","d3-hierarchy","plugin","d3-plugin","infovis","visualization","2d"],homepage:"https://github.com/klortho/d3-flextree",license:"WTFPL",repository:{type:"git",url:"https://github.com/klortho/d3-flextree.git"},scripts:{clean:"rm -rf build demo test","build:demo":"rollup -c --environment BUILD:demo","build:dev":"rollup -c --environment BUILD:dev","build:prod":"rollup -c --environment BUILD:prod","build:test":"rollup -c --environment BUILD:test",build:"rollup -c",lint:"eslint index.js src","test:main":"node test/bundle.js","test:browser":"node test/browser-tests.js",test:"npm-run-all test:*",prepare:"npm-run-all clean build lint test"},dependencies:{"d3-hierarchy":"^1.1.5"},devDependencies:{"babel-plugin-external-helpers":"^6.22.0","babel-preset-es2015-rollup":"^3.0.0",d3:"^4.13.0","d3-selection-multi":"^1.0.1",eslint:"^4.19.1",jsdom:"^11.6.2","npm-run-all":"^4.1.2",rollup:"^0.55.3","rollup-plugin-babel":"^2.7.1","rollup-plugin-commonjs":"^8.0.2","rollup-plugin-copy":"^0.2.3","rollup-plugin-json":"^2.3.0","rollup-plugin-node-resolve":"^3.0.2","rollup-plugin-uglify":"^3.0.0","uglify-es":"^3.3.9"}};const{version:w}=S,E=Object.freeze({children:t=>t.children,nodeSize:t=>t.data.size,spacing:0});function j(t){const e=Object.assign({},E,t);function n(t){const n=e[t];return"function"==typeof n?n:()=>n}function r(t){const e=a(function(){const t=i(),e=n("nodeSize"),r=n("spacing");return class extends t{constructor(t){super(t),Object.assign(this,{x:0,y:0,relX:0,prelim:0,shift:0,change:0,lExt:this,lExtRelX:0,lThr:null,rExt:this,rExtRelX:0,rThr:null})}get size(){return e(this.data)}spacing(t){return r(this.data,t.data)}get x(){return this.data.x}set x(t){this.data.x=t}get y(){return this.data.y}set y(t){this.data.y=t}update(){return C(this),X(this),this}}}(),t,(t=>t.children));return e.update(),e.data}function i(){const t=n("nodeSize"),e=n("spacing");return class n extends v.prototype.constructor{constructor(t){super(t)}copy(){const t=a(this.constructor,this,(t=>t.children));return t.each((t=>t.data=t.data.data)),t}get size(){return t(this)}spacing(t){return e(this,t)}get nodes(){return this.descendants()}get xSize(){return this.size[0]}get ySize(){return this.size[1]}get top(){return this.y}get bottom(){return this.y+this.ySize}get left(){return this.x-this.xSize/2}get right(){return this.x+this.xSize/2}get root(){const t=this.ancestors();return t[t.length-1]}get numChildren(){return this.hasChildren?this.children.length:0}get hasChildren(){return!this.noChildren}get noChildren(){return null===this.children}get firstChild(){return this.hasChildren?this.children[0]:null}get lastChild(){return this.hasChildren?this.children[this.numChildren-1]:null}get extents(){return(this.children||[]).reduce(((t,e)=>n.maxExtents(t,e.extents)),this.nodeExtents)}get nodeExtents(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}static maxExtents(t,e){return{top:Math.min(t.top,e.top),bottom:Math.max(t.bottom,e.bottom),left:Math.min(t.left,e.left),right:Math.max(t.right,e.right)}}}}function a(t,e,n){const r=(e,i)=>{const a=new t(e);Object.assign(a,{parent:i,depth:null===i?0:i.depth+1,height:0,length:1});const o=n(e)||[];return a.children=0===o.length?null:o.map((t=>r(t,a))),a.children&&Object.assign(a,a.children.reduce(((t,e)=>({height:Math.max(t.height,e.height+1),length:t.length+e.length})),a)),a};return r(e,null)}return Object.assign(r,{nodeSize(t){return arguments.length?(e.nodeSize=t,r):e.nodeSize},spacing(t){return arguments.length?(e.spacing=t,r):e.spacing},children(t){return arguments.length?(e.children=t,r):e.children},hierarchy(t,n){const r=void 0===n?e.children:n;return a(i(),t,r)},dump(t){const e=n("nodeSize"),r=t=>n=>{const i=t+" ",a=t+" ",{x:o,y:s}=n,l=e(n),c=n.children||[],h=0===c.length?" ":`,${i}children: [${a}${c.map(r(a)).join(a)}${i}],${t}`;return`{ size: [${l.join(", ")}],${i}x: ${o}, y: ${s}${h}},`};return r("\n")(t)}}),r}j.version=w;const C=(t,e=0)=>(t.y=e,(t.children||[]).reduce(((e,n)=>{const[r,i]=e;C(n,t.y+t.ySize);const a=(0===r?n.lExt:n.rExt).bottom;0!==r&&I(t,r,i);return[r+1,D(a,r,i)]}),[0,null]),O(t),T(t),t),X=(t,e,n)=>{void 0===e&&(e=-t.relX-t.prelim,n=0);const r=e+t.relX;return t.relX=r+t.prelim-n,t.prelim=0,t.x=n+t.relX,(t.children||[]).forEach((e=>X(e,r,t.x))),t},O=t=>{(t.children||[]).reduce(((t,e)=>{const[n,r]=t,i=n+e.shift,a=r+i+e.change;return e.relX+=a,[i,a]}),[0,0])},I=(t,e,n)=>{const r=t.children[e-1],i=t.children[e];let a=r,o=r.relX,s=i,l=i.relX,c=!0;for(;a&&s;){a.bottom>n.lowY&&(n=n.next);const r=o+a.prelim-(l+s.prelim)+a.xSize/2+s.xSize/2+a.spacing(s);(r>0||r<0&&c)&&(l+=r,M(i,r),A(t,e,n.index,r)),c=!1;const h=a.bottom,d=s.bottom;h<=d&&(a=R(a),a&&(o+=a.relX)),h>=d&&(s=$(s),s&&(l+=s.relX))}!a&&s?B(t,e,s,l):a&&!s&&N(t,e,a,o)},M=(t,e)=>{t.relX+=e,t.lExtRelX+=e,t.rExtRelX+=e},A=(t,e,n,r)=>{const i=t.children[e],a=e-n;if(a>1){const e=r/a;t.children[n+1].shift+=e,i.shift-=e,i.change-=r-e}},$=t=>t.hasChildren?t.firstChild:t.lThr,R=t=>t.hasChildren?t.lastChild:t.rThr,B=(t,e,n,r)=>{const i=t.firstChild,a=i.lExt,o=t.children[e];a.lThr=n;const s=r-n.relX-i.lExtRelX;a.relX+=s,a.prelim-=s,i.lExt=o.lExt,i.lExtRelX=o.lExtRelX},N=(t,e,n,r)=>{const i=t.children[e],a=i.rExt,o=t.children[e-1];a.rThr=n;const s=r-n.relX-i.rExtRelX;a.relX+=s,a.prelim-=s,i.rExt=o.rExt,i.rExtRelX=o.rExtRelX},T=t=>{if(t.hasChildren){const e=t.firstChild,n=t.lastChild,r=(e.prelim+e.relX-e.xSize/2+n.relX+n.prelim+n.xSize/2)/2;Object.assign(t,{prelim:r,lExt:e.lExt,lExtRelX:e.lExtRelX,rExt:n.rExt,rExtRelX:n.rExtRelX})}},D=(t,e,n)=>{for(;null!==n&&t>=n.lowY;)n=n.next;return{lowY:t,index:e,next:n}};
/*! @gera2ld/jsx-dom v2.1.1 | ISC License */
var H="http://www.w3.org/1999/xlink",L={show:H,actuate:H,href:H};function P(t,e){var n;if("string"==typeof t)n=1;else{if("function"!=typeof t)throw new Error("Invalid VNode type");n=2}return{vtype:n,type:t,props:e}}function F(t){return t.children}var Y={isSvg:!1};function W(t,e){if(1===e.type)null!=e.node&&t.append(e.node);else{if(4!==e.type)throw new Error("Unkown ref type "+JSON.stringify(e));e.children.forEach((function(e){W(t,e)}))}}var _={className:"class",labelFor:"for"};function U(t,e,n,r){if(e=_[e]||e,!0===n)t.setAttribute(e,"");else if(!1===n)t.removeAttribute(e);else{var i=r?L[e]:void 0;void 0!==i?t.setAttributeNS(i,e,n):t.setAttribute(e,n)}}function V(t,e){if(void 0===e&&(e=Y),null==t||"boolean"==typeof t)return{type:1,node:null};if(t instanceof Node)return{type:1,node:t};if(2===(null==(o=t)?void 0:o.vtype)){var n=t,r=n.type,i=n.props;if(r===F){var a=document.createDocumentFragment();if(i.children)W(a,V(i.children,e));return{type:1,node:a}}return V(r(i),e)}var o;if(function(t){return"string"==typeof t||"number"==typeof t}(t))return{type:1,node:document.createTextNode(""+t)};if(function(t){return 1===(null==t?void 0:t.vtype)}(t)){var s,l,c=t,h=c.type,d=c.props;if(e.isSvg||"svg"!==h||(e=Object.assign({},e,{isSvg:!0})),function(t,e,n){for(var r in e)"key"!==r&&"children"!==r&&"ref"!==r&&("dangerouslySetInnerHTML"===r?t.innerHTML=e[r].__html:"innerHTML"===r||"textContent"===r||"innerText"===r?t[r]=e[r]:r.startsWith("on")?t[r.toLowerCase()]=e[r]:U(t,r,e[r],n.isSvg))}(s=e.isSvg?document.createElementNS("http://www.w3.org/2000/svg",h):document.createElement(h),d,e),d.children){var u=e;e.isSvg&&"foreignObject"===h&&(u=Object.assign({},u,{isSvg:!1})),l=V(d.children,u)}null!=l&&W(s,l);var p=d.ref;return"function"==typeof p&&p(s),{type:1,node:s}}if(Array.isArray(t))return{type:4,children:t.map((function(t){return V(t,e)}))};throw new Error("mount: Invalid Vnode!")}function Z(t){for(var e=[],n=0;n<t.length;n+=1){var r=t[n];Array.isArray(r)?e=e.concat(Z(r)):null!=r&&e.push(r)}return e}function G(t){return 1===t.type?t.node:t.children.map(G)}function J(t){return Array.isArray(t)?Z(t.map(J)):G(V(t))}var K=".markmap{font:300 16px/20px sans-serif}.markmap-link{fill:none}.markmap-node>circle{cursor:pointer}.markmap-foreign{display:inline-block}.markmap-foreign a{color:#0097e6}.markmap-foreign a:hover{color:#00a8ff}.markmap-foreign code{background-color:#f0f0f0;border-radius:2px;color:#555;font-size:calc(1em - 2px)}.markmap-foreign :not(pre)>code{padding:.2em .4em}.markmap-foreign del{text-decoration:line-through}.markmap-foreign em{font-style:italic}.markmap-foreign strong{font-weight:bolder}.markmap-foreign mark{background:#ffeaa7}.markmap-foreign pre,.markmap-foreign pre[class*=language-]{margin:0;padding:.2em .4em}",q=".markmap-container{height:0;left:-100px;overflow:hidden;position:absolute;top:-100px;width:0}.markmap-container>.markmap-foreign{display:inline-block}.markmap-container>.markmap-foreign>div:last-child{white-space:nowrap}";function Q(t){const e=t.data;return Math.max(4-2*e.depth,1.5)}function tt(t,e){return t[r.minIndex(t,e)]}function et(t){t.stopPropagation()}const nt=new i,rt=r.scaleOrdinal(r.schemeCategory10),it="undefined"!=typeof navigator&&navigator.userAgent.includes("Macintosh");class at{constructor(t,e){this.revokers=[],["handleZoom","handleClick","handlePan"].forEach((t=>{this[t]=this[t].bind(this)})),this.viewHooks={transformHtml:new i},this.svg=t.datum?t:r.select(t),this.styleNode=this.svg.append("style"),this.zoom=r.zoom().filter((t=>this.options.scrollForPan&&"wheel"===t.type?t.ctrlKey&&!t.button:!(t.ctrlKey&&"wheel"!==t.type||t.button))).on("zoom",this.handleZoom),this.setOptions(e),this.state={id:this.options.id||this.svg.attr("id")||(s+=1,`mm-${o}-${s}`)},this.g=this.svg.append("g"),this.revokers.push(nt.tap((()=>{this.setData()})))}getStyleContent(){const{style:t}=this.options,{id:e}=this.state,n="function"==typeof t?t(e):"";return[this.options.embedGlobalCSS&&K,n].filter(Boolean).join("\n")}updateStyle(){this.svg.attr("class",function(t,...e){const n=(t||"").split(" ").filter(Boolean);return e.forEach((t=>{t&&n.indexOf(t)<0&&n.push(t)})),n.join(" ")}(this.svg.attr("class"),"markmap",this.state.id));const t=this.getStyleContent();this.styleNode.text(t)}handleZoom(t){const{transform:e}=t;this.g.attr("transform",e)}handlePan(t){t.preventDefault();const e=r.zoomTransform(this.svg.node()),n=e.translate(-t.deltaX/e.k,-t.deltaY/e.k);this.svg.call(this.zoom.transform,n)}handleClick(t,e){var n;const{data:r}=e;r.payload=g({},r.payload,{fold:null!=(n=r.payload)&&n.fold?0:1}),this.renderData(e.data)}initializeData(t){let e=0;const{color:n,nodeMinHeight:r,maxWidth:i,initialExpandLevel:a}=this.options,{id:o}=this.state,s=J(P("div",{className:`markmap-container markmap ${o}-g`})),l=J(P("style",{children:[this.getStyleContent(),q].join("\n")}));document.body.append(s,l);const d=i?`max-width: ${i}px`:"";let u=0;c(t,((t,r,i)=>{var o,l,c;t.children=null==(o=t.children)?void 0:o.map((t=>g({},t))),e+=1;const h=J(P("div",{className:"markmap-foreign",style:d,children:P("div",{dangerouslySetInnerHTML:{__html:t.content}})}));s.append(h),t.state=g({},t.state,{id:e,el:h.firstChild}),t.state.path=[null==i||null==(l=i.state)?void 0:l.path,t.state.id].filter(Boolean).join("."),n(t);const p=2===(null==(c=t.payload)?void 0:c.fold);p?u+=1:(u||a>=0&&t.depth>=a)&&(t.payload=g({},t.payload,{fold:1})),r(),p&&(u-=1)}));const p=h(s.childNodes).map((t=>t.firstChild));this.viewHooks.transformHtml.call(this,p),p.forEach((t=>{t.parentNode.append(t.cloneNode(!0))})),c(t,((t,e,n)=>{var i;const a=t.state.el.getBoundingClientRect();t.content=t.state.el.innerHTML,t.state.size=[Math.ceil(a.width)+1,Math.max(Math.ceil(a.height),r)],t.state.key=[null==n||null==(i=n.state)?void 0:i.id,t.state.id].filter(Boolean).join(".")+t.content,e()})),s.remove(),l.remove()}setOptions(t){this.options=g({},at.defaultOptions,t),this.options.zoom?this.svg.call(this.zoom):this.svg.on(".zoom",null),this.svg.on("wheel",this.options.pan?this.handlePan:null)}setData(t,e){t&&(this.state.data=t),e&&this.setOptions(e),this.initializeData(this.state.data),this.updateStyle(),this.renderData()}renderData(t){var e,n;if(!this.state.data)return;const{spacingHorizontal:i,paddingX:a,spacingVertical:o,autoFit:s,color:l}=this.options,h=j().children((t=>{var e;return!(null!=(e=t.payload)&&e.fold)&&t.children})).nodeSize((t=>{const[e,n]=t.data.state.size;return[n,e+(e?2*a:0)+i]})).spacing(((t,e)=>t.parent===e.parent?o:2*o)),u=h.hierarchy(this.state.data);h(u),function(t,e){c(t,((t,n)=>{t.ySizeInner=t.ySize-e,t.y+=e,n()}),"children")}(u,i);const p=u.descendants().reverse(),f=u.links(),m=r.linkHorizontal(),g=r.min(p,(t=>t.x-t.xSize/2)),y=r.max(p,(t=>t.x+t.xSize/2)),v=r.min(p,(t=>t.y)),x=r.max(p,(t=>t.y+t.ySizeInner));Object.assign(this.state,{minX:g,maxX:y,minY:v,maxY:x}),s&&this.fit();const k=t&&p.find((e=>e.data===t))||u,z=null!=(e=k.data.state.x0)?e:k.x,b=null!=(n=k.data.state.y0)?n:k.y,S=this.g.selectAll(d("g")).data(p,(t=>t.data.state.key)),w=S.enter().append("g").attr("data-depth",(t=>t.data.depth)).attr("data-path",(t=>t.data.state.path)).attr("transform",(t=>`translate(${b+k.ySizeInner-t.ySizeInner},${z+k.xSize/2-t.xSize})`)),E=this.transition(S.exit());E.select("line").attr("x1",(t=>t.ySizeInner)).attr("x2",(t=>t.ySizeInner)),E.select("foreignObject").style("opacity",0),E.attr("transform",(t=>`translate(${k.y+k.ySizeInner-t.ySizeInner},${k.x+k.xSize/2-t.xSize})`)).remove();const C=S.merge(w).attr("class",(t=>{var e;return["markmap-node",(null==(e=t.data.payload)?void 0:e.fold)&&"markmap-fold"].filter(Boolean).join(" ")}));this.transition(C).attr("transform",(t=>`translate(${t.y},${t.x-t.xSize/2})`));const X=C.selectAll(d("line")).data((t=>[t]),(t=>t.data.state.key)).join((t=>t.append("line").attr("x1",(t=>t.ySizeInner)).attr("x2",(t=>t.ySizeInner))),(t=>t),(t=>t.remove()));this.transition(X).attr("x1",-1).attr("x2",(t=>t.ySizeInner+2)).attr("y1",(t=>t.xSize)).attr("y2",(t=>t.xSize)).attr("stroke",(t=>l(t.data))).attr("stroke-width",Q);const O=C.selectAll(d("circle")).data((t=>t.data.children?[t]:[]),(t=>t.data.state.key)).join((t=>t.append("circle").attr("stroke-width","1.5").attr("cx",(t=>t.ySizeInner)).attr("cy",(t=>t.xSize)).attr("r",0).on("click",((t,e)=>this.handleClick(t,e)))),(t=>t),(t=>t.remove()));this.transition(O).attr("r",6).attr("cx",(t=>t.ySizeInner)).attr("cy",(t=>t.xSize)).attr("stroke",(t=>l(t.data))).attr("fill",(t=>{var e;return null!=(e=t.data.payload)&&e.fold&&t.data.children?l(t.data):"#fff"}));const I=C.selectAll(d("foreignObject")).data((t=>[t]),(t=>t.data.state.key)).join((t=>{const e=t.append("foreignObject").attr("class","markmap-foreign").attr("x",a).attr("y",0).style("opacity",0).on("mousedown",et).on("dblclick",et);return e.append("xhtml:div").select((function(t){const e=t.data.state.el.cloneNode(!0);return this.replaceWith(e),e})).attr("xmlns","http://www.w3.org/1999/xhtml"),e}),(t=>t),(t=>t.remove())).attr("width",(t=>Math.max(0,t.ySizeInner-2*a))).attr("height",(t=>t.xSize));this.transition(I).style("opacity",1);const M=this.g.selectAll(d("path")).data(f,(t=>t.target.data.state.key)).join((t=>{const e=[b+k.ySizeInner,z+k.xSize/2];return t.insert("path","g").attr("class","markmap-link").attr("data-depth",(t=>t.target.data.depth)).attr("data-path",(t=>t.target.data.state.path)).attr("d",m({source:e,target:e}))}),(t=>t),(t=>{const e=[k.y+k.ySizeInner,k.x+k.xSize/2];return this.transition(t).attr("d",m({source:e,target:e})).remove()}));this.transition(M).attr("stroke",(t=>l(t.target.data))).attr("stroke-width",(t=>Q(t.target))).attr("d",(t=>{const e=[t.source.y+t.source.ySizeInner,t.source.x+t.source.xSize/2],n=[t.target.y,t.target.x+t.target.xSize/2];return m({source:e,target:n})})),p.forEach((t=>{t.data.state.x0=t.x,t.data.state.y0=t.y}))}transition(t){const{duration:e}=this.options;return t.transition().duration(e)}async fit(){const t=this.svg.node(),{width:e,height:n}=t.getBoundingClientRect(),{fitRatio:i}=this.options,{minX:a,maxX:o,minY:s,maxY:c}=this.state,h=c-s,d=o-a,u=Math.min(e/h*i,n/d*i,2),p=r.zoomIdentity.translate((e-h*u)/2-s*u,(n-d*u)/2-a*u).scale(u);return this.transition(this.svg).call(this.zoom.transform,p).end().catch(l)}async ensureView(t,e){let n,i;if(this.g.selectAll(d("g")).each((function(e){e.data===t&&(n=this,i=e)})),!n||!i)return;const a=this.svg.node(),o=a.getBoundingClientRect(),s=r.zoomTransform(a),[c,h]=[i.y,i.y+i.ySizeInner+2].map((t=>t*s.k+s.x)),[u,p]=[i.x-i.xSize/2,i.x+i.xSize/2].map((t=>t*s.k+s.y)),f=g({left:0,right:0,top:0,bottom:0},e),m=[f.left-c,o.width-f.right-h],y=[f.top-u,o.height-f.bottom-p],v=m[0]*m[1]>0?tt(m,Math.abs)/s.k:0,x=y[0]*y[1]>0?tt(y,Math.abs)/s.k:0;if(v||x){const t=s.translate(v,x);return this.transition(this.svg).call(this.zoom.transform,t).end().catch(l)}}async rescale(t){const e=this.svg.node(),{width:n,height:i}=e.getBoundingClientRect(),a=n/2,o=i/2,s=r.zoomTransform(e),c=s.translate((a-s.x)*(1-t)/s.k,(o-s.y)*(1-t)/s.k).scale(t);return this.transition(this.svg).call(this.zoom.transform,c).end().catch(l)}destroy(){this.svg.on(".zoom",null),this.svg.html(null),this.revokers.forEach((t=>{t()}))}static create(t,e,n){const r=new at(t,e);return n&&(r.setData(n),r.fit()),r}}at.defaultOptions={autoFit:!1,color:t=>rt(`${t.state.path}`),duration:500,embedGlobalCSS:!0,fitRatio:.95,maxWidth:0,nodeMinHeight:16,paddingX:8,scrollForPan:it,spacingHorizontal:80,spacingVertical:5,initialExpandLevel:-1,zoom:!0,pan:!0},t.Markmap=at,t.defaultColorFn=rt,t.deriveOptions=function(t){const e={};t||(t={});const{color:n,colorFreezeLevel:i}=t;if(1===(null==n?void 0:n.length)){const t=n[0];e.color=()=>t}else if(null!=n&&n.length){const t=r.scaleOrdinal(n);e.color=e=>t(`${e.state.path}`)}if(i){const t=e.color||at.defaultOptions.color;e.color=e=>(e=g({},e,{state:g({},e.state,{path:e.state.path.split(".").slice(0,i).join(".")})}),t(e))}return["duration","maxWidth","initialExpandLevel"].forEach((n=>{const r=t[n];"number"==typeof r&&(e[n]=r)})),["zoom","pan"].forEach((n=>{const r=t[n];null!=r&&(e[n]=!!r)})),e},t.globalCSS=".markmap{font:300 16px/20px sans-serif}.markmap-link{fill:none}.markmap-node>circle{cursor:pointer}.markmap-foreign{display:inline-block}.markmap-foreign a{color:#0097e6}.markmap-foreign a:hover{color:#00a8ff}.markmap-foreign code{background-color:#f0f0f0;border-radius:2px;color:#555;font-size:calc(1em - 2px)}.markmap-foreign :not(pre)>code{padding:.2em .4em}.markmap-foreign del{text-decoration:line-through}.markmap-foreign em{font-style:italic}.markmap-foreign strong{font-weight:bolder}.markmap-foreign mark{background:#ffeaa7}.markmap-foreign pre,.markmap-foreign pre[class*=language-]{margin:0;padding:.2em .4em}",t.loadCSS=function(t){for(const e of t)m(e)},t.loadJS=async function(t,e){const n=t.filter((t=>{var e;return"script"===t.type&&(null==(e=t.data)?void 0:e.src)}));n.length>1&&n.forEach((t=>p(t.data.src))),e=a({getMarkmap:()=>window.markmap},e);for(const n of t)await f(n,e)},t.refreshHook=nt}(this.markmap=this.markmap||{},d3);
//# sourceMappingURL=/sm/f87409a1fbd6c1eea5d434939e1dbcc04bf2548f738e21bde5347c7e45cff4e0.map
|
2951121599/Bili-Insight
| 4,312
|
chrome-extension/scripts/stopwords.js
|
IGNORE_WORDS = [
"视频",
"关注",
"点赞",
"投币",
"收藏",
"三连",
"转发"
]
STOP_WORDS = new Set(
[
"一",
"一些",
"一何",
"一切",
"一则",
"一方面",
"一旦",
"一来",
"一样",
"一般",
"一转眼",
"万一",
"上",
"上下",
"下",
"不",
"不仅",
"不但",
"不光",
"不单",
"不只",
"不外乎",
"不如",
"不妨",
"不尽",
"不尽然",
"不得",
"不怕",
"不惟",
"不成",
"不拘",
"不料",
"不是",
"不比",
"不然",
"不特",
"不独",
"不管",
"不至于",
"不若",
"不论",
"不过",
"不问",
"与",
"与其",
"与其说",
"与否",
"与此同时",
"且",
"且不说",
"且说",
"两者",
"个",
"个别",
"临",
"为",
"为了",
"为什么",
"为何",
"为止",
"为此",
"为着",
"乃",
"乃至",
"乃至于",
"么",
"之",
"之一",
"之所以",
"之类",
"乌乎",
"乎",
"乘",
"也",
"也好",
"也罢",
"了",
"二来",
"于",
"于是",
"于是乎",
"云云",
"云尔",
"些",
"亦",
"人",
"人们",
"人家",
"什么",
"什么样",
"今",
"介于",
"仍",
"仍旧",
"从",
"从此",
"从而",
"他",
"他人",
"他们",
"以",
"以上",
"以为",
"以便",
"以免",
"以及",
"以故",
"以期",
"以来",
"以至",
"以至于",
"以致",
"们",
"任",
"任何",
"任凭",
"似的",
"但",
"但凡",
"但是",
"何",
"何以",
"何况",
"何处",
"何时",
"余外",
"作为",
"你",
"你们",
"使",
"使得",
"例如",
"依",
"依据",
"依照",
"便于",
"俺",
"俺们",
"倘",
"倘使",
"倘或",
"倘然",
"倘若",
"借",
"假使",
"假如",
"假若",
"傥然",
"像",
"儿",
"先不先",
"光是",
"全体",
"全部",
"兮",
"关于",
"其",
"其一",
"其中",
"其二",
"其他",
"其余",
"其它",
"其次",
"具体地说",
"具体说来",
"兼之",
"内",
"再",
"再其次",
"再则",
"再有",
"再者",
"再者说",
"再说",
"冒",
"冲",
"况且",
"几",
"几时",
"凡",
"凡是",
"凭",
"凭借",
"出于",
"出来",
"分别",
"则",
"则甚",
"别",
"别人",
"别处",
"别是",
"别的",
"别管",
"别说",
"到",
"前后",
"前此",
"前者",
"加之",
"加以",
"即",
"即令",
"即使",
"即便",
"即如",
"即或",
"即若",
"却",
"去",
"又",
"又及",
"及",
"及其",
"及至",
"反之",
"反而",
"反过来",
"反过来说",
"受到",
"另",
"另一方面",
"另外",
"另悉",
"只",
"只当",
"只怕",
"只是",
"只有",
"只消",
"只要",
"只限",
"叫",
"叮咚",
"可",
"可以",
"可是",
"可见",
"各",
"各个",
"各位",
"各种",
"各自",
"同",
"同时",
"后",
"后者",
"向",
"向使",
"向着",
"吓",
"吗",
"否则",
"吧",
"吧哒",
"吱",
"呀",
"呃",
"呕",
"呗",
"呜",
"呜呼",
"呢",
"呵",
"呵呵",
"呸",
"呼哧",
"咋",
"和",
"咚",
"咦",
"咧",
"咱",
"咱们",
"咳",
"哇",
"哈",
"哈哈",
"哉",
"哎",
"哎呀",
"哎哟",
"哗",
"哟",
"哦",
"哩",
"哪",
"哪个",
"哪些",
"哪儿",
"哪天",
"哪年",
"哪怕",
"哪样",
"哪边",
"哪里",
"哼",
"哼唷",
"唉",
"唯有",
"啊",
"啐",
"啥",
"啦",
"啪达",
"啷当",
"喂",
"喏",
"喔唷",
"喽",
"嗡",
"嗡嗡",
"嗬",
"嗯",
"嗳",
"嘎",
"嘎登",
"嘘",
"嘛",
"嘻",
"嘿",
"嘿嘿",
"因",
"因为",
"因了",
"因此",
"因着",
"因而",
"固然",
"在",
"在下",
"在于",
"地",
"基于",
"处在",
"多",
"多么",
"多少",
"大",
"大家",
"她",
"她们",
"好",
"如",
"如上",
"如上所述",
"如下",
"如何",
"如其",
"如同",
"如是",
"如果",
"如此",
"如若",
"始而",
"孰料",
"孰知",
"宁",
"宁可",
"宁愿",
"宁肯",
"它",
"它们",
"对",
"对于",
"对待",
"对方",
"对比",
"将",
"小",
"尔",
"尔后",
"尔尔",
"尚且",
"就",
"就是",
"就是了",
"就是说",
"就算",
"就要",
"尽",
"尽管",
"尽管如此",
"岂但",
"己",
"已",
"已矣",
"巴",
"巴巴",
"并",
"并且",
"并非",
"庶乎",
"庶几",
"开外",
"开始",
"归",
"归齐",
"当",
"当地",
"当然",
"当着",
"彼",
"彼时",
"彼此",
"往",
"待",
"很",
"得",
"得了",
"怎",
"怎么",
"怎么办",
"怎么样",
"怎奈",
"怎样",
"总之",
"总的来看",
"总的来说",
"总的说来",
"总而言之",
"恰恰相反",
"您",
"惟其",
"慢说",
"我",
"我们",
"或",
"或则",
"或是",
"或曰",
"或者",
"截至",
"所",
"所以",
"所在",
"所幸",
"所有",
"才",
"才能",
"打",
"打从",
"把",
"抑或",
"拿",
"按",
"按照",
"换句话说",
"换言之",
"据",
"据此",
"接着",
"故",
"故此",
"故而",
"旁人",
"无",
"无宁",
"无论",
"既",
"既往",
"既是",
"既然",
"时候",
"是",
"是以",
"是的",
"曾",
"替",
"替代",
"最",
"有",
"有些",
"有关",
"有及",
"有时",
"有的",
"望",
"朝",
"朝着",
"本",
"本人",
"本地",
"本着",
"本身",
"来",
"来着",
"来自",
"来说",
"极了",
"果然",
"果真",
"某",
"某个",
"某些",
"某某",
"根据",
"欤",
"正值",
"正如",
"正巧",
"正是",
"此",
"此地",
"此处",
"此外",
"此时",
"此次",
"此间",
"毋宁",
"每",
"每当",
"比",
"比及",
"比如",
"比方",
"没奈何",
"沿",
"沿着",
"漫说",
"焉",
"然则",
"然后",
"然而",
"照",
"照着",
"犹且",
"犹自",
"甚且",
"甚么",
"甚或",
"甚而",
"甚至",
"甚至于",
"用",
"用来",
"由",
"由于",
"由是",
"由此",
"由此可见",
"的",
"的确",
"的话",
"直到",
"相对而言",
"省得",
"看",
"眨眼",
"着",
"着呢",
"矣",
"矣乎",
"矣哉",
"离",
"竟而",
"第",
"等",
"等到",
"等等",
"简言之",
"管",
"类如",
"紧接着",
"纵",
"纵令",
"纵使",
"纵然",
"经",
"经过",
"结果",
"给",
"继之",
"继后",
"继而",
"综上所述",
"罢了",
"者",
"而",
"而且",
"而况",
"而后",
"而外",
"而已",
"而是",
"而言",
"能",
"能否",
"腾",
"自",
"自个儿",
"自从",
"自各儿",
"自后",
"自家",
"自己",
"自打",
"自身",
"至",
"至于",
"至今",
"至若",
"致",
"般的",
"若",
"若夫",
"若是",
"若果 ",
"若非",
"莫不然",
"莫如",
"莫若",
"虽",
"虽则",
"虽然",
"虽说",
"被",
"要",
"要不",
"要不是",
"要不然",
"要么",
"要是",
"譬喻",
"譬如",
"让",
"许多",
"论",
"设使",
"设或",
"设若",
"诚如",
"诚然",
"该",
"说来",
"诸",
"诸位",
"诸如",
"谁",
"谁人",
"谁料",
"谁知",
"贼死",
"赖以",
"赶",
"起",
"起见",
"趁",
"趁着",
"越是",
"距",
"跟",
"较",
"较之",
"边",
"过",
"还",
"还是",
"还有",
"还要",
"这",
"这一来",
"这个",
"这么",
"这么些",
"这么样",
"这么点儿",
"这些",
"这会儿",
"这儿",
"这就是说",
"这时",
"这样",
"这次",
"这般",
"这边",
"这里",
"进而",
"连",
"连同",
"逐步",
"通过",
"遵循",
"遵照",
"那",
"那个",
"那么",
"那么些",
"那么样",
"那些",
"那会儿",
"那儿",
"那时",
"那样",
"那般",
"那边",
"那里",
"都",
"鄙人",
"鉴于",
"针对",
"阿",
"除",
"除了",
"除外",
"除开",
"除此之外",
"除非",
"随",
"随后",
"随时",
"随着",
"难道说",
"非但",
"非徒",
"非特",
"非独",
"靠",
"顺",
"顺着",
"首先"
]
)
|
281677160/openwrt-package
| 5,046
|
luci-app-passwall/luasrc/passwall/util_hysteria2.lua
|
module("luci.passwall.util_hysteria2", package.seeall)
local api = require "luci.passwall.api"
local uci = api.uci
local jsonc = api.jsonc
function gen_config_server(node)
local config = {
listen = ":" .. node.port,
tls = {
cert = node.tls_certificateFile,
key = node.tls_keyFile,
},
obfs = (node.hysteria2_obfs) and {
type = "salamander",
salamander = {
password = node.hysteria2_obfs
}
} or nil,
auth = {
type = "password",
password = node.hysteria2_auth_password
},
bandwidth = (node.hysteria2_up_mbps or node.hysteria2_down_mbps) and {
up = node.hysteria2_up_mbps and node.hysteria2_up_mbps .. " mbps" or nil,
down = node.hysteria2_down_mbps and node.hysteria2_down_mbps .. " mbps" or nil
} or nil,
ignoreClientBandwidth = (node.hysteria2_ignoreClientBandwidth == "1") and true or false,
disableUDP = (node.hysteria2_udp == "0") and true or false,
}
return config
end
function gen_config(var)
local node_id = var["-node"]
if not node_id then
print("-node 不能为空")
return
end
local node = uci:get_all("passwall", node_id)
local local_tcp_redir_port = var["-local_tcp_redir_port"]
local local_udp_redir_port = var["-local_udp_redir_port"]
local local_socks_address = var["-local_socks_address"] or "0.0.0.0"
local local_socks_port = var["-local_socks_port"]
local local_socks_username = var["-local_socks_username"]
local local_socks_password = var["-local_socks_password"]
local local_http_address = var["-local_http_address"] or "0.0.0.0"
local local_http_port = var["-local_http_port"]
local local_http_username = var["-local_http_username"]
local local_http_password = var["-local_http_password"]
local tcp_proxy_way = var["-tcp_proxy_way"]
local server_host = var["-server_host"] or node.address
local server_port = var["-server_port"] or node.port
if api.is_ipv6(server_host) then
server_host = api.get_ipv6_full(server_host)
end
local server = server_host .. ":" .. server_port
if (node.hysteria2_hop) then
server = server .. "," .. string.gsub(node.hysteria2_hop, ":", "-")
end
local config = {
server = server,
transport = {
type = node.protocol or "udp",
udp = {
hopInterval = (function()
local HopIntervalStr = tostring(node.hysteria2_hop_interval or "30s")
local HopInterval = tonumber(HopIntervalStr:match("^%d+"))
if HopInterval and HopInterval >= 5 then
return tostring(HopInterval) .. "s"
end
return "30s"
end)(),
}
},
obfs = (node.hysteria2_obfs) and {
type = "salamander",
salamander = {
password = node.hysteria2_obfs
}
} or nil,
auth = node.hysteria2_auth_password,
tls = {
sni = node.tls_serverName,
insecure = (node.tls_allowInsecure == "1") and true or false,
pinSHA256 = (node.hysteria2_tls_pinSHA256) and node.hysteria2_tls_pinSHA256 or nil,
},
quic = {
initStreamReceiveWindow = (node.hysteria2_recv_window) and tonumber(node.hysteria2_recv_window) or nil,
initConnReceiveWindow = (node.hysteria2_recv_window_conn) and tonumber(node.hysteria2_recv_window_conn) or nil,
maxIdleTimeout = (function()
local timeoutStr = tostring(node.hysteria2_idle_timeout or "")
local timeout = tonumber(timeoutStr:match("^%d+"))
if timeout and timeout >= 4 and timeout <= 120 then
return tostring(timeout) .. "s"
end
return nil
end)(),
disablePathMTUDiscovery = (node.hysteria2_disable_mtu_discovery) and true or false,
},
bandwidth = (node.hysteria2_up_mbps or node.hysteria2_down_mbps) and {
up = node.hysteria2_up_mbps and node.hysteria2_up_mbps .. " mbps" or nil,
down = node.hysteria2_down_mbps and node.hysteria2_down_mbps .. " mbps" or nil
} or nil,
fast_open = (node.fast_open == "1") and true or false,
lazy = (node.hysteria2_lazy_start == "1") and true or false,
socks5 = (local_socks_address and local_socks_port) and {
listen = local_socks_address .. ":" .. local_socks_port,
username = (local_socks_username and local_socks_password) and local_socks_username or nil,
password = (local_socks_username and local_socks_password) and local_socks_password or nil,
disableUDP = false,
} or nil,
http = (local_http_address and local_http_port) and {
listen = local_http_address .. ":" .. local_http_port,
username = (local_http_username and local_http_password) and local_http_username or nil,
password = (local_http_username and local_http_password) and local_http_password or nil,
} or nil,
tcpRedirect = ("redirect" == tcp_proxy_way and local_tcp_redir_port) and {
listen = "0.0.0.0:" .. local_tcp_redir_port
} or nil,
tcpTProxy = ("tproxy" == tcp_proxy_way and local_tcp_redir_port) and {
listen = "0.0.0.0:" .. local_tcp_redir_port
} or nil,
udpTProxy = (local_udp_redir_port) and {
listen = "0.0.0.0:" .. local_udp_redir_port
} or nil
}
return jsonc.stringify(config, 1)
end
_G.gen_config = gen_config
if arg[1] then
local func =_G[arg[1]]
if func then
print(func(api.get_function_args(arg)))
end
end
|
2951121599/Bili-Insight
| 10,751
|
chrome-extension/scripts/biliapi.js
|
const BILIBILI_API_URL = "https://api.bilibili.com"
const NUM_PER_PAGE = 50
/*
* Bilibili http request util
*/
var biliMixin = null;
async function getBiliMixin() {
const OE = [46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45,
35, 27, 43, 5, 49, 33, 9, 42, 19, 29, 28, 14, 39, 12, 38,
41, 13, 37, 48, 7, 16, 24, 55, 40, 61, 26, 17, 0, 1, 60,
51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11, 36,
20, 34, 44, 52];
return fetch("https://api.bilibili.com/x/web-interface/nav")
.then((response) => response.json())
.then((data) => {
let img_val = data.data.wbi_img.img_url.split("/").pop().split(".")[0];
let sub_val = data.data.wbi_img.sub_url.split("/").pop().split(".")[0];
let val = img_val + sub_val;
return OE.reduce((s, v) => s + val[v], "").substring(0, 32);
});
}
async function biliGet(url, params) {
if (biliMixin === null) {
biliMixin = await getBiliMixin();
}
if (url.indexOf("/wbi/") != -1) {
// convert params to url in a sorted order
params["wts"] = Math.floor(Date.now() / 1000);
let keys = Object.keys(params).sort();
let paramsStr = keys.map((key) => `${key}=${params[key]}`).join("&");
let sign = md5(paramsStr + biliMixin);
url = `${url}?${paramsStr}&w_rid=${sign}`;
} else {
let keys = Object.keys(params).sort();
let paramsStr = keys.map((key) => `${key}=${params[key]}`).join("&");
url = `${url}?${paramsStr}`;
}
return fetch(url, { "credentials": "include", "mode": "cors" })
.then((response) => response.json())
.then((data) => {
if (data['code'] == -403) {
biliMixin = null;
}
return data;
});
}
async function getVideo(bvid) {
return await biliGet(`${BILIBILI_API_URL}/x/web-interface/view`, {
bvid: bvid
})
.then((data) => {
let video = data["data"]
if (!video) {
return
}
let subList = data["data"]["subtitle"]??["list"]
if (subList.length) {
video.subtitleUrl = subList[0]["subtitle_url"];
}
return video;
})
}
userInfoCache = new Map();
function updateWordMap(map, sentence, weight) {
// Remove all URLs
sentence = sentence.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '');
for (let word of IGNORE_WORDS) {
sentence = sentence.replaceAll(word, '');
}
let results = Array.from(new Intl.Segmenter('cn', { granularity: 'word' }).segment(sentence));
let wordMap = map.get("word");
for (let result of results) {
if (result.isWordLike) {
let word = result["segment"];
if (word && !STOP_WORDS.has(word)) {
if (wordMap.has(word)) {
wordMap.set(word, wordMap.get(word) + weight);
} else {
wordMap.set(word, weight);
}
}
}
}
}
function updateTypeMap(map, type) {
let typeMap = map.get("type");
if (typeMap.has(type)) {
typeMap.set(type, typeMap.get(type) + 1);
} else {
typeMap.set(type, 1);
}
}
function videoLengthStringToSeconds(s) {
let regex = /([0-9]*):([0-9]*)/;
let match = s.match(regex);
if (match) {
return parseInt(match[1]) * 60 + parseInt(match[2]);
}
return 0;
}
function convertVideoData(map) {
let data = {};
let typeData = Array.from(map.get("type"));
typeData.sort((a, b) => b[1] - a[1]);
data["word"] = Array.from(map.get("word"));
data["type"] = typeData.slice(0, 3);
return data;
}
function buildWordMap(map, video) {
if (video["summary"]) {
updateWordMap(map, video["desc"], 1);
updateWordMap(map, video["summary"], 1);
} else {
updateWordMap(map, video["title"], 1);
updateWordMap(map, video["desc"], 1);
}
updateTypeMap(map, video["tid"]);
}
function updateVideoData(videoId, callback, videoData) {
let map = new Map();
map.set("word", new Map());
map.set("type", new Map());
buildWordMap(map, videoData)
if (biliInsightOptions.enableWordCloud) {
cacheAndUpdate(callback, videoId, "wordcloud", convertVideoData(map));
}
}
const readStream2Map = async (
reader,
status
) => {
let partialLine = "";
var resp = "";
let markmapData = "";
while (true) {
// eslint-disable-next-line no-await-in-loop
const { value, done } = await reader.read();
if (done) break;
const decoder = new TextDecoder("utf-8");
const decodedText = decoder.decode(value, { stream: true });
if (status !== 200) {
const json = JSON.parse(decodedText); // start with "data: "
const content = json.error.message ?? decodedText;
//appendLastMessageContent(content);
questionInfo += content;
resp += content;
return;
}
console.log("decodedText:" + decodedText);
markmapData += decodedText;
}
console.log("resp:" + resp);
return markmapData
};
async function updateMapData(videoId, callback, videoData) {
// let markmapData = "";
// try {
// const result = await fetch("http://127.0.0.1:8000", {
// method: "post",
// // signal: AbortSignal.timeout(8000),
// // 开启后到达设定时间会中断流式输出
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify({
// model: "gpt-3.5-turbo",
// text: videoData.summary
// }),
// });
// const { body, status } = await result;
// if (body) {
// const reader = body.getReader();
// // await readStream(reader, status);
// markmapData = await readStream2Map(reader, status);
// }
// } catch (error) {
// console.error(error);
// } finally {
// console.log("markmapData res:" + markmapData);
// cacheAndUpdate(callback, videoId, "markmap", markmapData);
// }
chrome.runtime.sendMessage( //goes to bg_page.js
JSON.stringify({
type: 'summary',
text: videoData.transcript ? videoData.transcript : videoData.summary,
method: 'markmap',
}),
(data) => {
cacheAndUpdate(callback, videoId, "markmap", {
data: data.summary
})
} //your callback
);
}
function cacheValid(cache) {
for (let key of ["info", "wordcloud"]) {
if (!cache[key]) {
return false;
}
}
return true;
}
function cacheAndUpdate(callback, videoId, api, payload) {
let cache = {};
if (!userInfoCache.has(videoId)) {
userInfoCache.set(videoId, cache);
} else {
cache = userInfoCache.get(videoId);
}
cache[api] = payload;
callback({ "uid": videoId, "api": api, "payload": payload });
}
function updateVideoInfo(videoId, callback) {
this._prevVideoId = null;
if (this._prevVideoId != videoId) {
if (userInfoCache.has(videoId) && cacheValid(userInfoCache.get(videoId))) {
let cache = userInfoCache.get(videoId);
for (let api in cache) {
callback({ "uid": videoId, "api": api, "payload": cache[api] });
}
} else {
getVideo(videoId).then((video) => {
if (!video) {
return
}
let subtitleUrl = video.subtitleUrl
if (subtitleUrl) {
// 标题和描述
// 云图
updateUI(videoId, callback, video, false)
chrome.runtime.sendMessage( //goes to bg_page.js
JSON.stringify({
type: 'subtitleUrl',
url: subtitleUrl,
}),
(data) => {
let rawSubTitles = data["body"]
if (!rawSubTitles) {
return
}
var rawTranscript = []
rawSubTitles.forEach(element => {
rawTranscript.push(element["content"])
});
let longText = rawTranscript.join("\n")
video.transcript = longText
updateUI(videoId, callback, video, true)
} //your callback
);
} else {
// has not subtitle
updateUI(videoId, callback, video, true)
}
})
}
}
}
function updateUI(videoId, callback, video, markMap) {
let videoData = video
if (video.transcript) {
chrome.runtime.sendMessage( //goes to bg_page.js
JSON.stringify({
type: 'summary',
text: video.transcript,
}),
(data) => {
cacheAndUpdate(callback, videoId, "info", {
data: {
"like": videoData["stat"]["like"],
"coin": videoData["stat"]["coin"],
"favorite": videoData["stat"]["favorite"],
"share": videoData["stat"]["share"],
"pubdate": videoData["pubdate"],
"duration": videoData["duration"],
"summary": data.summary
}
})
videoData.summary = data.summary
updateVideoData(videoId, callback, videoData);
} //your callback
);
updateMapData(videoId, callback, videoData)
} else {
videoData.summary = videoData["desc"] ? videoData["desc"] : videoData["title"]
cacheAndUpdate(callback, videoId, "info", {
data: {
"like": videoData["stat"]["like"],
"coin": videoData["stat"]["coin"],
"favorite": videoData["stat"]["favorite"],
"share": videoData["stat"]["share"],
"pubdate": videoData["pubdate"],
"duration": videoData["duration"],
"summary": videoData.summary
}
})
updateVideoData(videoId, callback, videoData);
if (markMap) {
updateMapData(videoId, callback, videoData)
}
}
}
|
2977094657/ZsxqCrawler
| 12,959
|
frontend/src/components/CrawlSettingsDialog.tsx
|
'use client';
import React, { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
interface CrawlSettingsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
crawlInterval: number;
longSleepInterval: number;
pagesPerBatch: number;
onSettingsChange: (settings: {
crawlInterval: number;
longSleepInterval: number;
pagesPerBatch: number;
crawlIntervalMin?: number;
crawlIntervalMax?: number;
longSleepIntervalMin?: number;
longSleepIntervalMax?: number;
}) => void;
}
export default function CrawlSettingsDialog({
open,
onOpenChange,
crawlInterval,
longSleepInterval,
pagesPerBatch,
onSettingsChange,
}: CrawlSettingsDialogProps) {
const [localCrawlInterval, setLocalCrawlInterval] = useState(crawlInterval);
const [localLongSleepInterval, setLocalLongSleepInterval] = useState(longSleepInterval);
const [localPagesPerBatch, setLocalPagesPerBatch] = useState(pagesPerBatch);
// 新增范围设置状态
const [crawlIntervalMin, setCrawlIntervalMin] = useState(2);
const [crawlIntervalMax, setCrawlIntervalMax] = useState(5);
const [longSleepIntervalMin, setLongSleepIntervalMin] = useState(180);
const [longSleepIntervalMax, setLongSleepIntervalMax] = useState(300);
const [useRandomInterval, setUseRandomInterval] = useState(true);
const [selectedPreset, setSelectedPreset] = useState<'fast' | 'standard' | 'safe' | null>('standard');
// 当对话框打开时,同步当前设置值
useEffect(() => {
if (open) {
setLocalCrawlInterval(crawlInterval);
setLocalLongSleepInterval(longSleepInterval);
setLocalPagesPerBatch(pagesPerBatch);
// 如果是第一次打开,默认设置为标准配置
if (crawlInterval === 3.5 && longSleepInterval === 240 && pagesPerBatch === 15) {
setPreset('standard');
}
}
}, [open, crawlInterval, longSleepInterval, pagesPerBatch]);
const handleSave = () => {
// 确保所有值都有默认值
const finalCrawlIntervalMin = crawlIntervalMin || 2;
const finalCrawlIntervalMax = crawlIntervalMax || 5;
const finalLongSleepIntervalMin = longSleepIntervalMin || 180;
const finalLongSleepIntervalMax = longSleepIntervalMax || 300;
const finalPagesPerBatch = Math.max(localPagesPerBatch || 15, 5); // 确保最小值为5
const settingsToSend = {
crawlInterval: useRandomInterval
? (finalCrawlIntervalMin + finalCrawlIntervalMax) / 2
: Math.round((finalCrawlIntervalMin + finalCrawlIntervalMax) / 2),
longSleepInterval: useRandomInterval
? (finalLongSleepIntervalMin + finalLongSleepIntervalMax) / 2
: Math.round((finalLongSleepIntervalMin + finalLongSleepIntervalMax) / 2),
pagesPerBatch: finalPagesPerBatch,
crawlIntervalMin: useRandomInterval ? finalCrawlIntervalMin : undefined,
crawlIntervalMax: useRandomInterval ? finalCrawlIntervalMax : undefined,
longSleepIntervalMin: useRandomInterval ? finalLongSleepIntervalMin : undefined,
longSleepIntervalMax: useRandomInterval ? finalLongSleepIntervalMax : undefined,
};
try {
onSettingsChange(settingsToSend);
} catch (error) {
console.error('CrawlSettingsDialog handleSave - onSettingsChange 调用失败:', error);
}
onOpenChange(false);
};
const handleCancel = () => {
// 重置为原始值
setLocalCrawlInterval(crawlInterval);
setLocalLongSleepInterval(longSleepInterval);
setLocalPagesPerBatch(pagesPerBatch);
onOpenChange(false);
};
const setPreset = (preset: 'fast' | 'standard' | 'safe') => {
setUseRandomInterval(true);
setSelectedPreset(preset);
switch (preset) {
case 'fast':
setCrawlIntervalMin(1);
setCrawlIntervalMax(3);
setLongSleepIntervalMin(60);
setLongSleepIntervalMax(120);
setLocalPagesPerBatch(20);
break;
case 'standard':
setCrawlIntervalMin(2);
setCrawlIntervalMax(5);
setLongSleepIntervalMin(180);
setLongSleepIntervalMax(300);
setLocalPagesPerBatch(15);
break;
case 'safe':
setCrawlIntervalMin(5);
setCrawlIntervalMax(10);
setLongSleepIntervalMin(300);
setLongSleepIntervalMax(600);
setLocalPagesPerBatch(10);
break;
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>话题爬取间隔设置</DialogTitle>
<DialogDescription>
调整话题爬取的间隔时间和批次设置,以避免触发反爬虫机制。
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{/* 间隔模式选择 */}
<div className="space-y-2">
<Label>间隔模式</Label>
<div className="flex gap-2">
<Button
type="button"
variant={useRandomInterval ? "default" : "outline"}
size="sm"
onClick={() => setUseRandomInterval(true)}
className="flex-1"
>
随机间隔 (推荐)
</Button>
<Button
type="button"
variant={!useRandomInterval ? "default" : "outline"}
size="sm"
onClick={() => setUseRandomInterval(false)}
className="flex-1"
>
固定间隔
</Button>
</div>
</div>
{/* 爬取间隔范围 */}
<div className="space-y-2">
<Label>页面爬取间隔范围 (秒)</Label>
<div className="flex gap-2 items-center">
<Input
type="number"
min="1"
max="60"
value={crawlIntervalMin}
onChange={(e) => {
const value = e.target.value;
if (value === '') {
setCrawlIntervalMin('');
} else {
const num = parseInt(value);
if (!isNaN(num)) {
setCrawlIntervalMin(num);
}
}
}}
onBlur={(e) => {
if (e.target.value === '') {
setCrawlIntervalMin(2);
}
}}
placeholder="2"
className="flex-1"
/>
<span className="text-sm text-gray-500">-</span>
<Input
type="number"
min="1"
max="60"
value={crawlIntervalMax}
onChange={(e) => {
const value = e.target.value;
if (value === '') {
setCrawlIntervalMax('');
} else {
const num = parseInt(value);
if (!isNaN(num)) {
setCrawlIntervalMax(num);
}
}
}}
onBlur={(e) => {
if (e.target.value === '') {
setCrawlIntervalMax(5);
}
}}
placeholder="5"
className="flex-1"
/>
</div>
<p className="text-xs text-gray-500">
{useRandomInterval
? '每次爬取页面后的随机等待时间范围'
: `每次爬取页面后的固定等待时间 (取中间值: ${Math.round((crawlIntervalMin + crawlIntervalMax) / 2)}秒)`
}
</p>
</div>
{/* 长休眠间隔范围 */}
<div className="space-y-2">
<Label>长休眠间隔范围 (秒)</Label>
<div className="flex gap-2 items-center">
<Input
type="number"
min="60"
max="3600"
value={longSleepIntervalMin}
onChange={(e) => {
const value = e.target.value;
if (value === '') {
setLongSleepIntervalMin('');
} else {
const num = parseInt(value);
if (!isNaN(num)) {
setLongSleepIntervalMin(num);
}
}
}}
onBlur={(e) => {
if (e.target.value === '') {
setLongSleepIntervalMin(180);
}
}}
placeholder="180"
className="flex-1"
/>
<span className="text-sm text-gray-500">-</span>
<Input
type="number"
min="60"
max="3600"
value={longSleepIntervalMax}
onChange={(e) => {
const value = e.target.value;
if (value === '') {
setLongSleepIntervalMax('');
} else {
const num = parseInt(value);
if (!isNaN(num)) {
setLongSleepIntervalMax(num);
}
}
}}
onBlur={(e) => {
if (e.target.value === '') {
setLongSleepIntervalMax(300);
}
}}
placeholder="300"
className="flex-1"
/>
</div>
<p className="text-xs text-gray-500">
{useRandomInterval
? '达到批次大小后的随机长时间休眠范围'
: `达到批次大小后的固定长时间休眠 (取中间值: ${Math.round((longSleepIntervalMin + longSleepIntervalMax) / 2)}秒)`
}
</p>
</div>
{/* 批次大小 */}
<div className="space-y-2">
<Label>批次大小 (页面数)</Label>
<Input
type="number"
min="5"
max="50"
value={localPagesPerBatch}
onChange={(e) => {
const value = e.target.value;
if (value === '') {
setLocalPagesPerBatch('');
} else {
const num = parseInt(value);
if (!isNaN(num)) {
setLocalPagesPerBatch(num);
}
}
}}
onBlur={(e) => {
if (e.target.value === '' || parseInt(e.target.value) < 5) {
setLocalPagesPerBatch(15);
}
}}
placeholder="15"
/>
<p className="text-xs text-gray-500">
爬取多少个页面后触发长休眠(最小值:5页)
</p>
</div>
{/* 快速配置 */}
<div className="space-y-2">
<Label>快速配置</Label>
<div className="flex gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setPreset('fast')}
className={`flex-1 ${
selectedPreset === 'fast'
? 'bg-green-100 text-green-800 border-green-300 hover:bg-green-200'
: 'bg-gray-50 text-gray-500 border-gray-200 hover:bg-gray-100'
}`}
>
快速
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setPreset('standard')}
className={`flex-1 ${
selectedPreset === 'standard'
? 'bg-blue-100 text-blue-800 border-blue-300 hover:bg-blue-200'
: 'bg-gray-50 text-gray-500 border-gray-200 hover:bg-gray-100'
}`}
>
标准
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setPreset('safe')}
className={`flex-1 ${
selectedPreset === 'safe'
? 'bg-orange-100 text-orange-800 border-orange-300 hover:bg-orange-200'
: 'bg-gray-50 text-gray-500 border-gray-200 hover:bg-gray-100'
}`}
>
安全
</Button>
</div>
<div className="text-xs text-gray-500 space-y-1">
<div>• 快速: 1-3秒间隔, 1-2分钟长休眠, 20页/批次</div>
<div>• 标准: 2-5秒间隔, 3-5分钟长休眠, 15页/批次</div>
<div>• 安全: 5-10秒间隔, 5-10分钟长休眠, 10页/批次</div>
</div>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={handleCancel}>
取消
</Button>
<Button type="button" onClick={handleSave}>
保存设置
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
|
281677160/openwrt-package
| 36,966
|
luci-app-passwall/luasrc/passwall/api.lua
|
module("luci.passwall.api", package.seeall)
local com = require "luci.passwall.com"
bin = require "nixio".bin
fs = require "nixio.fs"
sys = require "luci.sys"
uci = require "luci.model.uci".cursor()
util = require "luci.util"
datatypes = require "luci.cbi.datatypes"
jsonc = require "luci.jsonc"
i18n = require "luci.i18n"
appname = "passwall"
curl_args = { "-skfL", "--connect-timeout 3", "--retry 3" }
command_timeout = 300
OPENWRT_ARCH = nil
DISTRIB_ARCH = nil
OPENWRT_BOARD = nil
CACHE_PATH = "/tmp/etc/" .. appname .. "_tmp"
LOG_FILE = "/tmp/log/" .. appname .. ".log"
TMP_PATH = "/tmp/etc/" .. appname
TMP_IFACE_PATH = TMP_PATH .. "/iface"
function log(...)
local result = os.date("%Y-%m-%d %H:%M:%S: ") .. table.concat({...}, " ")
local f, err = io.open(LOG_FILE, "a")
if f and err == nil then
f:write(result .. "\n")
f:close()
end
end
function is_js_luci()
return sys.call('[ -f "/www/luci-static/resources/uci.js" ]') == 0
end
function is_old_uci()
return sys.call("grep -E 'require[ \t]*\"uci\"' /usr/lib/lua/luci/model/uci.lua >/dev/null 2>&1") == 0
end
function set_apply_on_parse(map)
if not map then
return
end
if is_js_luci() then
map.apply_on_parse = false
map.on_after_apply = function(self)
showMsg_Redirect(self.redirect, 3000)
end
end
map.render = function(self, ...)
getmetatable(self).__index.render(self, ...) -- 保持原渲染流程
optimize_cbi_ui()
end
end
function showMsg_Redirect(redirectUrl, delay)
local message = "PassWall " .. i18n.translate("Settings have been successfully saved and applied!")
luci.http.write([[
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
// 创建遮罩层
var overlay = document.createElement('div');
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
overlay.style.zIndex = '9999';
// 创建提示条
var messageDiv = document.createElement('div');
messageDiv.style.position = 'fixed';
messageDiv.style.top = '0';
messageDiv.style.left = '0';
messageDiv.style.width = '100%';
messageDiv.style.background = '#4caf50';
messageDiv.style.color = '#fff';
messageDiv.style.textAlign = 'center';
messageDiv.style.padding = '10px';
messageDiv.style.zIndex = '10000';
messageDiv.textContent = ']] .. message .. [[';
// 将遮罩层和提示条添加到页面
document.body.appendChild(overlay);
document.body.appendChild(messageDiv);
// 重定向或隐藏提示条和遮罩层
var redirectUrl = ']] .. (redirectUrl or "") .. [[';
var delay = ]] .. (delay or 3000) .. [[;
setTimeout(function() {
if (redirectUrl) {
window.location.href = redirectUrl;
} else {
if (messageDiv && messageDiv.parentNode) {
messageDiv.parentNode.removeChild(messageDiv);
}
if (overlay && overlay.parentNode) {
overlay.parentNode.removeChild(overlay);
}
window.location.href = window.location.href;
}
}, delay);
});
</script>
]])
end
function uci_save(cursor, config, commit, apply)
if is_old_uci() then
cursor:save(config)
if commit then
cursor:commit(config)
if apply then
sys.call("/etc/init.d/" .. config .. " reload > /dev/null 2>&1 &")
end
end
else
commit = true
if commit then
if apply then
cursor:commit(config)
else
sh_uci_commit(config)
end
end
end
end
function sh_uci_get(config, section, option)
local _, val = exec_call(string.format("uci -q get %s.%s.%s", config, section, option))
return val
end
function sh_uci_set(config, section, option, val, commit)
exec_call(string.format("uci -q set %s.%s.%s=\"%s\"", config, section, option, val))
if commit then sh_uci_commit(config) end
end
function sh_uci_del(config, section, option, commit)
exec_call(string.format("uci -q delete %s.%s.%s", config, section, option))
if commit then sh_uci_commit(config) end
end
function sh_uci_add_list(config, section, option, val, commit)
exec_call(string.format("uci -q del_list %s.%s.%s=\"%s\"", config, section, option, val))
exec_call(string.format("uci -q add_list %s.%s.%s=\"%s\"", config, section, option, val))
if commit then sh_uci_commit(config) end
end
function sh_uci_commit(config)
exec_call(string.format("uci -q commit %s", config))
end
function set_cache_var(key, val)
sys.call(string.format('/usr/share/passwall/app.sh set_cache_var %s "%s"', key, val))
end
function get_cache_var(key)
local val = sys.exec(string.format('echo -n $(/usr/share/passwall/app.sh get_cache_var %s)', key))
if val == "" then val = nil end
return val
end
function exec_call(cmd)
local process = io.popen(cmd .. '; echo -e "\n$?"')
local lines = {}
local result = ""
local return_code
for line in process:lines() do
lines[#lines + 1] = line
end
process:close()
if #lines > 0 then
return_code = lines[#lines]
for i = 1, #lines - 1 do
result = result .. lines[i] .. ((i == #lines - 1) and "" or "\n")
end
end
return tonumber(return_code), trim(result)
end
function base64Decode(text)
local raw = text
if not text then return '' end
text = text:gsub("%z", "")
text = text:gsub("%c", "")
text = text:gsub("_", "/")
text = text:gsub("-", "+")
local mod4 = #text % 4
text = text .. string.sub('====', mod4 + 1)
local result = nixio.bin.b64decode(text)
if result then
return result:gsub("%z", "")
else
return raw
end
end
function base64Encode(text)
local result = nixio.bin.b64encode(text)
return result
end
--提取URL中的域名和端口(no ip)
function get_domain_port_from_url(url)
local scheme, domain, port = string.match(url, "^(https?)://([%w%.%-]+):?(%d*)")
if not domain then
scheme, domain, port = string.match(url, "^(https?)://(%b[])([^:/]*)/?")
end
if not domain then return nil, nil end
if domain:sub(1, 1) == "[" then domain = domain:sub(2, -2) end
port = port ~= "" and tonumber(port) or (scheme == "https" and 443 or 80)
if datatypes.ipaddr(domain) or datatypes.ip6addr(domain) then return nil, nil end
return domain, port
end
--解析域名
function domainToIPv4(domain, dns)
local Dns = dns or "223.5.5.5"
local IPs = luci.sys.exec('nslookup %s %s | awk \'/^Name:/{getline; if ($1 == "Address:") print $2}\'' % { domain, Dns })
for IP in string.gmatch(IPs, "%S+") do
if datatypes.ipaddr(IP) and not datatypes.ip6addr(IP) then return IP end
end
return nil
end
function curl_base(url, file, args)
if not args then args = {} end
if file then
args[#args + 1] = "-o " .. file
end
local cmd = string.format('curl %s "%s"', table_join(args), url)
return exec_call(cmd)
end
function curl_proxy(url, file, args)
--使用代理
local socks_server = get_cache_var("GLOBAL_TCP_SOCKS_server")
if socks_server and socks_server ~= "" then
if not args then args = {} end
local tmp_args = clone(args)
tmp_args[#tmp_args + 1] = "-x socks5h://" .. socks_server
return curl_base(url, file, tmp_args)
end
return nil, nil
end
function curl_logic(url, file, args)
local return_code, result = curl_proxy(url, file, args)
if not return_code or return_code ~= 0 then
return_code, result = curl_base(url, file, args)
end
return return_code, result
end
function curl_direct(url, file, args)
--直连访问
local chn_list = uci:get(appname, "@global[0]", "chn_list") or "direct"
local Dns = (chn_list == "proxy") and "1.1.1.1" or "223.5.5.5"
if not args then args = {} end
local tmp_args = clone(args)
local domain, port = get_domain_port_from_url(url)
if domain then
local ip = domainToIPv4(domain, Dns)
if ip then
tmp_args[#tmp_args + 1] = "--resolve " .. domain .. ":" .. port .. ":" .. ip
end
end
return curl_base(url, file, tmp_args)
end
function curl_auto(url, file, args)
local localhost_proxy = uci:get(appname, "@global[0]", "localhost_proxy") or "1"
if localhost_proxy == "1" then
return curl_base(url, file, args) -- 当路由器本机开启代理时,采用passwall规则进行访问
else
local return_code, result = curl_proxy(url, file, args)
if not return_code or return_code ~= 0 then
return_code, result = curl_direct(url, file, args)
end
return return_code, result
end
end
function url(...)
local url = string.format("admin/services/%s", appname)
local args = { ... }
for i, v in pairs(args) do
if v ~= "" then
url = url .. "/" .. v
end
end
return require "luci.dispatcher".build_url(url)
end
function trim(text)
if not text or text == "" then return "" end
return text:match("^%s*(.-)%s*$")
end
-- 分割字符串
function split(full, sep)
if full then
full = full:gsub("%z", "") -- 这里不是很清楚 有时候结尾带个\0
local off, result = 1, {}
while true do
local nStart, nEnd = full:find(sep, off)
if not nEnd then
local res = string.sub(full, off, string.len(full))
if #res > 0 then -- 过滤掉 \0
table.insert(result, res)
end
break
else
table.insert(result, string.sub(full, off, nStart - 1))
off = nEnd + 1
end
end
return result
end
return {}
end
function is_exist(table, value)
for index, k in ipairs(table) do
if k == value then
return true
end
end
return false
end
function repeat_exist(table, value)
local count = 0
for index, k in ipairs(table) do
if k:find("-") and k == value then
count = count + 1
end
end
if count > 1 then
return true
end
return false
end
function remove(...)
for index, value in ipairs({...}) do
if value and #value > 0 and value ~= "/" then
sys.call(string.format("rm -rf %s", value))
end
end
end
function is_install(package)
if package and #package > 0 then
local file_path = "/usr/lib/opkg/info"
local file_ext = ".control"
local has = sys.call("[ -d " .. file_path .. " ]")
if has ~= 0 then
file_path = "/lib/apk/packages"
file_ext = ".list"
end
return sys.call(string.format('[ -s "%s/%s%s" ]', file_path, package, file_ext)) == 0
end
return false
end
function get_args(arg)
local var = {}
for i, arg_k in pairs(arg) do
if i > 0 then
local v = arg[i + 1]
if v then
if repeat_exist(arg, v) == false then
var[arg_k] = v
end
end
end
end
return var
end
function get_function_args(arg)
local var = nil
if arg and #arg > 1 then
local param = {}
for i = 2, #arg do
param[#param + 1] = arg[i]
end
var = get_args(param)
end
return var
end
function strToTable(str)
if str == nil or type(str) ~= "string" then
return {}
end
return loadstring("return " .. str)()
end
function is_normal_node(e)
if e and e.type and e.protocol and (e.protocol == "_balancing" or e.protocol == "_shunt" or e.protocol == "_iface" or e.protocol == "_urltest") then
return false
end
return true
end
function is_special_node(e)
return is_normal_node(e) == false
end
function is_ip(val)
if is_ipv6(val) then
val = get_ipv6_only(val)
end
return datatypes.ipaddr(val)
end
function is_ipv6(val)
local str = val
local address = val:match('%[(.*)%]')
if address then
str = address
end
if datatypes.ip6addr(str) then
return true
end
return false
end
function is_local_ip(ip)
ip = tostring(ip or ""):lower()
ip = ip:gsub("^[%w%d]+://", "") -- 去掉协议头
:gsub("/.*$", "") -- 去掉路径
:gsub("^%[", ""):gsub("%]$", "") -- 去掉IPv6方括号
:gsub(":%d+$", "") -- 去掉端口
return ip:match("^127%.") or ip:match("^10%.") or
ip:match("^172%.1[6-9]%.") or ip:match("^172%.2[0-9]%.") or
ip:match("^172%.3[0-1]%.") or ip:match("^192%.168%.") or
ip == "::1" or ip:match("^f[cd]") or ip:match("^fe[89ab]")
end
function is_ipv6addrport(val)
if is_ipv6(val) then
local address, port = val:match('%[(.*)%]:([^:]+)$')
if port then
return datatypes.port(port)
end
end
return false
end
function get_ipv6_only(val)
local result = ""
if is_ipv6(val) then
result = val
if val:match('%[(.*)%]') then
result = val:match('%[(.*)%]')
end
end
return result
end
function get_ipv6_full(val)
local result = ""
if is_ipv6(val) then
result = val
if not val:match('%[(.*)%]') then
result = "[" .. result .. "]"
end
end
return result
end
function get_ip_type(val)
if is_ipv6(val) then
return "6"
elseif datatypes.ip4addr(val) then
return "4"
end
return ""
end
function is_mac(val)
return datatypes.macaddr(val)
end
function ip_or_mac(val)
if val then
if get_ip_type(val) == "4" then
return "ip"
end
if is_mac(val) then
return "mac"
end
end
return ""
end
function iprange(val)
if val then
local ipStart, ipEnd = val:match("^([^/]+)-([^/]+)$")
if (ipStart and datatypes.ip4addr(ipStart)) and (ipEnd and datatypes.ip4addr(ipEnd)) then
return true
end
end
return false
end
function get_domain_from_url(url)
local domain = string.match(url, "//([^/]+)")
if domain then
return domain
end
return url
end
function get_valid_nodes()
local show_node_info = uci_get_type("@global_other[0]", "show_node_info", "0")
local nodes = {}
uci:foreach(appname, "nodes", function(e)
e.id = e[".name"]
if e.type and e.remarks then
if (e.type == "sing-box" or e.type == "Xray") and e.protocol and
(e.protocol == "_balancing" or e.protocol == "_shunt" or e.protocol == "_iface" or e.protocol == "_urltest") then
local type = e.type
if type == "sing-box" then type = "Sing-Box" end
e["remark"] = "%s:[%s] " % {type .. " " .. i18n.translatef(e.protocol), e.remarks}
e["node_type"] = "special"
nodes[#nodes + 1] = e
end
local port = e.port or e.hysteria_hop or e.hysteria2_hop
if port and e.address then
local address = e.address
if is_ip(address) or datatypes.hostname(address) then
local type = e.type
if (type == "sing-box" or type == "Xray") and e.protocol then
local protocol = e.protocol
if protocol == "vmess" then
protocol = "VMess"
elseif protocol == "vless" then
protocol = "VLESS"
elseif protocol == "shadowsocks" then
protocol = "SS"
elseif protocol == "shadowsocksr" then
protocol = "SSR"
elseif protocol == "wireguard" then
protocol = "WG"
elseif protocol == "hysteria" then
protocol = "HY"
elseif protocol == "hysteria2" then
protocol = "HY2"
elseif protocol == "anytls" then
protocol = "AnyTLS"
elseif protocol == "ssh" then
protocol = "SSH"
else
protocol = protocol:gsub("^%l",string.upper)
end
if type == "sing-box" then type = "Sing-Box" end
type = type .. " " .. protocol
end
if is_ipv6(address) then address = get_ipv6_full(address) end
e["remark"] = "%s:[%s]" % {type, e.remarks}
if show_node_info == "1" then
port = port:gsub(":", "-")
e["remark"] = "%s:[%s] %s:%s" % {type, e.remarks, address, port}
end
e.node_type = "normal"
nodes[#nodes + 1] = e
end
end
end
end)
return nodes
end
function get_node_remarks(n)
local remarks = ""
if n then
if (n.type == "sing-box" or n.type == "Xray") and n.protocol and
(n.protocol == "_balancing" or n.protocol == "_shunt" or n.protocol == "_iface" or n.protocol == "_urltest") then
remarks = "%s:[%s] " % {n.type .. " " .. i18n.translatef(n.protocol), n.remarks}
else
local type2 = n.type
if (n.type == "sing-box" or n.type == "Xray") and n.protocol then
local protocol = n.protocol
if protocol == "vmess" then
protocol = "VMess"
elseif protocol == "vless" then
protocol = "VLESS"
elseif protocol == "shadowsocks" then
protocol = "SS"
elseif protocol == "shadowsocksr" then
protocol = "SSR"
elseif protocol == "wireguard" then
protocol = "WG"
elseif protocol == "hysteria" then
protocol = "HY"
elseif protocol == "hysteria2" then
protocol = "HY2"
elseif protocol == "anytls" then
protocol = "AnyTLS"
elseif protocol == "ssh" then
protocol = "SSH"
else
protocol = protocol:gsub("^%l",string.upper)
end
if type2 == "sing-box" then type2 = "Sing-Box" end
type2 = type2 .. " " .. protocol
end
remarks = "%s:[%s]" % {type2, n.remarks}
end
end
return remarks
end
function get_full_node_remarks(n)
local remarks = get_node_remarks(n)
if #remarks > 0 then
local port = n.port or n.hysteria_hop or n.hysteria2_hop
if n.address and port then
port = port:gsub(":", "-")
remarks = remarks .. " " .. n.address .. ":" .. port
end
end
return remarks
end
function gen_uuid(format)
local uuid = sys.exec("echo -n $(cat /proc/sys/kernel/random/uuid)")
if format == nil then
uuid = string.gsub(uuid, "-", "")
end
return uuid
end
function gen_short_uuid()
return sys.exec("echo -n $(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 8)")
end
function uci_get_type(type, config, default)
local value = uci:get(appname, type, config) or default
if (value == nil or value == "") and (default and default ~= "") then
value = default
end
return value
end
local function chmod_755(file)
if file and file ~= "" then
if not fs.access(file, "rwx", "rx", "rx") then
fs.chmod(file, 755)
end
end
end
function get_customed_path(e)
return uci_get_type("@global_app[0]", e .. "_file")
end
function finded_com(e)
local bin = get_app_path(e)
if not bin then return end
local s = luci.sys.exec('echo -n $(type -t -p "%s" | head -n1)' % { bin })
if s == "" then
s = nil
end
return s
end
function finded(e)
return luci.sys.exec('echo -n $(type -t -p "/bin/%s" -p "/usr/bin/%s" "%s" | head -n1)' % {e, e, e})
end
function is_finded(e)
return finded(e) ~= "" and true or false
end
function clone(org)
local function copy(org, res)
for k,v in pairs(org) do
if type(v) ~= "table" then
res[k] = v;
else
res[k] = {};
copy(v, res[k])
end
end
end
local res = {}
copy(org, res)
return res
end
function get_bin_version_cache(file, cmd)
sys.call("mkdir -p /tmp/etc/passwall_tmp")
if fs.access(file) then
chmod_755(file)
local md5 = sys.exec("echo -n $(md5sum " .. file .. " | awk '{print $1}')")
if fs.access("/tmp/etc/passwall_tmp/" .. md5) then
return sys.exec("echo -n $(cat /tmp/etc/passwall_tmp/%s)" % md5)
else
local version = sys.exec(string.format("echo -n $(%s %s)", file, cmd))
if version and version ~= "" then
sys.call("echo '" .. version .. "' > " .. "/tmp/etc/passwall_tmp/" .. md5)
return version
end
end
end
return ""
end
function get_app_path(app_name)
if com[app_name] then
local def_path = com[app_name].default_path
local path = uci_get_type("@global_app[0]", app_name:gsub("%-","_") .. "_file")
path = path and (#path>0 and path or def_path) or def_path
return path
end
end
function get_app_version(app_name, file)
if file == nil then file = get_app_path(app_name) end
return get_bin_version_cache(file, com[app_name].cmd_version)
end
local function is_file(path)
if path and #path > 1 then
if sys.exec('[ -f "%s" ] && echo -n 1' % path) == "1" then
return true
end
end
return nil
end
local function is_dir(path)
if path and #path > 1 then
if sys.exec('[ -d "%s" ] && echo -n 1' % path) == "1" then
return true
end
end
return nil
end
local function get_final_dir(path)
if is_dir(path) then
return path
else
return get_final_dir(fs.dirname(path))
end
end
local function get_free_space(dir)
if dir == nil then dir = "/" end
if sys.call("df -k " .. dir .. " >/dev/null 2>&1") == 0 then
return tonumber(sys.exec("echo -n $(df -k " .. dir .. " | awk 'NR>1' | awk '{print $4}')"))
end
return 0
end
local function get_file_space(file)
if file == nil then return 0 end
if fs.access(file) then
return tonumber(sys.exec("echo -n $(du -k " .. file .. " | awk '{print $1}')"))
end
return 0
end
function _unpack(t, i)
i = i or 1
if t[i] ~= nil then return t[i], _unpack(t, i + 1) end
end
function table_join(t, s)
if not s then
s = " "
end
local str = ""
for index, value in ipairs(t) do
str = str .. t[index] .. (index == #t and "" or s)
end
return str
end
local function exec(cmd, args, writer, timeout)
local os = require "os"
local nixio = require "nixio"
local fdi, fdo = nixio.pipe()
local pid = nixio.fork()
if pid > 0 then
fdo:close()
if writer or timeout then
local starttime = os.time()
while true do
if timeout and os.difftime(os.time(), starttime) >= timeout then
nixio.kill(pid, nixio.const.SIGTERM)
return 1
end
if writer then
local buffer = fdi:read(2048)
if buffer and #buffer > 0 then
writer(buffer)
end
end
local wpid, stat, code = nixio.waitpid(pid, "nohang")
if wpid and stat == "exited" then return code end
if not writer and timeout then nixio.nanosleep(1) end
end
else
local wpid, stat, code = nixio.waitpid(pid)
return wpid and stat == "exited" and code
end
elseif pid == 0 then
nixio.dup(fdo, nixio.stdout)
fdi:close()
fdo:close()
nixio.exece(cmd, args, nil)
nixio.stdout:close()
os.exit(1)
end
end
function compare_versions(ver1, comp, ver2)
local table = table
if not ver1 then ver1 = "" end
if not ver2 then ver2 = "" end
local av1 = util.split(ver1, "[%.%-]", nil, true)
local av2 = util.split(ver2, "[%.%-]", nil, true)
local max = table.getn(av1)
local n2 = table.getn(av2)
if (max < n2) then max = n2 end
for i = 1, max, 1 do
local s1 = tonumber(av1[i] or 0) or 0
local s2 = tonumber(av2[i] or 0) or 0
if comp == "~=" and (s1 ~= s2) then return true end
if (comp == "<" or comp == "<=") and (s1 < s2) then return true end
if (comp == ">" or comp == ">=") and (s1 > s2) then return true end
if (s1 ~= s2) then return false end
end
return not (comp == "<" or comp == ">")
end
local function auto_get_arch()
local arch = nixio.uname().machine or ""
if not OPENWRT_ARCH and fs.access("/usr/lib/os-release") then
OPENWRT_ARCH = sys.exec("echo -n $(grep 'OPENWRT_ARCH' /usr/lib/os-release | awk -F '[\\042\\047]' '{print $2}')")
OPENWRT_BOARD = sys.exec("echo -n $(grep 'OPENWRT_BOARD' /usr/lib/os-release | awk -F '[\\042\\047]' '{print $2}')")
if OPENWRT_ARCH == "" then OPENWRT_ARCH = nil end
if OPENWRT_BOARD == "" then OPENWRT_BOARD = nil end
end
if not DISTRIB_ARCH and fs.access("/etc/openwrt_release") then
DISTRIB_ARCH = sys.exec("echo -n $(grep 'DISTRIB_ARCH' /etc/openwrt_release | awk -F '[\\042\\047]' '{print $2}')")
if DISTRIB_ARCH == "" then DISTRIB_ARCH = nil end
end
if arch:match("^i[%d]86$") then
arch = "x86"
elseif arch:match("armv5") then -- armv5l
arch = "armv5"
elseif arch:match("armv6") then
arch = "armv6"
elseif arch:match("armv7") then -- armv7l
arch = "armv7"
end
if OPENWRT_ARCH or DISTRIB_ARCH then
if arch == "mips" then
if OPENWRT_ARCH and OPENWRT_ARCH:match("mipsel") == "mipsel"
or DISTRIB_ARCH and DISTRIB_ARCH:match("mipsel") == "mipsel" then
arch = "mipsel"
end
elseif arch == "armv7" then
if OPENWRT_ARCH and not OPENWRT_ARCH:match("vfp") and not OPENWRT_ARCH:match("neon")
or DISTRIB_ARCH and not DISTRIB_ARCH:match("vfp") and not DISTRIB_ARCH:match("neon") then
arch = "armv5"
end
end
end
if arch == "aarch64" and OPENWRT_BOARD and OPENWRT_BOARD:match("rockchip") ~= nil then
arch = "rockchip"
end
return trim(arch)
end
function parseURL(url)
if not url or url == "" then
return nil
end
local pattern = "^(%w+)://"
local protocol = url:match(pattern)
if not protocol then
--error("Invalid URL: " .. url)
return nil
end
local auth_host_port = url:sub(#protocol + 4)
local auth_pattern = "^([^@]+)@"
local auth = auth_host_port:match(auth_pattern)
local username, password
if auth then
username, password = auth:match("^([^:]+):([^:]+)$")
auth_host_port = auth_host_port:sub(#auth + 2)
end
local host, port = auth_host_port:match("^([^:]+):(%d+)$")
if not host or not port then
--error("Invalid URL: " .. url)
return nil
end
return {
protocol = protocol,
username = username,
password = password,
host = host,
port = tonumber(port)
}
end
local default_file_tree = {
x86_64 = "amd64",
x86 = "386",
aarch64 = "arm64",
rockchip = "arm64",
mips = "mips",
mips64 = "mips64",
mipsel = "mipsel",
mips64el = "mips64el",
armv5 = "arm.*5",
armv6 = "arm.*6[^4]*",
armv7 = "arm.*7",
armv8 = "arm64",
riscv64 = "riscv64"
}
local function get_api_json(url)
local jsonc = require "luci.jsonc"
local return_code, content = curl_auto(url, nil, curl_args)
if return_code ~= 0 or content == "" then return {} end
return jsonc.parse(content) or {}
end
local function check_path(app_name)
local path = get_app_path(app_name) or ""
if path == "" then
return {
code = 1,
error = i18n.translatef("You did not fill in the %s path. Please save and apply then update manually.", app_name)
}
end
return {
code = 0,
app_path = path
}
end
function to_check(arch, app_name)
local result = check_path(app_name)
if result.code ~= 0 then
return result
end
if not arch or arch == "" then arch = auto_get_arch() end
local file_tree = com[app_name].file_tree[arch] or default_file_tree[arch] or ""
if file_tree == "" then
return {
code = 1,
error = i18n.translate("Can't determine ARCH, or ARCH not supported.")
}
end
local local_version = get_app_version(app_name)
local match_file_name = string.format(com[app_name].match_fmt_str, file_tree)
local json = get_api_json(com[app_name]:get_url())
if #json > 0 then
json = json[1]
end
if json.tag_name == nil then
return {
code = 1,
error = i18n.translate("Get remote version info failed.")
}
end
local remote_version = json.tag_name
if com[app_name].remote_version_str_replace then
remote_version = remote_version:gsub(com[app_name].remote_version_str_replace, "")
end
local has_update = compare_versions(local_version:match("[^v]+"), "<", remote_version:match("[^v]+"))
--[[
if not has_update then
return {
code = 0,
local_version = local_version,
remote_version = remote_version
}
end
]]--
local asset = {}
for _, v in ipairs(json.assets) do
if v.name and v.name:match(match_file_name) then
asset = v
break
end
end
if not asset.browser_download_url then
return {
code = 1,
local_version = local_version,
remote_version = remote_version,
html_url = json.html_url,
data = asset,
error = i18n.translate("New version found, but failed to get new version download url.")
}
end
return {
code = 0,
has_update = has_update,
local_version = local_version,
remote_version = remote_version,
html_url = json.html_url,
data = asset
}
end
function to_download(app_name, url, size)
local result = check_path(app_name)
if result.code ~= 0 then
return result
end
if not url or url == "" then
return {code = 1, error = i18n.translate("Download url is required.")}
end
sys.call("/bin/rm -f /tmp/".. app_name .."_download.*")
local tmp_file = trim(util.exec("mktemp -u -t ".. app_name .."_download.XXXXXX"))
if size then
local kb1 = get_free_space("/tmp")
if tonumber(size) > tonumber(kb1) then
return {code = 1, error = i18n.translatef("%s not enough space.", "/tmp")}
end
end
local _curl_args = clone(curl_args)
table.insert(_curl_args, "--speed-limit 51200 --speed-time 15 --max-time 300")
local return_code, result = curl_auto(url, tmp_file, _curl_args)
result = return_code == 0
if not result then
exec("/bin/rm", {"-f", tmp_file})
return {
code = 1,
error = i18n.translatef("File download failed or timed out: %s", url)
}
end
return {code = 0, file = tmp_file, zip = com[app_name].zipped }
end
function to_extract(app_name, file, subfix)
local result = check_path(app_name)
if result.code ~= 0 then
return result
end
if not file or file == "" or not fs.access(file) then
return {code = 1, error = i18n.translate("File path required.")}
end
local tools_name
if com[app_name].zipped then
if not com[app_name].zipped_suffix or com[app_name].zipped_suffix == "zip" then
tools_name = "unzip"
end
if com[app_name].zipped_suffix and com[app_name].zipped_suffix == "tar.gz" then
tools_name = "tar"
end
if tools_name then
if sys.exec("echo -n $(command -v %s)" % { tools_name }) == "" then
exec("/bin/rm", {"-f", file})
return {
code = 1,
error = i18n.translate("Not installed %s, Can't unzip!" % { tools_name })
}
end
end
end
sys.call("/bin/rm -rf /tmp/".. app_name .."_extract.*")
local new_file_size = get_file_space(file)
local tmp_free_size = get_free_space("/tmp")
if tmp_free_size <= 0 or tmp_free_size <= new_file_size then
return {code = 1, error = i18n.translatef("%s not enough space.", "/tmp")}
end
local tmp_dir = trim(util.exec("mktemp -d -t ".. app_name .."_extract.XXXXXX"))
local output = {}
if tools_name then
if tools_name == "unzip" then
local bin = sys.exec("echo -n $(command -v unzip)")
exec(bin, {"-o", file, app_name, "-d", tmp_dir}, function(chunk) output[#output + 1] = chunk end)
elseif tools_name == "tar" then
local bin = sys.exec("echo -n $(command -v tar)")
if com[app_name].zipped_suffix == "tar.gz" then
exec(bin, {"-zxf", file, "-C", tmp_dir}, function(chunk) output[#output + 1] = chunk end)
sys.call("/bin/mv -f " .. tmp_dir .. "/*/" .. com[app_name].name:lower() .. " " .. tmp_dir)
end
end
end
local files = util.split(table.concat(output))
exec("/bin/rm", {"-f", file})
return {code = 0, file = tmp_dir}
end
function to_move(app_name,file)
local result = check_path(app_name)
if result.code ~= 0 then
return result
end
local app_path = result.app_path
local bin_path = file
local cmd_rm_tmp = "/bin/rm -rf /tmp/" .. app_name .. "_download.*"
if fs.stat(file, "type") == "dir" then
bin_path = file .. "/" .. com[app_name].name:lower()
cmd_rm_tmp = "/bin/rm -rf /tmp/" .. app_name .. "_extract.*"
end
if not file or file == "" then
sys.call(cmd_rm_tmp)
return {code = 1, error = i18n.translate("Client file is required.")}
end
local new_version = get_app_version(app_name, bin_path)
if new_version == "" then
sys.call(cmd_rm_tmp)
return {
code = 1,
error = i18n.translate("The client file is not suitable for current device.") .. app_name .. "__" .. bin_path
}
end
local flag = sys.call('pgrep -af "passwall/.*'.. app_name ..'" >/dev/null')
if flag == 0 then
sys.call("/etc/init.d/passwall stop")
end
local old_app_size = 0
if fs.access(app_path) then
old_app_size = get_file_space(app_path)
end
local new_app_size = get_file_space(bin_path)
local final_dir = get_final_dir(app_path)
local final_dir_free_size = get_free_space(final_dir)
if final_dir_free_size > 0 then
final_dir_free_size = final_dir_free_size + old_app_size
if new_app_size > final_dir_free_size then
sys.call(cmd_rm_tmp)
return {code = 1, error = i18n.translatef("%s not enough space.", final_dir)}
end
end
result = exec("/bin/mv", { "-f", bin_path, app_path }, nil, command_timeout) == 0
sys.call(cmd_rm_tmp)
if flag == 0 then
sys.call("/etc/init.d/passwall restart >/dev/null 2>&1 &")
end
if not result or not fs.access(app_path) then
return {
code = 1,
error = i18n.translatef("Can't move new file to path: %s", app_path)
}
end
return {code = 0}
end
function get_version()
local version = sys.exec("opkg list-installed luci-app-passwall 2>/dev/null | awk '{print $3}'")
if not version or #version == 0 then
version = sys.exec("apk list luci-app-passwall 2>/dev/null | awk '/installed/ {print $1}' | cut -d'-' -f4-")
end
return version or ""
end
function to_check_self()
local url = "https://raw.githubusercontent.com/xiaorouji/openwrt-passwall/main/luci-app-passwall/Makefile"
local tmp_file = "/tmp/passwall_makefile"
local return_code, result = curl_auto(url, tmp_file, curl_args)
result = return_code == 0
if not result then
exec("/bin/rm", {"-f", tmp_file})
return {
code = 1,
error = i18n.translatef("Failed")
}
end
local local_version = get_version()
local remote_version = sys.exec("echo -n $(grep 'PKG_VERSION' /tmp/passwall_makefile|awk -F '=' '{print $2}')")
exec("/bin/rm", {"-f", tmp_file})
local has_update = compare_versions(local_version, "<", remote_version)
if not has_update then
return {
code = 0,
local_version = local_version,
remote_version = remote_version
}
end
return {
code = 1,
has_update = true,
local_version = local_version,
remote_version = remote_version,
error = i18n.translatef("The latest version: %s, currently does not support automatic update, if you need to update, please compile or download the ipk and then manually install.", remote_version)
}
end
function luci_types(id, m, s, type_name, option_prefix)
local rewrite_option_table = {}
for key, value in pairs(s.fields) do
if key:find(option_prefix) == 1 then
if not s.fields[key].not_rewrite then
if s.fields[key].rewrite_option then
if not rewrite_option_table[s.fields[key].rewrite_option] then
rewrite_option_table[s.fields[key].rewrite_option] = 1
else
rewrite_option_table[s.fields[key].rewrite_option] = rewrite_option_table[s.fields[key].rewrite_option] + 1
end
end
s.fields[key].cfgvalue = function(self, section)
-- 添加自定义 custom_cfgvalue 属性,如果有自定义的 custom_cfgvalue 函数,则使用自定义的 cfgvalue 逻辑
if self.custom_cfgvalue then
return self:custom_cfgvalue(section)
else
if self.rewrite_option then
return m:get(section, self.rewrite_option)
else
if self.option:find(option_prefix) == 1 then
return m:get(section, self.option:sub(1 + #option_prefix))
end
end
end
end
s.fields[key].write = function(self, section, value)
if s.fields["type"]:formvalue(id) == type_name then
-- 添加自定义 custom_write 属性,如果有自定义的 custom_write 函数,则使用自定义的 write 逻辑
if self.custom_write then
self:custom_write(section, value)
else
if self.rewrite_option then
m:set(section, self.rewrite_option, value)
else
if self.option:find(option_prefix) == 1 then
m:set(section, self.option:sub(1 + #option_prefix), value)
end
end
end
end
end
s.fields[key].remove = function(self, section)
if s.fields["type"]:formvalue(id) == type_name then
-- 添加自定义 custom_remove 属性,如果有自定义的 custom_remove 函数,则使用自定义的 remove 逻辑
if self.custom_remove then
self:custom_remove(section)
else
if self.rewrite_option and rewrite_option_table[self.rewrite_option] == 1 then
m:del(section, self.rewrite_option)
else
if self.option:find(option_prefix) == 1 then
m:del(section, self.option:sub(1 + #option_prefix))
end
end
end
end
end
end
local deps = s.fields[key].deps
if #deps > 0 then
for index, value in ipairs(deps) do
deps[index]["type"] = type_name
end
else
s.fields[key]:depends({ type = type_name })
end
end
end
end
function get_std_domain(domain)
domain = trim(domain)
if domain == "" or domain:find("#") then return "" end
-- 删除首尾所有的 .
domain = domain:gsub("^[%.]+", ""):gsub("[%.]+$", "")
-- 如果 domain 包含 '*',则分割并删除包含 '*' 的部分及其前面的部分
if domain:find("%*") then
local parts = {}
for part in domain:gmatch("[^%.]+") do
table.insert(parts, part)
end
for i = #parts, 1, -1 do
if parts[i]:find("%*") then
-- 删除包含 '*' 的部分及其前面的部分
return parts[i + 1] and parts[i + 1] .. "." .. table.concat(parts, ".", i + 2) or ""
end
end
end
return domain
end
function format_go_time(input)
input = input and trim(input)
local N = 0
if input and input:match("^%d+$") then
N = tonumber(input)
elseif input and input ~= "" then
for value, unit in input:gmatch("(%d+)%s*([hms])") do
value = tonumber(value)
if unit == "h" then
N = N + value * 3600
elseif unit == "m" then
N = N + value * 60
elseif unit == "s" then
N = N + value
end
end
end
if N <= 0 then
return "0s"
end
local result = ""
local h = math.floor(N / 3600)
local m = math.floor(N % 3600 / 60)
local s = N % 60
if h > 0 then result = result .. h .. "h" end
if m > 0 then result = result .. m .. "m" end
if s > 0 or result == "" then result = result .. s .. "s" end
return result
end
function optimize_cbi_ui()
luci.http.write([[
<script type="text/javascript">
//修正上移、下移按钮名称
document.querySelectorAll("input.btn.cbi-button.cbi-button-up").forEach(function(btn) {
btn.value = "]] .. i18n.translate("Move up") .. [[";
});
document.querySelectorAll("input.btn.cbi-button.cbi-button-down").forEach(function(btn) {
btn.value = "]] .. i18n.translate("Move down") .. [[";
});
//删除控件和说明之间的多余换行
document.querySelectorAll("div.cbi-value-description").forEach(function(descDiv) {
var prev = descDiv.previousSibling;
while (prev && prev.nodeType === Node.TEXT_NODE && prev.textContent.trim() === "") {
prev = prev.previousSibling;
}
if (prev && prev.nodeType === Node.ELEMENT_NODE && prev.tagName === "BR") {
prev.remove();
}
});
</script>
]])
end
|
2951121599/Bili-Insight
| 2,080
|
chrome-extension/scripts/constants.js
|
BILIBILI_SPACE_URL = "https://space.bilibili.com/"
BILIBILI_POPULAR_URL = "https://www.bilibili.com/v/popular"
BILIBILI_VIDEO_TYPE_MAP = {"1": "动画", "24": "MAD·AMV", "25": "MMD·3D", "47": "短片·手书·配音", "210": "手办·模玩", "86": "特摄", "253": "动漫杂谈", "27": "综合", "13": "番剧", "51": "资讯", "152": "官方延伸", "32": "完结动画", "33": "连载动画", "167": "国创", "153": "国产动画", "168": "国产原创相关", "169": "布袋戏", "170": "资讯", "195": "动态漫·广播剧", "3": "音乐", "28": "原创音乐", "31": "翻唱", "30": "VOCALOID·UTAU", "59": "演奏", "193": "MV", "29": "音乐现场", "130": "音乐综合", "243": "乐评盘点", "244": "音乐教学", "129": "舞蹈", "20": "宅舞", "154": "舞蹈综合", "156": "舞蹈教程", "198": "街舞", "199": "明星舞蹈", "200": "中国舞", "4": "游戏", "17": "单机游戏", "171": "电子竞技", "172": "手机游戏", "65": "网络游戏", "173": "桌游棋牌", "121": "GMV", "136": "音游", "19": "Mugen", "36": "知识", "201": "科学科普", "124": "社科·法律·心理", "228": "人文历史", "207": "财经商业", "208": "校园学习", "209": "职业职场", "229": "设计·创意", "122": "野生技术协会", "188": "科技", "95": "数码", "230": "软件应用", "231": "计算机技术", "232": "科工机械 ", "233": "极客DIY", "234": "运动", "235": "篮球", "249": "足球", "164": "健身", "236": "竞技体育", "237": "运动文化", "238": "运动综合", "223": "汽车", "245": "赛车", "246": "改装玩车", "247": "新能源车", "248": "房车", "240": "摩托车", "227": "购车攻略", "176": "汽车生活", "160": "生活", "138": "搞笑", "250": "出行", "251": "三农", "239": "家居房产", "161": "手工", "162": "绘画", "21": "日常", "211": "美食", "76": "美食制作", "212": "美食侦探", "213": "美食测评", "214": "田园美食", "215": "美食记录", "217": "动物圈", "218": "喵星人", "219": "汪星人", "220": "大熊猫", "221": "野生动物", "222": "爬宠", "75": "动物综合", "119": "鬼畜", "22": "鬼畜调教", "26": "音MAD", "126": "人力VOCALOID", "216": "鬼畜剧场", "127": "教程演示", "155": "时尚", "157": "美妆护肤", "252": "仿妆cos", "158": "穿搭", "159": "时尚潮流", "202": "资讯", "203": "热点", "204": "环球", "205": "社会", "206": "综合", "165": "广告", "5": "娱乐", "71": "综艺", "241": "娱乐杂谈", "242": "粉丝创作", "137": "明星综合", "181": "影视", "182": "影视杂谈", "183": "影视剪辑", "85": "小剧场", "184": "预告·资讯", "177": "纪录片", "37": "人文·历史", "178": "科学·探索·自然", "179": "军事", "180": "社会·美食·旅行", "23": "电影", "147": "华语电影", "145": "欧美电影", "146": "日本电影", "83": "其他国家", "11": "电视剧", "185": "国产剧", "187": "海外剧"}
|
2951121599/Bili-Insight
| 3,571
|
chrome-extension/content-scripts/content.js
|
document.addEventListener("mouseover", showProfileDebounce);
document.addEventListener("mousemove", (ev) => videoProfileCard.updateCursor(ev.pageX, ev.pageY));
biliInsightOptions = null;
chrome.storage.sync.get({
enableWordCloud: true,
minSize: 5
}, function (items) {
biliInsightOptions = items;
});
biliInsightOptions = {
enableWordCloud: true,
minSize: 5
}
function getVideoFromLink(url) {
var vid = url.split("/")[4];
if (vid.startsWith('BV')) {
if (vid.indexOf('?') > 5) {
return vid.slice(0, vid.indexOf('?'));
}
return vid;
}
}
async function getVideoId(target) {
if (target.tagName == "DIV" && target.classList.contains("card-box")) {
return getVideoFromLink(target.childNodes[1].firstChild.href);
}
if (target.tagName == "A" && target.classList.contains("dynamic-video-item")) {
return getVideoFromLink(target.href);
}
if (target.childNodes[0].tagName == "A") {
return getVideoFromLink(target.childNodes[0].href);
}
let vid = getVideoFromLink(target.childNodes[0].firstChild.href);
if (vid) {
return vid;
}
}
function getTarget(target) {
for (let videoLink of [
target,
target?.parentNode,
target?.parentNode?.parentNode,
target?.parentNode?.parentNode?.parentNode,
target?.parentNode?.parentNode?.parentNode?.parentNode,
target?.parentNode?.parentNode?.parentNode?.parentNode?.parentNode,
target?.parentNode?.parentNode?.parentNode?.parentNode?.parentNode?.parentNode]) {
if (videoLink) {
if (videoLink.tagName == "DIV" && videoLink.classList.contains("video-card")) {
return videoLink;
}
if (videoLink.tagName == "DIV" && videoLink.classList.contains("bili-video-card__wrap")) {
return videoLink;
}
//动态页面
if (videoLink.tagName == "DIV" && videoLink.classList.contains("bili-dyn-content__orig__major")) {
return videoLink;
}
if (videoLink.tagName == "A" && videoLink.classList.contains("dynamic-video-item")) {
return videoLink;
}
if (videoLink.tagName == "DIV" && videoLink.classList.contains("small-item") && videoLink.classList.contains("fakeDanmu-item")) {
return videoLink;
}
//推荐
if (videoLink.tagName == "DIV" && videoLink.classList.contains("card-box")) {
return videoLink;
}
}
}
return null;
}
function showProfile(event) {
let target = getTarget(event.target);
if (target && videoProfileCard.enable()) {
videoProfileCard.updateCursor(event.pageX, event.pageY);
videoProfileCard.updateTarget(target);
getVideoId(target).then((vid) => {
if (vid) {
if (vid != videoProfileCard.videoId) {
videoProfileCard.updateVideoId(vid);
updateVideoInfo(vid, (data) => videoProfileCard.updateData(data));
}
} else {
videoProfileCard.disable();
}
})
} else {
videoProfileCard.checkTargetValid(event.target);
}
}
function showProfileDebounce(event) {
clearTimeout(showProfileDebounce.timer);
event.target.addEventListener("mouseout", () => clearTimeout(showProfileDebounce.timer));
showProfileDebounce.timer = setTimeout(() => {
showProfile(event)
}, 200);
}
|
2951121599/Bili-Insight
| 1,719
|
chrome-extension/css/viedocard.css
|
#biliinsight-video-card {
background: #fff;
box-shadow: 0 0 2px rgba(0, 0, 0, .3);
border-radius: 8px;
position: absolute;
z-index: 1002;
width: 425px;
line-height: 1.6;
overflow: hidden;
}
#biliinsight-video-card * {
box-sizing: content-box;
}
#biliinsight-video-card .d-none {
display: none;
}
#biliinsight-video-card data-title {
color: #777;
}
#biliinsight-video-card .idc-info {
padding: 7px 35px 10px 40px;
position: relative
}
#biliinsight-video-card .idc-meta {
font-size: 12px;
margin-top: 4px
}
#biliinsight-video-card .idc-meta-item {
margin-right: 20px
}
#biliinsight-video-card .idc-tag-list {
display: none;
padding-bottom: 0
}
#biliinsight-video-card .description {
line-height: 20px;
font-size: 12px;
margin-top: 4px;
color: #6d757a
}
#biliinsight-video-card #tag-list-bi {
margin-top: 6px;
margin-bottom: 8px;
}
#biliinsight-video-card .badge {
color: white;
display: inline-block;
padding: 0px 10px;
line-height: 24px;
vertical-align: top;
font-size: 12px;
font-weight: 600;
border-radius: 6px;
background-color: #00a1d6;
margin-right: 5px;
}
#word-cloud-canvas-wrapper-bi {
height: 0px;
overflow: hidden;
transition-property: height, opacity;
transition-duration: .25s;
transition-timing-function: ease;
}
#word-cloud-canvas-wrapper-bi.canvas-show {
height: 187.5px;
}
.markmap>svg {
width: 425px;
height: 200px;
}
.markmap-wrapper {
height: 0px;
transition-property: height, opacity;
transition-duration: .25s;
transition-timing-function: ease;
}
.markmap-wrapper.canvas-show {
height: 200px;
}
|
Subsets and Splits
HTML Files in Train Set
Retrieves all records from the dataset where the file path ends with .html or .htm, providing a basic filter for HTML files.
SQL Console for nick007x/github-code-2025
Retrieves 200 file paths that end with '.html' or '.htm', providing a basic overview of HTML files in the dataset.
Top HTML Files
The query retrieves a sample of HTML file paths, providing basic filtering but limited analytical value.
CSharp Repositories Excluding Unity
Retrieves all records for repositories that contain C# files but are not related to Unity, providing a basic filter of the dataset.
C# File Count per Repository
Counts the total number of C# files across distinct repositories, providing a basic measure of C# file presence.
SQL Console for nick007x/github-code-2025
Lists unique repository IDs containing C# files, providing basic filtering to understand which repositories have C# code.
Select Groovy Files: Train Set
Retrieves the first 1000 entries from the 'train' dataset where the file path ends with '.groovy', providing a basic sample of Groovy files.
GitHub Repos with WiFiClientSecure
Finds specific file paths in repositories that contain particular code snippets related to WiFiClientSecure and ChatGPT, providing basic filtering of relevant files.