repo_id
stringlengths
6
101
size
int64
367
5.14M
file_path
stringlengths
2
269
content
stringlengths
367
5.14M
2977094657/BiliHistoryFrontend
42,633
src/components/tailwind/page/VideoDownloader.vue
<!-- 视频下载界面 --> <template> <div class="mt-10"> <!-- 搜索区域 - 使用与首页一致的搜索栏,去掉背景、边框和顶部内容 --> <div class="mx-auto max-w-6xl"> <div> <!-- 搜索框和类型选择 --> <div class="flex flex-col md:flex-row gap-4"> <!-- 搜索框容器 --> <div class="w-full flex"> <div class="flex items-center rounded-md border border-gray-300 bg-white focus-within:border-[#fb7299] transition-colors duration-200 flex-grow"> <!-- 下载类型选择 --> <div class="h-10 pl-2 flex items-center"> <CustomDropdown v-model="downloadType" :options="downloadTypeOptions" :selected-text="getDownloadTypeLabel(downloadType)" @change="onDownloadTypeChange" custom-class="h-full border-none !shadow-none !p-0 !m-0 !rounded-none !pr-1" :min-width="120" :use-fixed-width="false" > <template #trigger-content> <span class="text-[#fb7299] text-sm flex items-center whitespace-nowrap">{{ getDownloadTypeLabel(downloadType) }}</span> </template> </CustomDropdown> </div> <!-- 分隔线 --> <div class="h-5 w-px bg-gray-200 mx-1"></div> <!-- 输入框 --> <input v-model="inputValue" @keyup.enter="handleDownload" type="search" :placeholder="downloadType === 'video' ? '输入BV号或完整视频链接' : '输入UP主UID'" class="h-10 w-full border-none bg-transparent px-2 pr-3 text-gray-700 focus:outline-none focus:ring-0 text-sm leading-none" /> </div> <!-- 搜索按钮 - 增加左边距 --> <button @click="handleDownload" :disabled="!inputValue" class="flex-shrink-0 bg-[#fb7299] hover:bg-[#fb7299]/90 text-white px-4 py-2 rounded-md font-medium transition-colors duration-200 flex items-center justify-center ml-4" > <span class="flex items-center"> <svg class="mr-1 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path> </svg> 下载视频 </span> </button> </div> </div> <p class="mt-2 text-xs text-gray-500"> {{ downloadType === 'video' ? '支持完整链接或 BV 号,例如:BV1xx411c7mD' : '在 UP 主空间页面 URL 中查看 UID' }} </p> </div> </div> <!-- 空状态提示 --> <div v-if="!inputValue" class="mx-auto max-w-6xl mt-24 flex flex-col items-center justify-center text-center"> <div class="w-24 h-24 text-gray-300 mb-4"> <svg fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /> </svg> </div> <h3 class="text-lg font-medium text-gray-900 mb-2">开始下载视频</h3> <p class="text-sm text-gray-500 max-w-md"> {{ downloadType === 'video' ? '请输入视频的 BV 号或完整链接,支持单个视频下载' : '请输入 UP 主的 UID,支持批量下载 UP 主的所有投稿视频' }} </p> </div> <!-- 视频信息卡片(仅当有视频信息且输入框有内容时显示) --> <div v-if="hasVideoInfo && inputValue" class="mx-auto max-w-6xl"> <div class="mb-6 overflow-hidden"> <!-- 视频信息卡片内容 --> <div class="p-4 flex flex-col"> <!-- 视频数据统计和提示信息合并在同一行 --> <div class="flex flex-wrap items-center gap-4 mb-4"> <!-- 播放量 --> <div class="flex items-center"> <svg class="view-icon w-4 h-4 text-gray-600 mr-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <path d="M10 4.040041666666666C7.897383333333334 4.040041666666666 6.061606666666667 4.147 4.765636666666667 4.252088333333334C3.806826666666667 4.32984 3.061106666666667 5.0637316666666665 2.9755000000000003 6.015921666666667C2.8803183333333333 7.074671666666667 2.791666666666667 8.471183333333332 2.791666666666667 9.998333333333333C2.791666666666667 11.525566666666668 2.8803183333333333 12.922083333333333 2.9755000000000003 13.9808C3.061106666666667 14.932983333333334 3.806826666666667 15.666916666666667 4.765636666666667 15.744683333333336C6.061611666666668 15.849716666666666 7.897383333333334 15.956666666666667 10 15.956666666666667C12.10285 15.956666666666667 13.93871666666667 15.849716666666666 15.234766666666667 15.74461666666667C16.193416666666668 15.66685 16.939000000000004 14.933216666666667 17.024583333333336 13.981216666666668C17.11975 12.922916666666667 17.208333333333332 11.526666666666666 17.208333333333332 9.998333333333333C17.208333333333332 8.470083333333333 17.11975 7.073818333333334 17.024583333333336 6.015513333333334C16.939000000000004 5.063538333333333 16.193416666666668 4.329865000000001 15.234766666666667 4.252118333333334C13.93871666666667 4.147016666666667 12.10285 4.040041666666666 10 4.040041666666666zM4.684808333333334 3.255365C6.001155 3.14862 7.864583333333334 3.0400416666666668 10 3.0400416666666668C12.13565 3.0400416666666668 13.999199999999998 3.148636666666667 15.315566666666667 3.2553900000000002C16.753416666666666 3.3720016666666672 17.890833333333333 4.483195 18.020583333333335 5.925965000000001C18.11766666666667 7.005906666666667 18.208333333333336 8.433 18.208333333333336 9.998333333333333C18.208333333333336 11.56375 18.11766666666667 12.990833333333335 18.020583333333335 14.0708C17.890833333333333 15.513533333333331 16.753416666666666 16.624733333333335 15.315566666666667 16.74138333333333C13.999199999999998 16.848116666666666 12.13565 16.95666666666667 10 16.95666666666667C7.864583333333334 16.95666666666667 6.001155 16.848116666666666 4.684808333333334 16.7414C3.2467266666666665 16.624750000000002 2.1092383333333338 15.513266666666667 1.9795200000000002 14.070383333333334C1.8823900000000002 12.990000000000002 1.7916666666666667 11.562683333333334 1.7916666666666667 9.998333333333333C1.7916666666666667 8.434066666666666 1.8823900000000002 7.00672 1.9795200000000002 5.926381666666667C2.1092383333333338 4.483463333333334 3.2467266666666665 3.371976666666667 4.684808333333334 3.255365z" fill="currentColor"></path> <path d="M12.23275 9.1962C12.851516666666667 9.553483333333332 12.851516666666667 10.44665 12.232683333333332 10.803866666666666L9.57975 12.335600000000001C8.960983333333335 12.692816666666667 8.1875 12.246250000000002 8.187503333333334 11.531733333333333L8.187503333333334 8.4684C8.187503333333334 7.753871666666667 8.960983333333335 7.307296666666667 9.57975 7.66456L12.23275 9.1962z" fill="currentColor"></path> </svg> <span class="text-sm font-medium text-gray-600">{{ formatCount(videoInfo.stat?.view) }}</span> </div> <!-- 弹幕数 --> <div class="flex items-center"> <svg class="dm-icon w-4 h-4 text-gray-600 mr-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <path d="M10 4.040041666666666C7.897383333333334 4.040041666666666 6.061606666666667 4.147 4.765636666666667 4.252088333333334C3.806826666666667 4.32984 3.061106666666667 5.0637316666666665 2.9755000000000003 6.015921666666667C2.8803183333333333 7.074671666666667 2.791666666666667 8.471183333333332 2.791666666666667 9.998333333333333C2.791666666666667 11.525566666666668 2.8803183333333333 12.922083333333333 2.9755000000000003 13.9808C3.061106666666667 14.932983333333334 3.806826666666667 15.666916666666667 4.765636666666667 15.744683333333336C6.061611666666668 15.849716666666666 7.897383333333334 15.956666666666667 10 15.956666666666667C12.10285 15.956666666666667 13.93871666666667 15.849716666666666 15.234766666666667 15.74461666666667C16.193416666666668 15.66685 16.939000000000004 14.933216666666667 17.024583333333336 13.981216666666668C17.11975 12.922916666666667 17.208333333333332 11.526666666666666 17.208333333333332 9.998333333333333C17.208333333333332 8.470083333333333 17.11975 7.073818333333334 17.024583333333336 6.015513333333334C16.939000000000004 5.063538333333333 16.193416666666668 4.329865000000001 15.234766666666667 4.252118333333334C13.93871666666667 4.147016666666667 12.10285 4.040041666666666 10 4.040041666666666zM4.684808333333334 3.255365C6.001155 3.14862 7.864583333333334 3.0400416666666668 10 3.0400416666666668C12.13565 3.0400416666666668 13.999199999999998 3.148636666666667 15.315566666666667 3.2553900000000002C16.753416666666666 3.3720016666666672 17.890833333333333 4.483195 18.020583333333335 5.925965000000001C18.11766666666667 7.005906666666667 18.208333333333336 8.433 18.208333333333336 9.998333333333333C18.208333333333336 11.56375 18.11766666666667 12.990833333333335 18.020583333333335 14.0708C17.890833333333333 15.513533333333331 16.753416666666666 16.624733333333335 15.315566666666667 16.74138333333333C13.999199999999998 16.848116666666666 12.13565 16.95666666666667 10 16.95666666666667C7.864583333333334 16.95666666666667 6.001155 16.848116666666666 4.684808333333334 16.7414C3.2467266666666665 16.624750000000002 2.1092383333333338 15.513266666666667 1.9795200000000002 14.070383333333334C1.8823900000000002 12.990000000000002 1.7916666666666667 11.562683333333334 1.7916666666666667 9.998333333333333C1.7916666666666667 8.434066666666666 1.8823900000000002 7.00672 1.9795200000000002 5.926381666666667C2.1092383333333338 4.483463333333334 3.2467266666666665 3.371976666666667 4.684808333333334 3.255365z" fill="currentColor"></path> <path d="M13.291666666666666 8.833333333333334L8.166666666666668 8.833333333333334C7.890526666666666 8.833333333333334 7.666666666666666 8.609449999999999 7.666666666666666 8.333333333333334C7.666666666666666 8.057193333333334 7.890526666666666 7.833333333333334 8.166666666666668 7.833333333333334L13.291666666666666 7.833333333333334C13.567783333333335 7.833333333333334 13.791666666666668 8.057193333333334 13.791666666666668 8.333333333333334C13.791666666666668 8.609449999999999 13.567783333333335 8.833333333333334 13.291666666666666 8.833333333333334z" fill="currentColor"></path> <path d="M14.541666666666666 12.166666666666666L9.416666666666668 12.166666666666666C9.140550000000001 12.166666666666666 8.916666666666666 11.942783333333333 8.916666666666666 11.666666666666668C8.916666666666666 11.390550000000001 9.140550000000001 11.166666666666668 9.416666666666668 11.166666666666668L14.541666666666666 11.166666666666668C14.817783333333335 11.166666666666668 15.041666666666668 11.390550000000001 15.041666666666668 11.666666666666668C15.041666666666668 11.942783333333333 14.817783333333335 12.166666666666666 14.541666666666666 12.166666666666666z" fill="currentColor"></path> <path d="M6.5 8.333333333333334C6.5 8.609449999999999 6.27614 8.833333333333334 6 8.833333333333334L5.458333333333333 8.833333333333334C5.182193333333334 8.833333333333334 4.958333333333334 8.609449999999999 4.958333333333334 8.333333333333334C4.958333333333334 8.057193333333334 5.182193333333334 7.833333333333334 5.458333333333333 7.833333333333334L6 7.833333333333334C6.27614 7.833333333333334 6.5 8.057193333333334 6.5 8.333333333333334z" fill="currentColor"></path> <path d="M7.750000000000001 11.666666666666668C7.750000000000001 11.942783333333333 7.526140000000001 12.166666666666666 7.25 12.166666666666666L6.708333333333334 12.166666666666666C6.432193333333334 12.166666666666666 6.208333333333334 11.942783333333333 6.208333333333334 11.666666666666668C6.208333333333334 11.390550000000001 6.432193333333334 11.166666666666668 6.708333333333334 11.166666666666668L7.25 11.166666666666668C7.526140000000001 11.166666666666668 7.750000000000001 11.390550000000001 7.750000000000001 11.666666666666668z" fill="currentColor"></path> </svg> <span class="text-sm font-medium text-gray-600">{{ formatCount(videoInfo.stat?.danmaku) }}</span> </div> <!-- 发布时间 --> <div v-if="videoInfo.pubdate" class="flex items-center"> <svg class="w-4 h-4 text-gray-600 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" /> </svg> <span class="text-sm font-medium text-gray-600">{{ formatDetailedTimestamp(videoInfo.pubdate) }}</span> </div> <!-- 警告/提示信息 --> <div v-if="videoInfo.argue_info?.argue_msg" class="inline-flex items-center bg-yellow-50 px-2 py-1 rounded text-xs text-yellow-700"> <span class="mr-1">提示:</span>{{ videoInfo.argue_info.argue_msg }} </div> <!-- 荣誉信息 - 修改样式 --> <div v-if="videoInfo.honor_reply?.honor && videoInfo.honor_reply.honor.length > 0" class="inline-flex flex-wrap gap-4"> <div v-for="(honor, index) in videoInfo.honor_reply.honor" :key="index" class="text-xs px-2 py-1 bg-[#fff7e9] text-[#ffb027] rounded-md flex items-center"> <svg width="16" height="16" viewBox="0 0 16 13" fill="none" xmlns="http://www.w3.org/2000/svg" class="honor-icon mr-1" data-v-b37c19ce=""><path fill-rule="evenodd" clip-rule="evenodd" d="M0.69043 3.9539C0.69043 2.62399 1.76853 1.5459 3.09843 1.5459L3.09843 2.23389C3.09843 2.89885 3.63748 3.4379 4.30243 3.4379C4.96739 3.4379 5.50643 2.89885 5.50643 2.2339V1.5459H10.4944V2.23389C10.4944 2.89885 11.0335 3.4379 11.6984 3.4379C12.3634 3.4379 12.9024 2.89885 12.9024 2.2339L12.9024 1.5459C14.2323 1.5459 15.3104 2.62399 15.3104 3.9539V10.5759C15.3104 11.9058 14.2323 12.9839 12.9024 12.9839H3.09843C1.76853 12.9839 0.69043 11.9058 0.69043 10.5759V3.9539ZM8.59407 5.73981C8.26159 5.73981 7.99207 6.00934 7.99207 6.34181C7.99207 6.67429 8.26159 6.9438 8.59407 6.9438H13.4101C13.7425 6.9438 14.0121 6.67429 14.0121 6.34181C14.0121 6.00934 13.7425 5.73981 13.4101 5.73981H8.59407ZM7.99207 9.35182C7.99207 9.01935 8.26159 8.74982 8.59407 8.74982H13.4101C13.7425 8.74982 14.0121 9.01935 14.0121 9.35182C14.0121 9.6843 13.7425 9.95381 13.4101 9.95381H8.59407C8.26159 9.95381 7.99207 9.6843 7.99207 9.35182ZM2.23794 6.80617L3.04621 6.68384L3.4095 5.92297C3.61412 5.4928 4.20532 5.4928 4.40994 5.92297L4.77212 6.68384L5.5815 6.80617C6.00636 6.87022 6.19423 7.37784 5.95382 7.71812L5.89065 7.79341L5.30428 8.38548L5.44316 9.22243C5.5161 9.66373 5.10432 10.0072 4.71637 9.86957L4.63378 9.83257L3.90972 9.43657L3.18566 9.83257C2.8037 10.0409 2.36159 9.74072 2.36788 9.31535L2.37628 9.22243L2.51404 8.38548L1.92879 7.79341C1.62136 7.48247 1.75692 6.95721 2.14419 6.82854L2.23794 6.80617Z" fill="currentColor"></path> <path fill-rule="evenodd" clip-rule="evenodd" d="M4.31965 1.02979V1.88979V1.02979Z" fill="currentColor"></path> <path d="M4.31965 1.02979V1.88979" stroke-width="1.72" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"></path> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.7415 1.02979V1.88979V1.02979Z" fill="currentColor"></path> <path d="M11.7415 1.02979V1.88979" stroke-width="1.72" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"></path></svg> {{ honor.desc }} </div> </div> </div> <div class="flex flex-col md:flex-row space-x-0 md:space-x-4"> <!-- 左侧封面 --> <div class="w-full md:w-1/3 mb-4 md:mb-0 flex flex-col"> <div class="relative aspect-video bg-gray-200 rounded-lg overflow-hidden"> <img v-if="videoInfo.pic" :src="normalizeImageUrl(videoInfo.pic)" :alt="videoInfo.title" class="w-full h-full object-cover" /> <div v-else class="w-full h-full flex items-center justify-center text-gray-400"> <svg class="w-16 h-16" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" /> </svg> </div> <!-- 视频时长标记 --> <div v-if="videoInfo.duration" class="absolute bottom-1 right-1 rounded bg-black/50 px-1 py-0.5 text-xs font-semibold text-white"> {{ formatDuration(videoInfo.duration) }} </div> <!-- 视频数据统计 - 播放、弹幕、评论放在封面上与时长同一行 --> <div class="absolute bottom-1 left-1 flex space-x-2"> </div> </div> <!-- 视频互动数据统计 - 点赞、投币、收藏、分享 --> <div class="grid grid-cols-4 gap-2 mt-6"> <div class="flex items-center justify-center text-gray-700"> <svg class="w-5 h-5 mr-1" width="36" height="36" viewBox="0 0 36 36" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M9.77234 30.8573V11.7471H7.54573C5.50932 11.7471 3.85742 13.3931 3.85742 15.425V27.1794C3.85742 29.2112 5.50932 30.8573 7.54573 30.8573H9.77234ZM11.9902 30.8573V11.7054C14.9897 10.627 16.6942 7.8853 17.1055 3.33591C17.2666 1.55463 18.9633 0.814421 20.5803 1.59505C22.1847 2.36964 23.243 4.32583 23.243 6.93947C23.243 8.50265 23.0478 10.1054 22.6582 11.7471H29.7324C31.7739 11.7471 33.4289 13.402 33.4289 15.4435C33.4289 15.7416 33.3928 16.0386 33.3215 16.328L30.9883 25.7957C30.2558 28.7683 27.5894 30.8573 24.528 30.8573H11.9911H11.9902Z" fill="currentColor"/> </svg> <span class="text-sm font-medium">{{ formatCount(videoInfo.stat?.like) }}</span> </div> <div class="flex items-center justify-center text-gray-700"> <svg class="w-5 h-5 mr-1" width="28" height="28" viewBox="0 0 28 28" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M14.045 25.5454C7.69377 25.5454 2.54504 20.3967 2.54504 14.0454C2.54504 7.69413 7.69377 2.54541 14.045 2.54541C20.3963 2.54541 25.545 7.69413 25.545 14.0454C25.545 17.0954 24.3334 20.0205 22.1768 22.1771C20.0201 24.3338 17.095 25.5454 14.045 25.5454ZM9.66202 6.81624H18.2761C18.825 6.81624 19.27 7.22183 19.27 7.72216C19.27 8.22248 18.825 8.62807 18.2761 8.62807H14.95V10.2903C17.989 10.4444 20.3766 12.9487 20.3855 15.9916V17.1995C20.3854 17.6997 19.9799 18.1052 19.4796 18.1052C18.9793 18.1052 18.5738 17.6997 18.5737 17.1995V15.9916C18.5667 13.9478 16.9882 12.2535 14.95 12.1022V20.5574C14.95 21.0577 14.5444 21.4633 14.0441 21.4633C13.5437 21.4633 13.1382 21.0577 13.1382 20.5574V12.1022C11.1 12.2535 9.52148 13.9478 9.51448 15.9916V17.1995C9.5144 17.6997 9.10883 18.1052 8.60856 18.1052C8.1083 18.1052 7.70273 17.6997 7.70265 17.1995V15.9916C7.71158 12.9487 10.0992 10.4444 13.1382 10.2903V8.62807H9.66202C9.11309 8.62807 8.66809 8.22248 8.66809 7.72216C8.66809 7.22183 9.11309 6.81624 9.66202 6.81624Z" fill="currentColor"/> </svg> <span class="text-sm font-medium">{{ formatCount(videoInfo.stat?.coin) }}</span> </div> <div class="flex items-center justify-center text-gray-700"> <svg class="w-5 h-5 mr-1" width="28" height="28" viewBox="0 0 28 28" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M19.8071 9.26152C18.7438 9.09915 17.7624 8.36846 17.3534 7.39421L15.4723 3.4972C14.8998 2.1982 13.1004 2.1982 12.4461 3.4972L10.6468 7.39421C10.1561 8.36846 9.25639 9.09915 8.19315 9.26152L3.94016 9.91102C2.63155 10.0734 2.05904 11.6972 3.04049 12.6714L6.23023 15.9189C6.96632 16.6496 7.29348 17.705 7.1299 18.7605L6.39381 23.307C6.14844 24.6872 7.62063 25.6614 8.84745 25.0119L12.4461 23.0634C13.4276 22.4951 14.6544 22.4951 15.6359 23.0634L19.2345 25.0119C20.4614 25.6614 21.8518 24.6872 21.6882 23.307L20.8703 18.7605C20.7051 17.705 21.0339 16.6496 21.77 15.9189L24.9597 12.6714C25.9412 11.6972 25.3687 10.0734 24.06 9.91102L19.8071 9.26152Z" fill="currentColor"/> </svg> <span class="text-sm font-medium">{{ formatCount(videoInfo.stat?.favorite) }}</span> </div> <div class="flex items-center justify-center text-gray-700"> <svg class="w-5 h-5 mr-1" width="28" height="28" viewBox="0 0 28 28" xmlns="http://www.w3.org/2000/svg"> <path d="M12.6058 10.3326V5.44359C12.6058 4.64632 13.2718 4 14.0934 4C14.4423 4 14.78 4.11895 15.0476 4.33606L25.3847 12.7221C26.112 13.3121 26.2087 14.3626 25.6007 15.0684C25.5352 15.1443 25.463 15.2144 25.3847 15.2779L15.0476 23.6639C14.4173 24.1753 13.4791 24.094 12.9521 23.4823C12.7283 23.2226 12.6058 22.8949 12.6058 22.5564V18.053C7.59502 18.053 5.37116 19.9116 2.57197 23.5251C2.47607 23.6489 2.00031 23.7769 2.00031 23.2122C2.00031 16.2165 3.90102 10.3326 12.6058 10.3326Z" fill="currentColor"/> </svg> <span class="text-sm font-medium">{{ formatCount(videoInfo.stat?.share) }}</span> </div> </div> </div> <!-- 右侧信息 --> <div class="w-full md:w-2/3 flex flex-col"> <!-- 视频标题可点击 --> <a :href="`https://www.bilibili.com/video/${videoInfo.bvid}`" target="_blank" class="text-xl font-bold text-gray-900 mb-6 line-clamp-2 hover:text-[#fb7299] transition-colors duration-200" > {{ videoInfo.title }} </a> <!-- 作者信息区域 - UP 主可点击 --> <div v-if="videoInfo.owner" class="flex items-center mb-6 space-x-2"> <a :href="`https://space.bilibili.com/${videoInfo.owner.mid}`" target="_blank" class="flex items-center space-x-2 hover:text-[#fb7299] transition-colors duration-200" > <img v-if="videoInfo.owner.face" :src="videoInfo.owner.face" :alt="videoInfo.owner.name" class="w-10 h-10 rounded-full object-cover border border-gray-200" /> <div class="text-sm font-medium text-gray-900">{{ videoInfo.owner.name || '未知作者' }}</div> </a> </div> <!-- 视频动态信息 - 在作者信息下方,添加提示文字 --> <div v-if="videoInfo.dynamic" class="mb-6 text-xs bg-blue-50 border border-blue-200 px-2 py-1 rounded text-blue-700"> <span class="font-medium mr-1">视频同步发布的动态:</span>{{ videoInfo.dynamic }} </div> <!-- 视频基本信息 --> <div class="mb-6 grid grid-cols-4 gap-2"> <!-- 分区 显示 tname-tname_v2 --> <div v-if="videoInfo.tname" class="flex items-center text-gray-700 text-sm"> <svg class="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" /> </svg> <span>{{ videoInfo.tname + (videoInfo.tname_v2 ? `-${videoInfo.tname_v2}` : '') }}</span> </div> <!-- 视频类型 --> <div v-if="videoInfo.copyright !== undefined" class="flex items-center text-gray-700 text-sm"> <svg class="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /> </svg> <span>{{ videoInfo.copyright === 1 ? '原创' : '转载' }}</span> </div> <!-- 清晰度 --> <div v-if="videoInfo.dimension" class="flex items-center text-gray-700 text-sm"> <svg class="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" /> </svg> <span>{{ videoInfo.dimension.width }}x{{ videoInfo.dimension.height }}</span> </div> <!-- 评论数 --> <div v-if="videoInfo.stat?.reply" class="flex items-center text-gray-700 text-sm"> <svg class="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <span>{{ formatCount(videoInfo.stat?.reply) }} 条评论</span> </div> </div> <!-- 合集信息调试 --> <div v-if="collectionInfo.is_collection" class="mb-5 p-3 bg-blue-50 border border-blue-200 rounded-md"> <h4 class="text-sm font-semibold text-blue-900 mb-2">🎬 检测到合集</h4> <p class="text-sm text-blue-800"> <strong>{{ collectionInfo.collection_title }}</strong> </p> <p class="text-xs text-blue-600 mt-1"> 共 {{ collectionInfo.total_videos }} 个视频,当前是第 {{ collectionInfo.current_video_index }} 个 </p> </div> <!-- 多 P 信息 --> <div v-if="videoInfo.pages && videoInfo.pages.length > 1" class="mb-5"> <h4 class="text-sm font-semibold text-gray-900 mb-5">分 P 列表</h4> <div class="max-h-40 overflow-y-auto border border-gray-200 rounded-md"> <div v-for="(page, index) in videoInfo.pages" :key="index" class="flex items-center p-2 text-sm hover:bg-gray-100 border-b border-gray-100 last:border-b-0" > <span class="mr-2 bg-gray-200 text-gray-700 w-6 h-6 flex items-center justify-center rounded-full text-xs">{{ page.page }}</span> <span class="mr-auto truncate">{{ page.part }}</span> <span class="text-gray-500 text-xs">{{ formatDuration(page.duration) }}</span> </div> </div> </div> </div> </div> <!-- 视频简介 - 移动到外层,占据整行 --> <div v-if="videoInfo.desc" class="mt-3"> <h4 class="text-sm font-semibold text-gray-900 mb-2">视频简介</h4> <p class="text-sm text-gray-600 bg-gray-50 p-2 rounded-md max-h-32 overflow-y-auto whitespace-pre-wrap">{{ videoInfo.desc }}</p> </div> </div> </div> </div> <!-- 用户视频列表 --> <div v-if="downloadType === 'user' && inputValue" class="mt-6"> <UserVideos :mid="inputValue" /> </div> <!-- 下载对话框 --> <DownloadDialog v-model:show="showDownloadDialog" :video-info="downloadVideoInfo" :up-user-videos="upUserVideosList" @download-complete="handleDownloadComplete" /> <!-- 合集选择对话框 --> <Teleport to="body"> <div v-if="showCollectionChoice" class="fixed inset-0 z-50 flex items-center justify-center"> <!-- 背景遮罩 --> <div class="absolute inset-0 bg-black/50" @click="showCollectionChoice = false"></div> <!-- 对话框内容 --> <div class="relative bg-white rounded-lg border border-gray-200 w-[500px] z-10 p-6"> <h3 class="text-lg font-medium text-gray-900 mb-4">检测到合集视频</h3> <div class="mb-4"> <p class="text-gray-600 mb-2"> 此视频属于合集:<span class="font-medium text-gray-800">{{ collectionInfo.collection_title }}</span> </p> <p class="text-sm text-gray-500 mb-4"> 合集共包含 {{ collectionInfo.total_videos }} 个视频,当前是第 {{ collectionInfo.current_video_index }} 个 </p> <p class="text-gray-600 mb-4"> 请选择下载方式: </p> </div> <!-- 选择按钮 --> <div class="flex flex-col gap-3 mb-6"> <button @click="handleCollectionChoice('single')" class="w-full px-4 py-3 text-left border border-gray-200 rounded-md hover:border-[#fb7299] hover:bg-[#fb7299]/5 transition-colors" > <div class="font-medium text-gray-900">只下载当前视频</div> <div class="text-sm text-gray-500">仅下载当前播放的这个视频</div> </button> <button @click="handleCollectionChoice('collection')" class="w-full px-4 py-3 text-left border border-gray-200 rounded-md hover:border-[#fb7299] hover:bg-[#fb7299]/5 transition-colors" > <div class="font-medium text-gray-900">下载整个合集</div> <div class="text-sm text-gray-500">下载合集中的所有 {{ collectionInfo.total_videos }} 个视频</div> </button> </div> <!-- 取消按钮 --> <div class="flex justify-end"> <button @click="showCollectionChoice = false" class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors" > 取消 </button> </div> </div> </div> </Teleport> </div> </template> <script setup> import { ref, computed, watch } from 'vue' import { showNotify } from 'vant' import 'vant/es/notify/style' import { getLoginStatus, downloadVideo, downloadUserVideos, getVideoInfo, checkCollection, downloadCollection } from '../../../api/api' import DownloadDialog from '../DownloadDialog.vue' import SimpleSearchBar from '../SimpleSearchBar.vue' import CustomDropdown from '../CustomDropdown.vue' import UserVideos from '../UserVideos.vue' import { normalizeImageUrl } from '@/utils/imageUrl.js' // 下载类型 const downloadType = ref('video') const inputValue = ref('') // 下载类型选项 const downloadTypeOptions = [ { value: 'video', label: '单个视频' }, { value: 'user', label: 'UP 主投稿' } ] // 获取显示文本 const getDownloadTypeLabel = (value) => { const option = downloadTypeOptions.find(opt => opt.value === value) return option ? option.label : '单个视频' } // 处理下载类型变更 const onDownloadTypeChange = (value) => { downloadType.value = value inputValue.value = '' // 清空输入框 videoInfo.value = {} // 重置视频信息 } // 下载选项 const downloadCover = ref(true) const onlyAudio = ref(false) // 下载状态 const isDownloading = ref(false) const showDownloadDialog = ref(false) // 视频信息 const videoInfo = ref({}) const hasVideoInfo = computed(() => !!videoInfo.value?.bvid) // 合集信息 const collectionInfo = ref({}) const isCollection = computed(() => collectionInfo.value?.is_collection || false) const showCollectionChoice = ref(false) // 下载对话框的视频信息 const downloadVideoInfo = ref({}) // 添加用于存储UP主视频列表的ref const upUserVideosList = ref([]) // 从 BV 链接提取 BV 号 const extractBvid = (input) => { // 如果已经是 BV 开头的格式,直接返回 if (/^BV[a-zA-Z0-9]{10}$/.test(input)) { return input } // 尝试从 URL 中提取 BV 号 const match = input.match(/\/video\/(BV[a-zA-Z0-9]{10})/) if (match && match[1]) { return match[1] } return input // 返回原始输入,让后端处理错误 } // 监听输入框内容变化,自动提取并获取视频信息 watch(inputValue, async (newValue) => { if (downloadType.value === 'video') { if (newValue) { const extractedBvid = extractBvid(newValue) if (/^BV[a-zA-Z0-9]{10}$/.test(extractedBvid)) { // 自动获取视频信息 await handleVideoInfo(extractedBvid) } } else { // 当输入框被清空时,重置视频信息 videoInfo.value = {} } } }) // 获取视频信息单独拆分成函数 const handleVideoInfo = async (bvid) => { isDownloading.value = true try { // 获取视频详细信息 const response = await getVideoInfo({ bvid }) if (response.data.status === 'success') { videoInfo.value = response.data.data console.log('获取到视频信息:', videoInfo.value) // 检查是否为合集 await checkVideoCollection(inputValue.value) } else { throw new Error(response.data.message || '获取视频信息失败') } } catch (error) { console.error('处理失败:', error) showNotify({ type: 'danger', message: error.message || '获取信息失败' }) } finally { isDownloading.value = false } } // 检查视频是否为合集 const checkVideoCollection = async (url) => { try { console.log('开始检查合集,URL:', url) const response = await checkCollection(url) console.log('合集检测API响应:', response) if (response.data.status === 'success') { collectionInfo.value = response.data.data console.log('合集检测结果:', collectionInfo.value) console.log('是否为合集:', collectionInfo.value.is_collection) } else { console.log('合集检测API返回失败状态:', response.data) collectionInfo.value = { is_collection: false } } } catch (error) { console.error('检查合集失败:', error) // 不显示错误,因为这不是关键功能 collectionInfo.value = { is_collection: false } } } // 处理下载 const handleDownload = async () => { try { if (!inputValue.value) return isDownloading.value = true if (downloadType.value === 'video') { // 如果已有视频信息,检查是否为合集 if (hasVideoInfo.value) { console.log('已有视频信息,检查是否为合集') console.log('isCollection.value:', isCollection.value) console.log('collectionInfo.value:', collectionInfo.value) if (isCollection.value) { // 是合集,显示选择对话框 console.log('检测到合集,显示选择对话框') isDownloading.value = false showCollectionChoice.value = true return } else { // 不是合集,直接下载 console.log('不是合集,直接下载') startDownload() } } else { // 没有视频信息,先获取信息再开始下载 console.log('没有视频信息,先获取信息') const extractedBvid = extractBvid(inputValue.value) await handleVideoInfo(extractedBvid) if (hasVideoInfo.value) { console.log('获取视频信息后,检查是否为合集') console.log('isCollection.value:', isCollection.value) console.log('collectionInfo.value:', collectionInfo.value) if (isCollection.value) { // 是合集,显示选择对话框 console.log('检测到合集,显示选择对话框') isDownloading.value = false showCollectionChoice.value = true return } else { // 不是合集,直接下载 console.log('不是合集,直接下载') startDownload() } } } } else { // 用户投稿下载 - 先获取视频列表信息 try { console.log('获取UP主视频信息,UID:', inputValue.value) const { getUserVideos } = await import('../../../api/api') // 先获取第一个视频以获取封面 const response = await getUserVideos({ mid: inputValue.value, pn: 1, ps: 1 // 只获取第一个视频,用于显示封面 }) console.log('获取UP主视频响应:', response.data) // 检查响应 if (response.data.status === 'success' && response.data.data.list.vlist && response.data.data.list.vlist.length > 0) { const firstVideo = response.data.data.list.vlist[0] console.log('第一个视频信息:', firstVideo) console.log('视频封面URL:', firstVideo.pic) // 使用第一个视频的信息 downloadVideoInfo.value = { title: `UP 主 ${firstVideo.author || inputValue.value} 的全部投稿视频`, author: firstVideo.author || '', bvid: firstVideo.bvid || '', pic: firstVideo.pic || '', cover: firstVideo.pic || '', cid: 0, // 特殊字段标识这是用户视频下载 is_user_videos: true, user_id: inputValue.value } console.log('准备显示下载弹窗,传递的视频信息:', downloadVideoInfo.value) console.log('检查封面URL是否正确:', downloadVideoInfo.value.pic) // 开始预加载更多视频的信息,获取页数和投稿总数 await fetchUpUserVideosList(inputValue.value) } else { console.warn('未获取到UP主视频信息,使用默认值') // 使用默认信息 downloadVideoInfo.value = { title: `UP 主 ${inputValue.value} 的全部投稿视频`, author: '', bvid: '', cover: '', pic: '', cid: 0, // 特殊字段标识这是用户视频下载 is_user_videos: true, user_id: inputValue.value } } } catch (error) { console.error('获取UP主视频信息失败:', error) // 使用默认信息 downloadVideoInfo.value = { title: `UP 主 ${inputValue.value} 的全部投稿视频`, author: '', bvid: '', cover: '', pic: '', cid: 0, // 特殊字段标识这是用户视频下载 is_user_videos: true, user_id: inputValue.value } } // 显示下载对话框 showDownloadDialog.value = true } } catch (error) { console.error('处理失败:', error) showNotify({ type: 'danger', message: error.message || '处理失败' }) isDownloading.value = false } } // 获取UP主的视频列表,预加载视频数据 const fetchUpUserVideosList = async (userId) => { try { const { getUserVideos } = await import('../../../api/api') // 先获取第一页,确定总视频数 const response = await getUserVideos({ mid: userId, pn: 1, ps: 30 }) if (!response.data || response.data.status !== 'success') { console.warn('获取UP主视频列表失败') return } // 保存第一页的视频 const videos = response.data.data.list.vlist || [] upUserVideosList.value = videos // 尝试获取总页数 const count = response.data.data.page?.count || 0 if (count > 30) { // 如果总数超过30个,只预加载前2页 const totalPages = Math.min(3, Math.ceil(count / 30)) for (let page = 2; page <= totalPages; page++) { try { const pageResponse = await getUserVideos({ mid: userId, pn: page, ps: 30 }) if (pageResponse.data && pageResponse.data.status === 'success') { const pageVideos = pageResponse.data.data.list.vlist || [] upUserVideosList.value = [...upUserVideosList.value, ...pageVideos] } // 防止频繁请求 await new Promise(resolve => setTimeout(resolve, 300)) } catch (err) { console.error(`获取第${page}页UP主视频列表失败:`, err) } } } console.log(`已预加载 ${upUserVideosList.value.length} 个视频信息`) } catch (error) { console.error('预加载UP主视频列表失败:', error) } } // 格式化时长 const formatDuration = (seconds) => { if (!seconds) return '未知时长' const hours = Math.floor(seconds / 3600) const minutes = Math.floor((seconds % 3600) / 60) const remainingSeconds = seconds % 60 if (hours > 0) { return `${hours}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}` } else { return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}` } } // 格式化时间戳为秒级时间显示 const formatDetailedTimestamp = (timestamp) => { if (!timestamp) return '未知时间' const date = new Date(timestamp * 1000) const year = date.getFullYear() const month = (date.getMonth() + 1).toString().padStart(2, '0') const day = date.getDate().toString().padStart(2, '0') const hours = date.getHours().toString().padStart(2, '0') const minutes = date.getMinutes().toString().padStart(2, '0') const seconds = date.getSeconds().toString().padStart(2, '0') return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}` } // 格式化数字(播放、点赞等) const formatCount = (count) => { if (!count && count !== 0) return '0' if (count >= 10000) { return (count / 10000).toFixed(1) + '万' } return count.toString() } // 开始下载 const startDownload = () => { try { console.log('开始下载,类型:', downloadType.value) if (downloadType.value === 'video') { // 设置视频信息 downloadVideoInfo.value = { title: videoInfo.value.title, author: videoInfo.value.owner?.name || '', bvid: videoInfo.value.bvid, cover: videoInfo.value.pic, pic: videoInfo.value.pic, cid: videoInfo.value.cid } console.log('设置单个视频下载信息:', downloadVideoInfo.value) } else { // 此时应该已经在 handleDownload 中设置了用户投稿下载信息 // 确保必要的字段存在 if (!downloadVideoInfo.value.is_user_videos) { console.warn('用户视频下载信息不完整,重新设置') downloadVideoInfo.value = { ...downloadVideoInfo.value, is_user_videos: true, user_id: inputValue.value } } console.log('用户视频下载信息:', downloadVideoInfo.value) } // 显示下载对话框 showDownloadDialog.value = true } catch (error) { console.error('开始下载失败:', error) showNotify({ type: 'danger', message: error.message || '开始下载失败' }) } } // 处理合集选择 const handleCollectionChoice = (choice) => { showCollectionChoice.value = false if (choice === 'single') { // 下载单个视频 startDownload() } else if (choice === 'collection') { // 下载整个合集 startCollectionDownload() } } // 开始合集下载 const startCollectionDownload = () => { // 设置合集下载信息 downloadVideoInfo.value = { title: collectionInfo.value.collection_title || videoInfo.value.title, author: videoInfo.value.owner?.name || '', bvid: videoInfo.value.bvid, cover: videoInfo.value.pic || '', cid: videoInfo.value.cid || 0, // 特殊字段标识这是合集下载 is_collection_download: true, collection_info: collectionInfo.value, original_url: inputValue.value } // 显示下载对话框 showDownloadDialog.value = true } // 处理下载完成 const handleDownloadComplete = () => { showNotify({ type: 'success', message: '下载任务已完成' }) // 不自动重置输入,让用户可以再次点击下载 } </script> <style scoped> /* 移除搜索框的默认样式 */ input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-results-button, input[type="search"]::-webkit-search-results-decoration { display: none; } /* 移除输入框的默认 focus 样式 */ input:focus { box-shadow: none !important; outline: none !important; } :deep(.custom-dropdown-trigger) { border: none !important; box-shadow: none !important; background: transparent !important; } /* 确保下拉菜单按钮文本不会折行 */ :deep(.custom-dropdown-trigger span) { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } </style>
2977094657/BiliHistoryFrontend
14,326
src/components/tailwind/page/Images.vue
<!-- 图片管理页面 --> <template> <div class="container mx-auto max-w-full"> <!-- 操作按钮 --> <div class="mb-6 flex flex-col space-y-4 sm:flex-row sm:space-y-0 sm:space-x-4"> <div class="flex space-x-4"> <button @click="handleDownloadClick" :disabled="isLoading || isStoppingDownload" class="px-4 py-2 bg-[#fb7299] text-white rounded-md hover:bg-[#fb7299]/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 border border-[#fb7299]/20" > <div class="flex items-center space-x-2"> <svg v-if="isDownloading" class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"> <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle> <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path> </svg> <svg v-else class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /> </svg> <span>{{ isDownloading ? (isStoppingDownload ? '正在停止...' : '停止下载') : '下载图片' }}</span> </div> </button> <button @click="handleClear" :disabled="isDownloading || isLoading || isStoppingDownload" class="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 border border-red-400/20" > <div class="flex items-center space-x-2"> <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /> </svg> <span>清空图片</span> </div> </button> </div> <!-- 下载选项 --> <div class="flex items-center space-x-2 bg-white/50 backdrop-blur-sm rounded-md px-4 py-2 border border-gray-200"> <input type="checkbox" id="useSessdata" v-model="useSessdata" class="w-4 h-4 text-[#fb7299] bg-gray-100 border-gray-300 rounded focus:ring-[#fb7299]" > <label for="useSessdata" class="text-sm text-gray-700"> 使用SESSDATA下载图片(对于公开内容如视频封面和头像,可以不使用SESSDATA) </label> </div> </div> <!-- 加载状态 --> <div v-if="isLoading" class="space-y-8"> <div v-for="i in 2" :key="i" class="bg-white/50 backdrop-blur-sm rounded-lg p-6 border border-gray-200 animate-pulse"> <div class="h-8 bg-gray-200 rounded w-32 mb-4"></div> <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-4"> <div v-for="j in 4" :key="j" class="bg-white/50 rounded-lg p-4 border border-gray-200"> <div class="h-8 bg-gray-200 rounded w-16 mb-2"></div> <div class="h-4 bg-gray-200 rounded w-20"></div> </div> </div> </div> </div> <!-- 下载状态 --> <div v-else class="space-y-8"> <!-- 封面图片状态 --> <div class="bg-white/50 backdrop-blur-sm rounded-lg p-6 border border-gray-200"> <div class="flex items-center justify-between mb-4"> <h2 class="text-xl font-semibold text-[#fb7299]">封面图片</h2> <span class="text-sm text-gray-500">最后更新: {{ formatTime(status?.last_update) }}</span> </div> <!-- 进度条 --> <div v-if="isDownloading" class="mb-6"> <div class="flex justify-between mb-1"> <span class="text-sm text-gray-600">下载进度</span> <span class="text-sm text-gray-600">{{ getProgressPercentage(status?.covers, 'covers') }}%</span> </div> <div class="w-full bg-gray-200 rounded-full h-2.5"> <div class="bg-[#fb7299] h-2.5 rounded-full transition-all duration-500 animate-pulse" :style="{ width: getProgressPercentage(status?.covers, 'covers') + '%' }"></div> </div> </div> <!-- 状态卡片网格 --> <div class="grid grid-cols-2 sm:grid-cols-4 gap-4"> <div class="bg-white/50 rounded-lg p-4 border border-gray-200"> <div class="text-2xl font-bold text-[#fb7299]">{{ status?.covers?.total || 0 }}</div> <div class="text-sm text-gray-500">计划下载</div> </div> <div class="bg-white/50 rounded-lg p-4 border border-gray-200"> <div class="text-2xl font-bold text-[#fb7299]">{{ status?.covers?.downloaded || 0 }}</div> <div class="text-sm text-gray-500">已下载</div> </div> <div class="bg-white/50 rounded-lg p-4 border border-gray-200"> <div class="text-2xl font-bold text-red-500">{{ status?.covers?.failed || 0 }}</div> <div class="text-sm text-gray-500">失败数</div> </div> <div class="bg-white/50 rounded-lg p-4 border border-gray-200"> <div class="text-2xl font-bold text-blue-500">{{ status?.covers?.total_planned || 0 }}</div> <div class="text-sm text-gray-500">待下载</div> </div> </div> <!-- 失败列表 --> <div v-if="status?.covers?.failed_urls?.length" class="mt-4"> <div class="flex items-center space-x-2 mb-2"> <svg class="w-5 h-5 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> <h3 class="text-lg font-medium text-red-500">失败列表</h3> </div> <div class="max-h-40 overflow-y-auto space-y-2"> <div v-for="(item, index) in status.covers.failed_urls" :key="index" class="text-sm text-gray-600 p-2 bg-red-50 rounded border border-red-100"> <div class="flex justify-between"> <span class="font-medium">错误: {{ item.error }}</span> <span class="text-gray-500">{{ formatTime(item.timestamp) }}</span> </div> <div class="mt-1 text-gray-500 break-all">URL: {{ item.url }}</div> </div> </div> </div> </div> <!-- 头像图片状态 --> <div class="bg-white/50 backdrop-blur-sm rounded-lg p-6 border border-gray-200"> <div class="flex items-center justify-between mb-4"> <h2 class="text-xl font-semibold text-[#fb7299]">头像图片</h2> </div> <!-- 进度条 --> <div v-if="isDownloading" class="mb-6"> <div class="flex justify-between mb-1"> <span class="text-sm text-gray-600">下载进度</span> <span class="text-sm text-gray-600">{{ getProgressPercentage(status?.avatars, 'avatars') }}%</span> </div> <div class="w-full bg-gray-200 rounded-full h-2.5"> <div class="bg-[#fb7299] h-2.5 rounded-full transition-all duration-500 animate-pulse" :style="{ width: getProgressPercentage(status?.avatars, 'avatars') + '%' }"></div> </div> </div> <!-- 状态卡片网格 --> <div class="grid grid-cols-2 sm:grid-cols-4 gap-4"> <div class="bg-white/50 rounded-lg p-4 border border-gray-200"> <div class="text-2xl font-bold text-[#fb7299]">{{ status?.avatars?.total || 0 }}</div> <div class="text-sm text-gray-500">计划下载</div> </div> <div class="bg-white/50 rounded-lg p-4 border border-gray-200"> <div class="text-2xl font-bold text-[#fb7299]">{{ status?.avatars?.downloaded || 0 }}</div> <div class="text-sm text-gray-500">已下载</div> </div> <div class="bg-white/50 rounded-lg p-4 border border-gray-200"> <div class="text-2xl font-bold text-red-500">{{ status?.avatars?.failed || 0 }}</div> <div class="text-sm text-gray-500">失败数</div> </div> <div class="bg-white/50 rounded-lg p-4 border border-gray-200"> <div class="text-2xl font-bold text-blue-500">{{ status?.avatars?.total_planned || 0 }}</div> <div class="text-sm text-gray-500">待下载</div> </div> </div> <!-- 失败列表 --> <div v-if="status?.avatars?.failed_urls?.length" class="mt-4"> <div class="flex items-center space-x-2 mb-2"> <svg class="w-5 h-5 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> <h3 class="text-lg font-medium text-red-500">失败列表</h3> </div> <div class="max-h-40 overflow-y-auto space-y-2"> <div v-for="(item, index) in status.avatars.failed_urls" :key="index" class="text-sm text-gray-600 p-2 bg-red-50 rounded border border-red-100"> <div class="flex justify-between"> <span class="font-medium">错误: {{ item.error }}</span> <span class="text-gray-500">{{ formatTime(item.timestamp) }}</span> </div> <div class="mt-1 text-gray-500 break-all">URL: {{ item.url }}</div> </div> </div> </div> </div> </div> </div> </template> <script setup> import { ref, onMounted, onUnmounted } from 'vue' import { getImagesStatus, startImagesDownload, stopImagesDownload, clearImages } from '../../../api/api' import { showNotify, showDialog } from 'vant' import 'vant/es/notify/style' import 'vant/es/dialog/style' const status = ref(null) const isDownloading = ref(false) const isLoading = ref(true) const isStoppingDownload = ref(false) // 新增:是否正在停止下载 const useSessdata = ref(true) // 新增:是否使用SESSDATA let statusInterval = null // 格式化时间戳 const formatTime = (timestamp) => { if (!timestamp) return '无' const date = new Date(timestamp * 1000) return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) } // 计算进度百分比 const getProgressPercentage = (data, type) => { if (!data) return 0 return Math.round((data.downloaded / (data.total || 1)) * 100) } // 获取状态 const fetchStatus = async () => { try { const response = await getImagesStatus() if (response.data.status === 'success') { status.value = response.data.data isDownloading.value = status.value.is_downloading isLoading.value = false // 数据加载完成,关闭加载状态 // 如果下载完成,停止轮询 if (!status.value.is_downloading && statusInterval) { clearInterval(statusInterval) statusInterval = null showNotify({ type: 'success', message: '下载已完成' }) // 1秒后刷新页面 setTimeout(() => { window.location.reload() }, 1000) } } } catch (error) { console.error('获取状态失败:', error) isLoading.value = false // 发生错误时也关闭加载状态 if (statusInterval) { clearInterval(statusInterval) statusInterval = null } } } // 处理下载按钮点击 const handleDownloadClick = async () => { if (isDownloading.value) { // 如果已经在停止过程中,直接返回 if (isStoppingDownload.value) return // 显示确认对话框 try { await showDialog({ title: '确认停止', message: '确定要停止当前下载任务吗?', showCancelButton: true, confirmButtonText: '确认停止', cancelButtonText: '取消', confirmButtonColor: '#ef4444' }) // 设置停止状态,防止重复点击 isStoppingDownload.value = true // 停止下载 const response = await stopImagesDownload() if (response.data.status === 'success') { showNotify({ type: 'success', message: '已停止下载' }) // 重置状态 isDownloading.value = false isStoppingDownload.value = false // 清除定时器 if (statusInterval) { clearInterval(statusInterval) statusInterval = null } // 刷新状态 await fetchStatus() } } catch (error) { // 如果是用户取消,直接返回 if (error.toString().includes('cancel')) return showNotify({ type: 'danger', message: `停止下载失败: ${error.message}` }) } finally { // 如果停止失败,也需要重置停止状态 isStoppingDownload.value = false } } else { // 如果未在下载,则开始下载 try { const response = await startImagesDownload(null, useSessdata.value) if (response.data.status === 'success') { showNotify({ type: 'success', message: response.data.message }) isDownloading.value = true // 立即获取一次状态 await fetchStatus() // 开始定时获取状态 if (!statusInterval) { statusInterval = setInterval(fetchStatus, 1000) } } } catch (error) { showNotify({ type: 'danger', message: `开始下载失败: ${error.message}` }) } } } // 处理清空图片 const handleClear = async () => { try { await showDialog({ title: '确认清空', message: '确定要清空所有图片和下载状态吗?此操作不可恢复。', showCancelButton: true, confirmButtonText: '确认清空', cancelButtonText: '取消', confirmButtonColor: '#ef4444' }) const response = await clearImages() if (response.data.status === 'success') { showNotify({ type: 'success', message: response.data.message }) // 立即刷新状态 await fetchStatus() } else { throw new Error(response.data.message || '清空失败') } } catch (error) { if (error.toString().includes('cancel')) return showNotify({ type: 'danger', message: error.response?.status === 500 ? '服务器错误,请稍后重试' : `清空失败: ${error.message}` }) } } // 组件挂载时获取一次状态 onMounted(() => { fetchStatus() }) // 组件卸载时清除定时器 onUnmounted(() => { if (statusInterval) { clearInterval(statusInterval) } }) </script> <style scoped> .animate-pulse { animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .7; } } </style>
294coder/Efficient-MIF
5,702
Pansharpening_Hyper_SR_Matlab_Test_Package/BDSD/C_BDSD.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % C_BDSD fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images % through the Clustered Band-Dependent Spatial-Detail (C-BDSD) algorithm. % % Interface: % I_Fus_C_BDSD = C_BDSD(I_MS,I_PAN,ratio,sensor,K) % % Inputs: % I_MS: MS image upsampled at PAN scale; % I_PAN: PAN image; % ratio: Scale ratio between MS and PAN. Pre-condition: Integer value; % sensor: String for type of sensor (e.g. 'WV2', 'IKONOS'). % K: Number of clusters (K>1) (Optional: default value K=30); % % Outputs: % I_Fus_C_BDSD: C_BDSD pansharpened image. % % Reference: % [Garzelli15] A. Garzelli, Pansharpening of Multispectral Images Based on Nonlocal Parameter Optimization, % IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 4, pp. 2096-2107, April 2015. % [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods", % IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_Fus_C_BDSD = C_BDSD(I_MS,I_PAN,ratio,sensor,K) %%% % Control of input parameters and initialization %%% [N,M,Nb] = size(I_MS); if nargin == 5 if K < 2 fprintf(1,'Required number of clusters K>1.\n\n'); return end end if nargin < 5 K = 30; end if nargin < 4 fprintf(1,'\nI_Fus_C_BDSD = C_BDSD(I_MS,I_PAN,ratio,sensor,K)\n\n'); error('At least four input arguments required') end I_MS = double(I_MS); I_PAN = double(I_PAN); %%% % Reduced resolution %%% pan_LP = MTF_PAN(I_PAN,sensor,ratio); pan_LP_d = pan_LP(3:ratio:end,3:ratio:end); ms_orig = imresize(I_MS,1/ratio); ms_LP_d = MTF(ms_orig,sensor,ratio); % CLUSTER MAPS AT FULL RESOLUTION AND REDUCED RESOLUTION % Sa = stdfilt(I_PAN,ones(51)); Sa = Sa/max(Sa(:)); Sb = I_PAN; Sb = Sb/max(Sb(:)); opts = statset('TolX',1e-5); features = zeros(N/ratio,M/ratio,2,ratio*ratio); for i = 1:ratio for j = 1:ratio features(:,:,1,(i-1)*ratio+j) = Sa(1+(i-1):ratio:end,1+(j-1):ratio:end); features(:,:,2,(i-1)*ratio+j) = Sb(1+(i-1):ratio:end,1+(j-1):ratio:end); end end C_stack = zeros(N/ratio,M/ratio,ratio*ratio); f = features(:,:,:,(3-1)*ratio+3); warning off [aux, centers] = kmeans(reshape(f,[N/ratio*M/ratio,2]),K,'replicates',2,'start','cluster','options',opts); C = reshape(aux,[N/ratio M/ratio]); C_stack(:,:,(3-1)*ratio+3) = C; for i = 1:ratio for j = 1:ratio if(i*j~=9) f = features(:,:,:,(i-1)*ratio+j); aux = kmeans(reshape(f,[N/ratio*M/ratio,2]),K,'start',centers,'MaxIter',1); C_stack(:,:,(i-1)*ratio+j) = reshape(aux,[N/ratio M/ratio]); end end end C4 = zeros(size(I_PAN)); for i = 1:ratio for j = 1:ratio C4(i:ratio:end,j:ratio:end) = C_stack(:,:,(i-1)*ratio+j); end end % ESTIMATE PARAMETERS AT REDUCED RESOLUTION AND INJECT (CLUSTER BY CLUSTER) % g = zeros(K,Nb); alpha = zeros(Nb,Nb,K); offset = zeros(Nb,K); ms_ps_stack = zeros(N,M,Nb,K); % Estimate for K=1 [~,g_global,alpha_global,offset_global] = parm_est(ms_LP_d(:,:,:),pan_LP_d,ms_orig,find(C>0)); for j=1:K [~,g(j,:),alpha(:,:,j),offset(:,j)] = parm_est(ms_LP_d(:,:,:),pan_LP_d,ms_orig,find(C==j)); if(size(find(g<0)>0)) g(j,:) = g_global; alpha(:,:,j) = alpha_global; offset(:,j) = offset_global; end H = H_comp(I_PAN,I_MS,find(C4==j)); ms_ps_stack(:,:,:,j) = bdsd_injection(I_PAN,I_MS,H,g(j,:),squeeze(alpha(:,:,j)),offset(:,j),find(C4==j)); end % FORM PANSHARPENED IMAGE I_Fus_C_BDSD = sum(ms_ps_stack,4); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [gamma,g,alpha,offset] = parm_est(hs_LP_d,pan_LP_d,hs_orig,ind) Nb = size(hs_orig,3); for i=1:Nb % compute Hd Hd = zeros(size(ind,1),Nb+2); gamma = zeros((Nb+2),Nb); for k=1:Nb bfull = hs_LP_d(:,:,k); Hd(:,k) = bfull(ind); end Hd(:,Nb+1) = ones(size(ind)); Hd(:,Nb+2) = pan_LP_d(ind); % estimate gamma for k=1:Nb Z = (Hd'*Hd)\Hd'; bfull = hs_orig(:,:,k); b = bfull(ind); bdfull = hs_LP_d(:,:,k); bd = bdfull(ind); gamma(:,k) = Z *(b(:)-bd(:)); end g = gamma(Nb+2,:); alpha = zeros(Nb); for k = 1:Nb alpha(:,k) = -gamma(1:Nb,k)/gamma(Nb+2,k); end offset = zeros(Nb,1); for k = 1:Nb offset(k) = gamma(Nb+1,k)/gamma(Nb+2,k); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hs_en = bdsd_injection(pan,msexp,H,g,alpha,offset,ind) [N,M,Nb] = size(msexp); Intensity = zeros(length(ind),Nb); for k = 1:Nb Intensity(:,k) = H(:,1:Nb) * alpha(:,k) - offset(k); end pfull = pan; p = pfull(ind); hs_en = zeros(N,M,Nb); for k=1:Nb bfull = msexp(:,:,k); b = bfull(ind); b_en = b(:) + (p - Intensity(:,k)) * g(k); hs_enfull = hs_en(:,:,k); hs_enfull(ind) = b_en; hs_en(:,:,k) = reshape(hs_enfull,N,M); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function H = H_comp(pan,hs,ind) Nb = size(hs,3); H = zeros(length(ind),Nb+2); for k=1:Nb bfull = hs(:,:,k); H(:,k) = bfull(ind); end H(:,Nb+1) = ones(size(ind)); H(:,Nb+2) = pan(ind);
294coder/Efficient-MIF
4,340
Pansharpening_Hyper_SR_Matlab_Test_Package/PRACS/PRACS.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % PRACS fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by % exploiting the Partial Replacement Adaptive CS (PRACS) algorithm. % % Interface: % I_Fus_PRACS = PRACS(I_MS,I_PAN,ratio) % % Inputs: % I_MS: MS image upsampled at PAN scale; % I_PAN: PAN image; % ratio: Scale ratio between MS and PAN. Pre-condition: Integer value. % % Outputs: % I_Fus_PRACS: PRACS pansharpened image. % % References: % [Choi11] J. Choi, K. Yu, and Y. Kim, A new adaptive component-substitution-based satellite image fusion by using partial replacement, IEEE % Transactions on Geoscience and Remote Sensing, vol. 49, no. 1, pp. 295309, January 2011. % [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms, % IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015. % [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods", % IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315. % % % % % % % % % % % % % % % Version: 1 % % % % % % % % % % % % % % % % Copyright (C) 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_Fus_PRACS = PRACS(I_MS,I_PAN,ratio) beta = 0.95; % for 11-bit data % beta = 1.95; % for 8-bit data I_MS = double(I_MS); I_PAN = double(I_PAN); [N,M,L] = size(I_MS); %%% Histogram matching of each MS band to Pan msexp_hm = zeros(N,M,L); for k=1:L b = I_MS(:,:,k); b = (b - mean2(b) + mean2(I_PAN)/std2(I_PAN)*std2(b)) * std2(I_PAN)/std2(b); b(b<0) = 0; msexp_hm(:,:,k) = b; end %%% Computing low-resolution Pan by bicubic decimation/interpolation aux = imresize(I_PAN,1/ratio); pan_l = imresize(aux,ratio); clear aux %%% Regression of Pan_low vs MS (with offset) bb = zeros(N*M,L); for k = 1:L bb(:,k) = reshape(squeeze(msexp_hm(:,:,k)),[N*M,1]); end bb = [ones(N*M,1),bb]; alpha = regress(pan_l(:),bb); %%% Initial estimate of intensity aux = bb * alpha; I_l = reshape(aux,[N,M]); clear aux clear bb %%% Partial Replacement I_h = zeros(N,M,L); cc = zeros(1,L); for k=1:L b = msexp_hm(:,:,k); cc(k) = corr2(I_l(:),b(:)); aux = cc(k)*I_PAN(:)+(1-cc(k))*b(:); I_h(:,:,k) = reshape(aux,[N,M]); end clear aux %%% Band-dependent intensity %%% For each band, compute low-resolution I_h by bicubic decimation/interpolation I_h_low = zeros(N,M,L); for k=1:L aux = imresize(I_h(:,:,k),1/ratio); I_h_low(:,:,k) = imresize(aux,ratio); end clear aux %%% %%% Regression of I_h_low_k vs MS (with offset) alpha = zeros(L+1,L); for k = 1:L bb(:,k) = reshape(squeeze(msexp_hm(:,:,k)),[N*M,1]); end bb = [ones(N*M,1),bb]; for k=1:L aux = I_h_low(:,:,k); alpha(:,k) = regress(aux(:),bb); end clear aux %%% Intensities I_l_prime = zeros(N,M,L); for k=1:L aux = bb * alpha(:,k); I_l_prime(:,:,k) = reshape(aux,[N,M]); end clear aux %%% Computing detail images delta = zeros(N,M,L); for k=1:L delta(:,:,k)= I_h(:,:,k)-I_l_prime(:,:,k)-(mean2(I_h(:,:,k))-mean2(I_l_prime(:,:,k))); end %%% Computing mean of std. devs. aux3 = zeros(1,L); for k=1:L aux3(k) = std2(I_MS(:,:,k)); end aux3 = mean(aux3); %%% Computing weights w = zeros(1,L); for k=1:L aux1 = I_l_prime(:,:,k); b = I_MS(:,:,k); w(k) = beta .* corr2(aux1(:),b(:))*std(b(:))/aux3;%std(aux2(:)); end %%% Computing local instability adjustment parameter L_I = zeros(N,M,L); for k=1:L b = I_MS(:,:,k); I = I_l_prime(:,:,k); aux = 1-abs(1-corr2(I_l(:),b(:))*b(:)./I(:)); L_I(:,:,k) = reshape(aux,[N,M]); end %%% Computing pansharpened image det = zeros(N,M,L); I_Fus_PRACS = zeros(N,M,L); for k=1:L det(:,:,k) = w(k) * L_I(:,:,k) .* delta(:,:,k); I_Fus_PRACS(:,:,k) = I_MS(:,:,k) + det(:,:,k); end end
2881099/FreeSql.AdminLTE
1,644
Examples/net80_blazor/Admin/AdminExtensions.cs
using FreeSql; using Microsoft.AspNetCore.Components; using Microsoft.JSInterop; using System.Web; public static class AdminExtensions { public static string GetQueryStringValue(this NavigationManager nav, string name) { var obj = HttpUtility.ParseQueryString(new Uri(nav.Uri).Query); return obj[name] ?? ""; } public static string[] GetQueryStringValues(this NavigationManager nav, string name) { var obj = HttpUtility.ParseQueryString(new Uri(nav.Uri).Query); return obj.GetValues(name) ?? new string[0]; } public static void CopyTo<T>(this IFreeSql fsql, T from ,T to) { foreach (var col in fsql.CodeFirst.GetTableByEntity(typeof(T)).ColumnsByPosition) col.SetValue(to, col.GetValue(from)); } record ConfirmResult(bool isConfirmed); async public static Task<bool> Confirm(this IJSRuntime JS, string title, string text = "") { var jsr = await JS.InvokeAsync<ConfirmResult>("Swal.fire", new { title = title, text = text, icon = "warning", showCancelButton = true, confirmButtonColor = "#3085d6", cancelButtonColor = "#d33", confirmButtonText = "确定", cancelButtonText = "取消" }); return jsr.isConfirmed; } async public static Task Success(this IJSRuntime JS, string title) { await JS.InvokeVoidAsync("Swal.fire", new { //position = "top-end", title = title, icon = "success", showConfirmButton = false, timer = 1500 }); } }
2977094657/BiliHistoryFrontend
10,938
src/components/tailwind/page/Comments.vue
<template> <div> <!-- 致谢 --> <div class="mb-4"> <div class="bg-[#fb7299]/5 border border-[#fb7299]/20 px-3 py-0 rounded-md w-full flex items-center justify-center h-9"> <img src="https://www.aicu.cc/favicon.ico" alt="AICU" class="w-3 h-3 mr-1.5" /> <div class="flex items-center"> <span class="text-xs text-gray-700"> 感谢 <a href="https://www.aicu.cc/" target="_blank" class="text-[#fb7299] hover:text-[#fb7299]/80 font-medium">aicu.cc</a> 开放API </span> <span class="mx-1.5 text-gray-300">|</span> <div class="flex items-center text-xs text-gray-500"> <svg class="w-3 h-3 text-[#fb7299] mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /> </svg> <span>非官方API,数据不是实时更新</span> <a href="https://www.aicu.cc/help.html?id=11" target="_blank" class="text-[#fb7299] hover:text-[#fb7299]/80 ml-1 font-medium"> 了解更多 </a> </div> </div> </div> </div> <!-- 搜索和筛选 --> <div class="mb-6 bg-transparent"> <div class="mb-4"> <!-- 总评论数显示 --> <div class="mb-3 flex items-center text-sm text-gray-600"> <span>共</span> <span class="mx-1 text-[#fb7299] font-medium">{{ total }}</span> <span>条评论</span> </div> <div class="flex flex-nowrap items-center space-x-2"> <!-- 关键词搜索 - 改为与首页一致的样式 --> <div class="flex-1 min-w-0"> <SimpleSearchBar v-model="keyword" placeholder="搜索评论内容..." @search="handleSearch" class="w-full" /> </div> <!-- 评论类型筛选 --> <div class="w-24 flex-shrink-0"> <CustomDropdown v-model="commentType" :options="commentTypeOptions" :selected-text="getCommentTypeText(commentType)" @change="selectCommentType" :min-width="80" :use-fixed-width="true" custom-class="h-9" /> </div> <!-- 内容类型筛选 --> <div class="w-24 flex-shrink-0"> <CustomDropdown v-model="typeFilter" :options="contentTypeOptions" :selected-text="getContentTypeText(typeFilter)" @change="selectContentType" :min-width="80" :use-fixed-width="true" custom-class="h-9" /> </div> </div> </div> </div> <!-- 评论列表 --> <div class="bg-white rounded-lg border border-gray-200 overflow-hidden"> <!-- 评论项 --> <div v-if="!loading && comments.length > 0" class="divide-y divide-gray-100"> <div v-for="comment in comments" :key="comment.rpid" class="p-4 md:p-6"> <div class="space-y-2"> <!-- 评论内容 --> <p class="text-gray-800 text-sm md:text-base whitespace-pre-wrap leading-relaxed">{{ comment.message }}</p> <!-- 评论元数据 --> <div class="flex items-center justify-between text-xs text-gray-500"> <div class="flex items-center space-x-3"> <span :class="comment.type === 1 ? 'text-[#fb7299]' : 'text-[#fb7299]'"> {{ getCommentType(comment.type) }} </span> <span>{{ comment.time_str }}</span> </div> <a :href="getCommentLink(comment)" target="_blank" class="text-[#fb7299] hover:text-[#fb7299]/80 transition-colors" > 查看原文 → </a> </div> </div> </div> </div> <!-- 加载状态 --> <div v-if="loading" class="flex justify-center items-center py-16"> <div class="flex flex-col items-center"> <div class="animate-spin h-8 w-8 border-3 border-[#fb7299] border-t-transparent rounded-full"></div> <p class="text-gray-500 text-sm mt-4">加载评论中...</p> </div> </div> <!-- 空状态 --> <div v-if="!loading && comments.length === 0" class="flex justify-center items-center py-16"> <div class="flex flex-col items-center"> <div class="bg-[#fb7299]/5 rounded-full p-3 mb-3"> <svg class="w-8 h-8 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" /> </svg> </div> <p class="text-gray-600 font-medium">暂无评论数据</p> <p v-if="hasActiveFilters" class="text-gray-500 text-sm mt-1 text-center max-w-sm"> 尝试调整搜索条件 </p> <button v-if="hasActiveFilters" @click="clearFilters" class="mt-4 px-4 py-2 text-white bg-[#fb7299] hover:bg-[#fb7299]/90 rounded-md text-sm transition-colors" > 清除筛选 </button> </div> </div> </div> <!-- 分页控件 --> <div v-if="totalPages > 0" class="mt-6 flex justify-center"> <Pagination :current-page="currentPage" :total-pages="totalPages" @page-change="handlePageChange" /> </div> </div> </template> <script setup> import { ref, onMounted, watch, computed, onUnmounted } from 'vue' import { getComments, getLoginStatus } from '../../../api/api' import { showNotify } from 'vant' import { useRouter } from 'vue-router' import Pagination from '../Pagination.vue' import 'vant/es/notify/style' import SimpleSearchBar from '../SimpleSearchBar.vue' import CustomDropdown from '../CustomDropdown.vue' const router = useRouter() const comments = ref([]) const loading = ref(false) const currentPage = ref(1) const pageSize = ref(20) const total = ref(0) const totalPages = ref(0) const userInfo = ref(null) const keyword = ref('') const commentType = ref('all') const typeFilter = ref('0') // 获取用户信息 const getUserInfo = async () => { try { const response = await getLoginStatus() // 新的API响应格式是 {code: 0, message: "0", ttl: 1, data: {...}} // code为0表示请求成功 if (response.data && response.data.code === 0) { const userData = response.data.data if (userData.isLogin) { userInfo.value = userData return true } } // 如果未登录,显示提示 showNotify({ type: 'warning', message: '请先登录后查看评论' }) router.push('/') return false } catch (error) { console.error('获取用户信息失败:', error) showNotify({ type: 'danger', message: '获取用户信息失败' }) return false } } // 下拉菜单选项数据 const commentTypeOptions = [ { value: 'all', label: '全部' }, { value: 'root', label: '一级' }, { value: 'reply', label: '二级' } ] const contentTypeOptions = [ { value: '0', label: '全部' }, { value: '1', label: '视频' }, { value: '17', label: '动态' }, { value: '11', label: '旧动态' } ] // 计算下拉菜单按钮宽度 - 响应式设计 const windowWidth = ref(window.innerWidth) computed(() => { // 检测是否为移动设备 const isMobile = windowWidth.value < 768 return isMobile ? '100%' : 100 }) // 处理窗口大小变化 const handleWindowResize = () => { windowWidth.value = window.innerWidth } // 处理页码变化 const handlePageChange = (newPage) => { currentPage.value = newPage } // 获取评论列表 const fetchComments = async () => { if (!userInfo.value?.mid) { const hasUser = await getUserInfo() if (!hasUser) return } loading.value = true try { const response = await getComments( userInfo.value.mid, currentPage.value, pageSize.value, commentType.value, keyword.value, typeFilter.value ) if (response.data) { comments.value = response.data.comments total.value = response.data.total totalPages.value = response.data.total_pages } } catch (error) { console.error('获取评论列表失败:', error) showNotify({ type: 'danger', message: '获取评论列表失败' }) } finally { loading.value = false } } // 获取评论类型显示文本 const getCommentType = (type) => { switch (type) { case 1: return '视频评论' case 11: case 17: return '动态评论' default: return '其他评论' } } // 获取评论链接 const getCommentLink = (comment) => { const { type, oid, rpid } = comment switch (type) { case 1: // 视频评论 return `https://www.bilibili.com/video/av${oid}#reply${rpid}` case 11: // 动态评论类型11 return `https://t.bilibili.com/${oid}?type=2#reply${rpid}` case 17: // 动态评论类型17 return `https://t.bilibili.com/${oid}#reply${rpid}` default: return '#' } } // 监听分页变化 watch(currentPage, () => { fetchComments() }) // 监听筛选条件变化 watch([commentType, typeFilter], () => { currentPage.value = 1 fetchComments() }) // 在组件挂载时添加事件监听器和获取数据 onMounted(async () => { window.addEventListener('resize', handleWindowResize) const hasUser = await getUserInfo() if (hasUser) { fetchComments() } }) // 在组件卸载时移除事件监听器 onUnmounted(() => { window.removeEventListener('resize', handleWindowResize) }) // 处理搜索 const handleSearch = () => { if (keyword.value.trim() || hasActiveFilters.value) { currentPage.value = 1 fetchComments() } } // 获取评论类型文本 const getCommentTypeText = (type) => { switch (type) { case 'root': return '一级' case 'reply': return '二级' default: return '全部' } } // 获取内容类型文本 const getContentTypeText = (type) => { switch (type) { case '1': return '视频' case '17': return '动态' case '11': return '旧动态' case '0': default: return '全部' } } // 清除筛选条件 const clearFilters = () => { keyword.value = '' commentType.value = 'all' typeFilter.value = '0' currentPage.value = 1 fetchComments() } // 判断是否有活动筛选条件 const hasActiveFilters = computed(() => { return keyword.value || commentType.value !== 'all' || typeFilter.value !== '0' }) // 选择评论类型 const selectCommentType = (value) => { commentType.value = value handleSearch() } // 选择内容类型 const selectContentType = (value) => { typeFilter.value = value handleSearch() } </script> <style> /* 这里可以添加任何需要的自定义样式 */ </style>
2977094657/BiliHistoryFrontend
2,466
src/components/tailwind/layout/MainLayout.vue
<template> <Sidebar @change-content="currentContent = $event" v-model:showRemarks="showRemarks"> <!-- 主要内容区域 --> <div class="h-screen overflow-y-auto"> <router-view></router-view> </div> </Sidebar> <!-- 数据同步管理模态框 - 全局层级 --> <DataSyncManager v-model:showModal="showDataSyncModal" :initialTab="currentSyncTab" @sync-complete="handleSyncComplete" @check-complete="handleCheckComplete" /> </template> <script setup> import { ref, watch, onMounted, onUnmounted } from 'vue' import { useRoute } from 'vue-router' import Sidebar from '../Sidebar.vue' import DataSyncManager from '../DataSyncManager.vue' const route = useRoute() // 当前显示的内容 const currentContent = ref('history') const showRemarks = ref(false) // 数据同步弹窗状态 const showDataSyncModal = ref(false) const currentSyncTab = ref('integrity') // 监听路由变化 watch( () => route.path, (path) => { if (path === '/settings') { currentContent.value = 'settings' showRemarks.value = false } else if (path === '/media') { currentContent.value = 'media' // 如果是通过备注路由重定向过来的,需要显示备注 if (route.query.tab === 'remarks') { showRemarks.value = true } else { showRemarks.value = false } } else if (path === '/' || path.startsWith('/page/')) { currentContent.value = 'history' showRemarks.value = false } else if (path === '/analytics') { currentContent.value = 'analytics' showRemarks.value = false } else if (path === '/images') { currentContent.value = 'images' showRemarks.value = false } else if (path === '/scheduler') { currentContent.value = 'scheduler' showRemarks.value = false } else if (path === '/video-downloader') { currentContent.value = 'video-downloader' showRemarks.value = false } }, { immediate: true } ) // 处理同步完成事件 const handleSyncComplete = (result) => { console.log('同步完成:', result) } // 处理检查完成事件 const handleCheckComplete = (result) => { console.log('完整性检查完成:', result) } // 监听自定义全局事件 onMounted(() => { window.addEventListener('open-data-sync-manager', handleOpenDataSyncManager) }) onUnmounted(() => { window.removeEventListener('open-data-sync-manager', handleOpenDataSyncManager) }) // 处理打开数据同步管理器事件 const handleOpenDataSyncManager = (event) => { if (event.detail && event.detail.tab) { currentSyncTab.value = event.detail.tab } showDataSyncModal.value = true } </script>
2977094657/BiliHistoryFrontend
7,748
src/components/tailwind/scheduler/TaskHistory.vue
<template> <van-dialog :show="show" @update:show="$emit('update:show', $event)" title="任务执行历史" width="80%" :show-confirm-button="false" class="task-history-dialog" > <template #title> <div class="flex items-center justify-between px-3"> <span>任务执行历史</span> <button @click="$emit('update:show', false)" class="p-1 hover:bg-gray-100 rounded-lg transition-colors" > <svg class="w-4 h-4 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /> </svg> </button> </div> </template> <div class="p-3"> <div class="flex items-center justify-between mb-3"> <div class="flex items-center"> <div class="p-1.5 bg-[#fb7299]/10 rounded-lg mr-2"> <svg class="w-4 h-4 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> </div> <div> <h3 class="text-base font-medium text-gray-800">{{ taskName }}</h3> <p class="text-xs text-gray-500">ID: {{ taskId }}</p> </div> </div> <div> <button @click="refreshHistory" class="inline-flex items-center px-2 py-1 border border-transparent rounded-md text-xs font-medium text-white bg-[#fb7299] hover:bg-[#fb7299]/90 focus:outline-none" > <svg class="w-3.5 h-3.5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /> </svg> 刷新 </button> </div> </div> <div v-if="loading" class="flex justify-center items-center py-8"> <van-loading type="spinner" color="#fb7299" /> </div> <div v-else-if="!history.length" class="text-center py-8 text-gray-500"> 暂无执行历史 </div> <div v-else class="space-y-2"> <div v-for="record in history" :key="record.execution_id" class="bg-white rounded-lg p-3 border border-gray-200"> <div class="flex items-center justify-between"> <div class="flex items-center space-x-2"> <span :class="{ 'bg-green-50 text-green-700 border-green-200': record.status === 'success', 'bg-yellow-50 text-yellow-700 border-yellow-200': record.status === 'running', 'bg-red-50 text-red-700 border-red-200': record.status === 'error' }" class="px-1.5 py-0.5 text-xs font-medium rounded-md border" > {{ statusLabel(record.status) }} </span> <span class="text-sm text-gray-600">{{ record.start_time?.replace('T', ' ') }}</span> </div> <div class="text-sm text-gray-500"> 耗时: {{ record.duration?.toFixed(2) || 0 }}秒 </div> </div> <div v-if="record.error" class="mt-2"> <button @click="viewError(record)" class="text-xs text-red-600 hover:text-red-800" > 查看错误详情 </button> </div> </div> </div> <!-- 分页器 --> <div v-if="total > pageSize" class="mt-4 flex justify-center"> <van-pagination v-model="currentPage" :total-items="total" :items-per-page="pageSize" :show-page-size="3" force-ellipses @change="handlePageChange" /> </div> </div> <!-- 错误详情弹窗 --> <van-dialog v-model:show="showErrorDialog" title="错误详情" width="80%" :show-confirm-button="false" class="task-history-dialog" > <template #title> <div class="flex items-center justify-between px-3"> <span>错误详情</span> <button @click="showErrorDialog = false" class="p-1 hover:bg-gray-100 rounded-lg transition-colors" > <svg class="w-4 h-4 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /> </svg> </button> </div> </template> <div v-if="selectedRecord" class="p-3"> <div class="bg-red-50 p-2 rounded-md"> <pre class="text-xs font-mono text-red-800 whitespace-pre-wrap overflow-x-auto">{{ selectedRecord.error }}</pre> </div> </div> </van-dialog> </van-dialog> </template> <script setup> import { ref, onMounted, watch } from 'vue' import { showNotify } from 'vant' import 'vant/es/dialog/style' import 'vant/es/notify/style' import 'vant/es/loading/style' import 'vant/es/pagination/style' import 'vant/es/date-picker/style' import { getTaskHistory } from '../../../api/api' const props = defineProps({ show: { type: Boolean, default: false }, taskId: { type: String, default: '' }, taskName: { type: String, default: '' } }) const emit = defineEmits(['update:show']) const loading = ref(false) const history = ref([]) const showErrorDialog = ref(false) const selectedRecord = ref(null) // 分页相关 const currentPage = ref(1) const pageSize = ref(20) const total = ref(0) // 获取任务历史记录 const fetchHistory = async () => { if (!props.taskId) return loading.value = true try { const response = await getTaskHistory({ task_id: props.taskId, include_subtasks: false, page: currentPage.value, page_size: pageSize.value }) if (response.data && response.data.status === 'success') { history.value = response.data.history || [] total.value = response.data.total || 0 } else { showNotify({ type: 'danger', message: '获取历史记录失败: ' + (response.data?.message || '未知错误') }) } } catch (error) { showNotify({ type: 'danger', message: '获取历史记录出错: ' + (error.message || '未知错误') }) } finally { loading.value = false } } // 处理页码变化 const handlePageChange = (page) => { currentPage.value = page fetchHistory() } // 刷新历史记录 const refreshHistory = () => { fetchHistory() } // 查看错误详情 const viewError = (record) => { selectedRecord.value = record showErrorDialog.value = true } // 状态标签 const statusLabel = (status) => { switch (status) { case 'success': return '成功' case 'error': return '失败' case 'running': return '执行中' case 'pending': return '等待中' default: return status } } // 监听任务ID变化,自动获取历史记录 onMounted(() => { if (props.show && props.taskId) { fetchHistory() } }) // 监听show变化,自动获取历史记录 watch(() => props.show, (newVal) => { if (newVal && props.taskId) { fetchHistory() } }) </script> <script> export default { name: 'TaskHistory' } </script> <style scoped> .task-history-dialog :deep(.van-dialog) { max-height: 85vh; overflow: hidden; display: flex; flex-direction: column; margin-top: -10vh !important; } .task-history-dialog :deep(.van-dialog__header) { flex-shrink: 0; padding: 12px 16px; font-size: 14px; } .result-dialog :deep(.van-dialog) { max-height: 75vh; overflow: hidden; display: flex; flex-direction: column; margin-top: -5vh !important; } .result-dialog :deep(.van-dialog__header) { flex-shrink: 0; padding: 10px 14px; font-size: 13px; } </style>
298582245/wqwl_qinglong
13,084
wqwl_爱裹旧衣回收.js
/** * 脚本:wqwl_爱裹旧衣回收.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序爱裹旧衣回收 * 环境变量:wqwl_aiguo,多个换行或新建多个变量 * 环境变量描述:抓包Headers下的authorization,格式例如:authorization#备注1(authorization去掉Bearer ) * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 3 * * * 一天一次 */ /** * 积分不能全抵,我签到七天只得0.03,想玩就玩吧,ck不知道多久过期,自己登录好像会顶ck */ const axios = require('axios'); const fs = require('fs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || false; //并发数,默认4 let bfs = process.env["wqwl_bfs"] || 4; // 是否通知 let isNotify = true; //是否抽奖 let isDraw = true; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_aiguo'; //脚本名称 const name = '微信小程序爱裹旧衣回收' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } // let fileData = wqwlkj.readFile('aiguo') class Task { constructor(ck) { this.index = index++; this.ck = ck this.baseUrl = 'https://alipay.haliaeetus.cn/fuli' this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) } async init() { const ckData = this.ck.split('#') if (ckData.length < 1) { return this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 1) { this.remark = ckData[0].slice(0, 8); } else { this.remark = ckData[1]; } this.token = ckData[0]; this.headers = { "accept": "*/*", "accept-language": "zh-CN,zh;q=0.9", "authorization": this.token, "channelno": "", "content-type": "application/json", "plateform": "WX", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "xweb_xhr": "1", "Referer": "https://servicewechat.com/wx4ff260333d3c5ddd/245/page-frame.html", "Referrer-Policy": "unsafe-url" } if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } return true } async signed() { try { const options = { url: `${this.baseUrl}/api/fuli/signed`, headers: this.headers, method: 'GET' } const res = await this.request(options, 0); if (res.status === 200) this.sendMessage(`✅签到成功`) else this.sendMessage(`❌签到失败,原因:${res.msg}`) } catch (e) { throw new Error(`❌签到请求失败,${e.message}`) } } async account() { try { const options = { url: `${this.baseUrl}/api/jf/account`, headers: this.headers, method: 'POST', data: {} } const res = await this.request(options, 0); if (res.status === 200) { this.sendMessage(`✅当前积分为:${res.data}`) return res.data } else this.sendMessage(`❌查询失败,原因:${res.msg}`) return 0 } catch (e) { throw new Error(`❌查询请求失败,${e.message}`) } } //currentTime async currentTime() { try { const options = { url: `${this.baseUrl}/currentTime`, headers: this.headers, method: 'GET', } const res = await this.request(options, 0); //1756117235827 if ((typeof res === 'number' && res.toString().length === 13) || (typeof res === 'string' && res.length === 13)) { return res } else { this.sendMessage(`❌获取时间失败,服务器返回: ${JSON.stringify(res)}`) } } catch (e) { throw new Error(`❌获取时间请求失败,${e.message}`) } } // async wheelDraw() { try { const options = { url: `${this.baseUrl}/api/fuli/wheel/wheelDraw`, headers: this.headers, method: 'POST', data: JSON.stringify({ data: "" }), } const res = await this.request(options, 0); if (res.status === 200) { if (res.data.type === 0) this.sendMessage(`✅抽奖成功,获得奖品:${res.data.name}`) else this.sendMessage(`✅抽奖成功,获得奖品:${res.data.name}`, true) } else { this.sendMessage(`❌抽奖失败,原因:${res.msg}`) } } catch (e) { throw new Error(`❌抽奖请求失败,${e.message}`) } } async doTask(task) { try { let data = { data: { status: task.status, type: task.type, taskNo: task.taskNo, }, m: await this.currentTime(), } data.s = this.sign(data.m + JSON.stringify(data.data)) // console.log(data) const options = { url: `${this.baseUrl}/api/earnPoint/doTask`, headers: this.headers, method: 'POST', data: data } const res = await this.request(options, 0); // console.log(res) if (res.status === 200 || res.msg === '您已领取该任务') { this.sendMessage(`✅【${task.taskName}】任务${task.status === 1 ? '完成' : '领取'}成功`) return true } else { this.sendMessage(`❌【${task.taskName}】任务失败,原因:${res.msg}`) return false } } catch (e) { throw new Error(`❌任务请求失败,${e.message}`) } } async startTask() { const taskList = [ { taskName: '衣服预约', taskNo: '1000', type: 1 }, { taskName: '旧书预约', taskNo: '1001', type: 1 }, { taskName: '参与天天抽奖', taskNo: '1008', type: 1 }, ] for (let task of taskList) { task.status = 0 const isStart = await this.doTask(task) await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) if (!isStart) continue; task.status = 1 await this.doTask(task) await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) } } sign(t) { t = t.split("").sort().join("").replace(/^\s*|\s*$/g, "") return wqwlkj.md5(t) } async main() { const isFinish = await this.init() if (!isFinish) return await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.signed() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.startTask() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) const jf = await this.account() if (!isDraw) return for (let i = 0; i < Math.floor(jf / 10); i++) { this.sendMessage(`📝第${i + 1}次抽奖...`) await this.wheelDraw() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) } await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.account() } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); return data; } catch (error) { this.sendMessage(`🔐检测到请求发生错误,正在重试...`) // 刷新代理 const newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } // wqwlkj.saveFile(fileData, 'aiguo') console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
2977094657/BiliHistoryFrontend
13,933
src/components/tailwind/scheduler/TaskDetail.vue
<template> <van-dialog :show="show" @update:show="$emit('update:show', $event)" title="任务详情" width="60%" :show-confirm-button="false" class="task-detail-dialog" > <template #title> <div class="flex items-center justify-between px-3"> <span>任务详情</span> <div class="flex items-center space-x-2"> <button @click="$emit('view-history', task.task_id)" class="inline-flex items-center px-2 py-1 text-xs font-medium text-white bg-[#fb7299] hover:bg-[#fb7299]/90 focus:outline-none rounded-md" > <svg class="w-3.5 h-3.5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> 查看历史 </button> <button @click="$emit('update:show', false)" class="p-1 hover:bg-gray-100 rounded-lg transition-colors" > <svg class="w-4 h-4 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /> </svg> </button> </div> </div> </template> <div v-if="task" class="p-3"> <!-- 任务标题和状态栏 --> <div class="flex items-center justify-between mb-3 pb-2 border-b border-gray-100"> <div class="flex items-center"> <div class="p-1.5 bg-[#fb7299]/10 rounded-lg mr-2"> <svg class="w-4 h-4 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> </div> <div> <div class="flex items-center space-x-1"> <h3 class="text-base font-medium text-gray-800 truncate" :title="task.config?.name">{{ task.config?.name }}</h3> </div> <p class="text-xs text-gray-500">ID: {{ task.task_id }}</p> </div> </div> <div class="flex flex-col items-end"> <div class="flex items-center space-x-1 mb-1"> <span v-if="task.execution?.status" :class="{ 'bg-green-50 text-green-700 border-green-200': task.execution.status === 'success', 'bg-yellow-50 text-yellow-700 border-yellow-200': task.execution.status === 'running', 'bg-red-50 text-red-700 border-red-200': task.execution.status === 'error' }" class="px-1.5 py-0.5 text-xs font-medium rounded-md border" > {{ statusLabel }} </span> <span v-if="task.config?.enabled !== undefined" :class="{'bg-green-50 text-green-700 border-green-200': task.config.enabled, 'bg-red-50 text-red-700 border-red-200': !task.config.enabled}" class="px-1.5 py-0.5 text-xs font-medium rounded-md border" > {{ task.config.enabled ? '已启用' : '已禁用' }} </span> </div> </div> </div> <!-- 任务详情内容 --> <div class="space-y-3"> <!-- 基本信息 --> <div class="bg-white rounded-lg p-2 border border-gray-200"> <h4 class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-1.5 flex items-center"> <svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> 基本信息 </h4> <div class="grid grid-cols-2 gap-2"> <div> <p class="text-xs text-gray-500">API端点</p> <p class="text-sm text-gray-800 font-mono">{{ task.config?.endpoint }}</p> </div> <div> <p class="text-xs text-gray-500">请求方法</p> <p class="text-sm text-gray-800">{{ task.config?.method }}</p> </div> <div> <p class="text-xs text-gray-500">优先级</p> <p class="text-sm text-gray-800">{{ task.config?.priority || 0 }}</p> </div> <div> <p class="text-xs text-gray-500">最后修改</p> <p class="text-sm text-gray-800">{{ task.last_modified?.replace('T', ' ') }}</p> </div> </div> </div> <!-- 调度信息 --> <div class="bg-white rounded-lg p-2 border border-gray-200"> <h4 class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-1.5 flex items-center"> <svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> 调度信息 </h4> <div class="grid grid-cols-2 gap-2"> <div> <p class="text-xs text-gray-500">调度类型</p> <p class="text-sm text-gray-800">{{ scheduleTypeLabel }}</p> </div> <div> <p class="text-xs text-gray-500">执行时间</p> <p class="text-sm text-gray-800"> <template v-if="task.task_type === 'main'"> <template v-if="task.config?.schedule_type === 'interval'"> {{ task.config?.interval_value || '-' }} {{ task.config?.interval_unit === 'minutes' ? '分钟' : task.config?.interval_unit === 'hours' ? '小时' : task.config?.interval_unit === 'days' ? '天' : task.config?.interval_unit === 'months' ? '月' : task.config?.interval_unit === 'years' ? '年' : task.config?.interval_unit || '' }} </template> <template v-else> {{ task.config?.schedule_time || '未设置' }} </template> </template> <template v-else> 依赖于主任务 </template> </p> </div> <div> <p class="text-xs text-gray-500">上次执行</p> <p class="text-sm text-gray-800">{{ task.execution?.last_run?.replace('T', ' ') || '从未执行' }}</p> </div> <div> <p class="text-xs text-gray-500">下次执行</p> <p class="text-sm text-gray-800"> <template v-if="task.task_type === 'main'"> {{ task.execution?.next_run || '未排定' }} </template> <template v-else> 依赖于主任务 </template> </p> </div> </div> </div> <!-- 执行统计 --> <div class="bg-white rounded-lg p-2 border border-gray-200"> <h4 class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-1.5 flex items-center"> <svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /> </svg> 执行统计 </h4> <div class="grid grid-cols-2 gap-2"> <div> <div class="flex justify-between items-center mb-1"> <span class="text-xs text-gray-500">成功率</span> <span class="text-xs text-gray-800"> {{ Math.round(executionInfo.successRate) }}% </span> </div> <div class="h-1.5 w-full bg-gray-100 rounded-full overflow-hidden"> <div class="h-full rounded-full" :class="{ 'bg-green-500': executionInfo.successRate >= 90, 'bg-yellow-500': executionInfo.successRate >= 60 && executionInfo.successRate < 90, 'bg-red-500': executionInfo.successRate < 60 }" :style="{width: `${executionInfo.successRate}%`}"> </div> </div> </div> <div> <p class="text-xs text-gray-500">平均耗时</p> <p class="text-sm text-gray-800"> {{ executionInfo.avgDuration.toFixed(2) }}秒 </p> </div> <div> <p class="text-xs text-gray-500">总执行次数</p> <p class="text-sm text-gray-800"> {{ executionInfo.totalRuns }} </p> </div> <div> <p class="text-xs text-gray-500">成功/失败</p> <p class="text-sm"> <span class="text-green-600">{{ executionInfo.successRuns }}</span> <span class="text-gray-400 mx-1">/</span> <span class="text-red-600">{{ executionInfo.failRuns }}</span> </p> </div> </div> </div> <!-- 依赖任务 --> <div class="bg-white rounded-lg p-2 border border-gray-200"> <h4 class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-1.5 flex items-center"> <svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" /> </svg> 依赖任务 </h4> <div v-if="task.depends_on" class="flex flex-wrap gap-0.5"> <span class="inline-flex items-center px-1.5 py-0.5 rounded-md text-xs font-medium bg-blue-50 text-blue-700 border border-blue-200" :title="task.depends_on.name" > {{ task.depends_on.name }} ({{ task.depends_on.task_id }}) </span> </div> <p v-else class="text-xs text-gray-500">无依赖</p> </div> <!-- 最近错误 --> <div v-if="task.execution?.last_error" class="bg-white rounded-lg p-2 border border-red-100 shadow-sm"> <h4 class="text-xs font-semibold text-red-600 uppercase tracking-wider mb-1.5 flex items-center"> <svg class="w-3 h-3 mr-1 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> 最近错误 </h4> <p class="text-xs text-red-600 whitespace-pre-wrap">{{ task.execution.last_error }}</p> </div> </div> </div> </van-dialog> </template> <script setup> import { computed, watch } from 'vue' import { showNotify, showDialog } from 'vant' import 'vant/es/dialog/style' import 'vant/es/notify/style' const props = defineProps({ show: { type: Boolean, default: false }, task: { type: Object, default: null } }) const emit = defineEmits([ 'update:show', 'view-history', 'edit-task', 'execute-task', 'toggle-enabled', 'delete-task' ]) // 添加 watch 来监控 task 属性的变化 watch(() => props.task, (newTask) => { if (!newTask) { return } }, { deep: true, immediate: true }) // 添加计算属性来处理执行信息 const executionInfo = computed(() => { const execution = props.task?.execution || {} // 确保所有数值类型的字段都有默认值 const info = { lastRun: execution.last_run ?? null, nextRun: execution.next_run ?? null, status: execution.status ?? 'pending', successRate: typeof execution.success_rate === 'number' ? execution.success_rate : 0, avgDuration: typeof execution.avg_duration === 'number' ? execution.avg_duration : 0, totalRuns: typeof execution.total_runs === 'number' ? execution.total_runs : 0, successRuns: typeof execution.success_runs === 'number' ? execution.success_runs : 0, failRuns: typeof execution.fail_runs === 'number' ? execution.fail_runs : 0 } return info }) // 计算调度类型标签 const scheduleTypeLabel = computed(() => { const type = props.task?.config?.schedule_type return type === 'daily' ? '每日' : type === 'chain' ? '链式任务' : type === 'once' ? '一次性' : type === 'interval' ? '间隔执行' : type }) // 计算状态标签 const statusLabel = computed(() => { const status = props.task?.execution?.status return status === 'success' ? '成功' : status === 'running' ? '执行中' : status === 'error' ? '失败' : status === 'pending' ? '等待中' : status }) // 确认删除 const confirmDelete = () => { showDialog({ title: '确认删除', message: `确定要删除任务 "${props.task.config?.name}" 吗?此操作不可撤销。`, showCancelButton: true, confirmButtonText: '删除', confirmButtonColor: '#ee0a24', }).then(() => { emit('delete-task', props.task.task_id) }).catch(() => { // 用户取消删除 }) } </script> <script> export default { name: 'TaskDetail' } </script> <style> /* 确保弹窗在X轴和Y轴都居中 */ .task-detail-dialog .van-dialog { position: fixed !important; top: 50% !important; left: 50% !important; transform: translate(-50%, -50%) !important; margin: 0 !important; max-height: 80vh !important; overflow-y: auto !important; } .task-detail-dialog :deep(.van-dialog__content) { max-height: 70vh; overflow-y: auto; } .task-detail-dialog :deep(.van-dialog) { max-height: 85vh; overflow: hidden; display: flex; flex-direction: column; } .task-detail-dialog :deep(.van-dialog__header) { flex-shrink: 0; padding: 12px 16px; font-size: 14px; } </style>
2977094657/BiliHistoryFrontend
8,994
src/components/tailwind/scheduler/SelectDialog.vue
<template> <van-dialog :show="show" @update:show="$emit('update:show', $event)" :title="title" width="90%" :show-confirm-button="false" class="select-dialog" > <template #title> <div class="flex items-center justify-between px-4"> <span>{{ title }}</span> <button @click="$emit('update:show', false)" class="p-1 hover:bg-gray-100 rounded-lg transition-colors" > <svg class="w-4 h-4 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /> </svg> </button> </div> </template> <div class="p-4"> <!-- 搜索框 --> <div class="mb-4 flex items-center space-x-2"> <div class="flex-1 relative"> <input v-model="searchQuery" type="text" :placeholder="searchPlaceholder" class="w-full pl-8 pr-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-[#fb7299] focus:border-[#fb7299]" /> <svg class="w-4 h-4 text-gray-400 absolute left-2.5 top-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /> </svg> <button v-if="searchQuery" @click="resetSearch" class="absolute right-2 top-2 text-gray-400 hover:text-gray-600" > <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /> </svg> </button> </div> <!-- 方法过滤器 --> <select v-if="showMethodFilter" v-model="methodFilter" class="text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-[#fb7299] focus:border-[#fb7299] py-1.5 pl-2 pr-8" > <option value="ALL">全部</option> <option value="GET">GET</option> <option value="POST">POST</option> <option value="PUT">PUT</option> <option value="DELETE">DELETE</option> </select> </div> <!-- 列表内容 --> <div class="custom-scrollbar max-h-[45vh] overflow-y-auto pr-2"> <div v-for="(items, group) in filteredGroupedItems" :key="group" class="mb-4"> <div class="flex items-center justify-between cursor-pointer mb-2 bg-gray-100 p-2 rounded-lg hover:bg-gray-200" @click="toggleGroup(group)" > <div class="flex items-center space-x-2"> <span class="text-sm font-medium text-gray-800">{{ group || '未分类' }}</span> <span class="text-xs text-gray-600">({{ items.length }}个)</span> </div> <svg class="w-4 h-4 text-gray-600 transform transition-transform duration-200" :class="{ 'rotate-90': expandedGroups[group] }" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" /> </svg> </div> <div v-show="expandedGroups[group]" class="space-y-1 pl-2 border-l-2 border-gray-100"> <div v-for="item in items" :key="item.id" @click="selectItem(item)" class="p-2 hover:bg-gray-50 cursor-pointer rounded-md transition-colors" :class="{'bg-[#fb7299]/10 hover:bg-[#fb7299]/20': isSelected(item)}" > <div class="flex items-start justify-between"> <div class="flex-1"> <div class="text-sm font-medium text-gray-900">{{ item.name || '' }}</div> <div class="text-xs text-gray-500 mt-0.5">{{ item.description || '' }}</div> </div> <div v-if="item.method" class="ml-3"> <span class="px-2 py-0.5 text-xs font-medium rounded-full" :class="{ 'bg-blue-100 text-blue-800': item.method === 'GET', 'bg-green-100 text-green-800': item.method === 'POST', 'bg-yellow-100 text-yellow-800': item.method === 'PUT', 'bg-red-100 text-red-800': item.method === 'DELETE' }"> {{ item.method }} </span> </div> </div> </div> </div> </div> </div> </div> </van-dialog> </template> <script setup> import { ref, computed, watch } from 'vue' import 'vant/es/dialog/style' const props = defineProps({ show: { type: Boolean, default: false }, title: { type: String, required: true }, items: { type: Array, default: () => [] }, groupBy: { type: String, default: 'tags' }, selected: { type: [String, Array], default: null }, multiple: { type: Boolean, default: false }, showMethodFilter: { type: Boolean, default: false }, searchPlaceholder: { type: String, default: '搜索...' } }) const emit = defineEmits(['update:show', 'select', 'update:selected']) const searchQuery = ref('') const methodFilter = ref('ALL') const expandedGroups = ref({}) const selectedItems = ref(props.multiple ? [] : null) // 初始化选中状态 watch(() => props.selected, (newVal) => { selectedItems.value = props.multiple ? (Array.isArray(newVal) ? newVal : []) : newVal }, { immediate: true }) // 更新格式化任务项的函数以适应新的数据结构 const formatTaskItem = (task) => { const formattedTask = { id: task.id || task.operationId || task.path, name: task.name || task.summary || task.path, description: task.description || task.path, method: task.method || 'GET', tags: Array.isArray(task.tags) ? task.tags : [], enabled: task.enabled, execution: task.execution || {}, config: task.config || {}, parent_id: task.parent_id, sub_tasks: task.sub_tasks || [], sequence_number: task.sequence_number } return formattedTask } // 分组和过滤数据 const filteredGroupedItems = computed(() => { let filtered = props.items.map(formatTaskItem) // 搜索过滤 if (searchQuery.value) { const query = searchQuery.value.toLowerCase() filtered = filtered.filter(item => (item.name && item.name.toLowerCase().includes(query)) || (item.description && item.description.toLowerCase().includes(query)) ) } // 方法过滤 if (props.showMethodFilter && methodFilter.value !== 'ALL') { filtered = filtered.filter(item => item.method === methodFilter.value) } // 分组 const grouped = {} filtered.forEach(item => { if (props.groupBy === 'tags' && Array.isArray(item.tags) && item.tags.length > 0) { item.tags.forEach(tag => { if (!grouped[tag]) { grouped[tag] = [] } grouped[tag].push(item) }) } else { const group = item[props.groupBy] || '未分类' if (!grouped[group]) { grouped[group] = [] } grouped[group].push(item) } }) return grouped }) // 切换分组展开状态 const toggleGroup = (group) => { expandedGroups.value[group] = !expandedGroups.value[group] } // 重置搜索 const resetSearch = () => { searchQuery.value = '' methodFilter.value = 'ALL' // 重置所有分组为展开状态 Object.keys(filteredGroupedItems.value).forEach(group => { expandedGroups.value[group] = true }) } // 选择项目 const selectItem = (item) => { if (props.multiple) { const index = selectedItems.value.indexOf(item.id) if (index === -1) { selectedItems.value.push(item.id) } else { selectedItems.value.splice(index, 1) } } else { selectedItems.value = item.id emit('update:show', false) } emit('select', item) emit('update:selected', selectedItems.value) } // 判断是否选中 const isSelected = (item) => { if (props.multiple) { return selectedItems.value.includes(item.id) } return selectedItems.value === item.id } // 监听显示状态,重置搜索和展开所有分组 watch(() => props.show, (newVal) => { if (newVal) { resetSearch() } }) </script> <style scoped> .select-dialog :deep(.van-dialog) { max-height: 80vh; overflow: hidden; display: flex; flex-direction: column; } .select-dialog :deep(.van-dialog__header) { flex-shrink: 0; padding: 12px 16px; font-size: 14px; } /* 自定义滚动条样式 */ .custom-scrollbar { scrollbar-width: thin; scrollbar-color: #fb7299 #f3f4f6; } .custom-scrollbar::-webkit-scrollbar { width: 4px; } .custom-scrollbar::-webkit-scrollbar-track { background: #f3f4f6; border-radius: 2px; } .custom-scrollbar::-webkit-scrollbar-thumb { background-color: #fb7299; border-radius: 2px; } </style>
281677160/openwrt-package
4,646
luci-app-passwall2/luasrc/view/passwall2/node_list/link_add_node.htm
<% local api = require "luci.passwall2.api" -%> <script type="text/javascript"> //<![CDATA[ function ajax_add_node(link) { const chunkSize = 1000; // 分片发送以突破uhttpd的限制,每块1000字符 const totalChunks = Math.ceil(link.length / chunkSize); let currentChunk = 0; function sendNextChunk() { if (currentChunk < totalChunks) { const chunk = link.substring(currentChunk * chunkSize, (currentChunk + 1) * chunkSize); const xhr = new XMLHttpRequest(); xhr.open('POST', '<%=api.url("link_add_node")%>', true); xhr.onload = function () { if (xhr.status === 200) { currentChunk++; sendNextChunk(); } else { alert("<%:Error%>"); return; } }; xhr.onerror = function () { alert("<%:Network Error%>"); return; }; const formData = new FormData(); formData.append("chunk", chunk); formData.append("chunk_index", currentChunk); formData.append("total_chunks", totalChunks); xhr.send(formData); } else { window.location.href = '<%=api.url("node_list")%>'; } } sendNextChunk(); } function open_add_link_div() { document.getElementById("add_link_div").style.display = "block"; document.getElementById("nodes_link").focus(); } function close_add_link_div() { document.getElementById("add_link_div").style.display = "none"; } function add_node() { var nodes_link = document.getElementById("nodes_link").value; nodes_link = nodes_link.replace(/\t/g, "").replace(/\r\n|\r/g, "\n").trim(); if (nodes_link != "") { var s = nodes_link.split('://'); if (s.length > 1) { ajax_add_node(nodes_link); } else { alert("<%:Please enter the correct link.%>"); } } else { document.getElementById("nodes_link").focus(); } } function clear_all_nodes() { if (confirm('<%:Are you sure to clear all nodes?%>') == true){ XHR.get('<%=api.url("clear_all_nodes")%>', null, function(x, data) { if(x && x.status == 200) { window.location.href = '<%=api.url("node_list")%>'; } else { alert("<%:Error%>"); } }); } } //]]> </script> <div id="add_link_div"> <div id="add_link_modal_container"> <h3><%:Add the node via the link%></h3> <div class="cbi-value"> <textarea id="nodes_link" rows="10"></textarea> <p id="nodes_link_text"><%:Enter share links, one per line. Subscription links are not supported!%></p> </div> <div id="add_link_button_container"> <input class="btn cbi-button cbi-button-add" type="button" onclick="add_node()" value="<%:Add%>" /> <input class="btn cbi-button cbi-button-remove" type="button" onclick="close_add_link_div()" value="<%:Close%>" /> </div> </div> </div> <div class="cbi-value"> <label class="cbi-value-title"></label> <div class="cbi-value-field"> <input class="btn cbi-button cbi-button-add" type="submit" name="cbi.cts.<%=api.appname%>.nodes." value="<%:Add%>" /> <input class="btn cbi-button cbi-button-add" type="button" onclick="open_add_link_div()" value="<%:Add the node via the link%>" /> <input class="btn cbi-button cbi-button-remove" type="button" onclick="clear_all_nodes()" value="<%:Clear all nodes%>" /> <input class="btn cbi-button cbi-button-remove" type="button" onclick="delete_select_nodes()" value="<%:Delete select nodes%>" /> <input class="btn cbi-button" type="button" onclick="checked_all_node(this)" value="<%:Select all%>" /> <input class="btn cbi-button cbi-button-apply" type="submit" name="cbi.apply" value="<%:Save & Apply%>" /> <input class="btn cbi-button cbi-button-save" type="submit" name="cbi.save" value="<%:Save%>" /> <input class="btn cbi-button cbi-button-reset" type="button" value="<%:Reset%>" onclick="location.href='<%=REQUEST_URI%>'" /> <div id="div_node_count"></div> </div> </div> <style> #add_link_div { display: none; position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 2px solid #ccc; box-shadow: 0 0 10px rgba(0,0,0,0.5); z-index: 1000; width: 90%; max-width: 500px; } #add_link_modal_container { width: 100%; text-align: center; display: flex; flex-direction: column; align-items: center; padding-bottom: 20px; } #nodes_link { width: 100%; height: 180px; resize: vertical; font-family: monospace; padding: 5px; border: 1px solid #ccc; border-radius: 5px; } #nodes_link_text { color: red; font-size: 14px; margin-top: 5px; text-align: center; width: 100%; } #add_link_button_container { display: flex; justify-content: space-between; width: 100%; max-width: 300px; margin-top: 10px; } </style>
298582245/wqwl_qinglong
17,894
wqwl_老友时光汇.js
/** * update: 25/08/04 * 更新内容:优化了一下答题次数 * 脚本:wqwl_老友时光汇.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序老友时光汇 * 环境变量:wqwl_lysgh,多个换行或新建多个变量 * 环境变量描述:抓包Headers下的x-token * 代理变量:wqwl_daili * cron: 0 11 * * * */ const axios = require('axios'); const fs = require('fs'); const crypto = require('crypto'); !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); const isNotify = true; // 是否通知 let notify; if (isNotify) { try { notify = require('./sendNotify'); } catch (e) { console.log('❌加载发送通知失败'); } } let index = 0; const ckName = 'wqwl_lysgh'; const name = '微信小程序老友时光汇' class Task { constructor(cookie) { this.url = 'https://api.zijinzhaoyao.com/api' this.index = index++; this.headers = '' this.cookie = cookie; } async init() { this.headers = { "Host": "api.zijinzhaoyao.com", "code": '', "Connection": "keep-alive", "Cache-Control": "no-cache", "sec-ch-ua": "", "Accept": "application/json, text/plain, */*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Content-Type": "application/json;charset=UTF-8", "Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Dest": "empty", "Referrer-Policy": "unsafe-url", "xweb_xhr": "1", "User-Agent": wqwlkj.generateRandomUA(), "miniprogram-environment": "wechat", "wxapp-version": "1.0.3", "x-requested-with": "XMLHttpRequest", "project-name": "yl", "x-token": this.cookie, "x-tt-device-id": this.getDeviceId(), "deviceid": "", "Origin": "https://servicewechat.com", "Referer": "https://servicewechat.com/wxa973bdd2c6278631/13/page-frame.html", "Cookie": `acw_tc=${Date.now()}_${wqwlkj.getRandom(1000, 9999)};` } if (process.env["wqwl_daili"] != undefined) { this.proxy = await wqwlkj.getProxy() } else { this.proxy = '' } //解析jwt try { const jwtData = this.cookie.split('.') const jwt = JSON.parse(Buffer.from(jwtData[1], 'base64').toString()) this.userId = jwt.userID } catch (e) { throw new Error('cookie解析失败') } } async main() { await this.init() await this.sign() await wqwlkj.sleep(wqwlkj.getRandom(1, 3)) await this.getActivityList() await wqwlkj.sleep(wqwlkj.getRandom(1, 3)) } // 生成设备ID getDeviceId() { const prefix = "android-"; const randomStr = crypto.randomBytes(12).toString('hex'); return prefix + randomStr; } // 签到 async sign() { let result try { const url = `${this.url}/userIsSign` this.headers['project-name'] = 'yl' const options = { url: url, method: 'POST', headers: this.headers, data: {} } //console.log(options) result = await wqwlkj.request(options, this.proxy) this.headers['code'] = 'adsadada' if (result.data === false) { this.headers['deviceid'] = this.getAES('adsadada') const options = { url: `${this.url}/userSign`, method: 'POST', headers: this.headers, data: {} } //console.log(options) const signReusult = await wqwlkj.request(options, this.proxy) if (signReusult.code === 0) { this.sendMessage(`签到成功✅`) } } else { this.sendMessage(`今日已签到✅`) } } catch (e) { console.log(result) throw new Error(`签到发现异常❌:${e.message}`) } } // 获取活动列表 async getActivityList() { try { const url = `${this.url}/v3/activity-list/columns` const data = JSON.stringify({ column: 1 }) this.headers['project-name'] = 'xld' const options = { url, data: data, headers: this.headers, method: 'POST' } const res = await wqwlkj.request(options, this.proxy) if (res.code === 0) { const resData = res const activityList = resData.data if (activityList.length > 0) { for (let i = 0; i < activityList.length; i++) { const activity = activityList[i] const id = activity.id const title = activity.title const endTime = new Date(activity.endTime * 1000).toLocaleString() const leftMoney = activity.leftMoney const times = activity.times - activity.count let allTimes = 0 let testTimes = 0 if (leftMoney > 0 && times > 0 && activity.endTime * 1000 > Date.now()) { this.sendMessage(`获取到活动:【 ${title}】,结束时间: ${endTime},剩余金额: ${leftMoney},开始答题`) while (times > allTimes && testTimes < 10) { // console.log(`活动id:${id}`) this.sendMessage(`第${allTimes + 1}次答题`) const result = await this.startAnswer(id) testTimes++ if (testTimes >= 10) { this.sendMessage(`❌已连续答题10次未成功,请稍后再试`) break } if (!result) { await wqwlkj.sleep(wqwlkj.getRandom(5, 10)) continue } allTimes++ await wqwlkj.sleep(wqwlkj.getRandom(5, 10)) } await this.getUserCredits() } else { this.sendMessage(`获取到活动: ❌:【${title}】在${endTime}已结束|剩余${leftMoney}元|剩余答题${times}次`) } } } } else { this.sendMessage(`获取活动列表失败❌: ${res.message}`) } } catch (e) { throw new Error(`请求活动列表失败❌: ${e.message}`) } } async startAnswer(id) { try { const url = `${this.url}/v2/startAnswer` const data = JSON.stringify({ id: id }) this.headers['project-name'] = 'yl' const options = { url: url, method: 'POST', headers: this.headers, data: data } const res = await wqwlkj.request(options, this.proxy) if (res.code == 0) { const resData = res const questionNum = resData.data.questionNum const examId = resData.data.examId const answer = resData.data.question.answer if (id && examId && answer) { const res1 = await this.submitAnswer(id, examId, answer, questionNum) await wqwlkj.sleep(wqwlkj.getRandom(5, 10)) const res2 = await this.saveLog(this.userId, id) await wqwlkj.sleep(wqwlkj.getRandom(10, 15)) const res3 = await this.submitExam(id, examId) return res1 && res2 && res3 } else { this.sendMessage('获取答案失败') return false } } else { this.sendMessage(`开始答题失败:${res.message}`) return false } } catch (e) { throw new Error(`开始答题请求失败: ${e.message}`) } } async submitAnswer(id, examId, answer, number) { try { const url = `${this.url}/submitAnswer` const data = JSON.stringify({ id: id, examId: examId, answer: answer, number: number }) const options = { url: url, method: 'POST', headers: this.headers, data: data } const res = await wqwlkj.request(options, this.proxy) if (res.code === 0) { this.sendMessage(`提交答案请求结果:${res.data.isCorrect === true ? '✅正确' : '❌错误'}`) return true } else { this.sendMessage(`提交答案失败,${res.message}`) return false } } catch (e) { throw new Error(`提交答案请求失败: ${e.message}`) } } async submitExam(id, examId) { try { const url = `${this.url}/v2/submitExam` const data = JSON.stringify({ id: id, examId: examId, }) const code = this.getRandomCode() const deviceid = this.getAES(code) this.headers['code'] = code this.headers['deviceid'] = deviceid const options = { url: url, method: 'POST', headers: this.headers, data: data } //console.log(options) const res = await wqwlkj.request(options, this.proxy) if (res.code === 0) { this.sendMessage(`提交最终结果奖励:✅🪙积分:${res.data.credits},💰现金:${res.data.money}元`) return true } else { // console.log(res) this.sendMessage(`提交最终结果失败❌,${res.message}`) return false } } catch (e) { throw new Error(`提交最终结果请求失败❌: ${e.message}`) } } //保存日志 async saveLog(userId = 12, id) { try { const url = `${this.url}/userVisitLog` const data = JSON.stringify({ "visit_url": `/pages/crushPage/game/index?isNeedAd=1&adOrder=2&id=${id}&type=1`, "user_id": userId, "channel_id": 0, "event_type": "submit_activity" }) const options = { url: url, method: 'POST', headers: this.headers, data: data } const res = await wqwlkj.request(options, this.proxy) return true //console.log(res) } catch (e) { throw new Error(`保存日志请求失败❌: ${e.message}`) } } async getUserCredits() { try { const options = { url: `${this.url}/v2/getUserCredits`, method: 'POST', headers: this.headers, data: JSON.stringify({ }) } const res = await wqwlkj.request(options, this.proxy) if (res.code === 0) { const amount = res.data.credits this.sendMessage(`获取用户积分成功✅: ${amount}`) if (amount > 50) { this.sendMessage(`积分可以兑换,开始自动兑换`) await this.creditExchange(amount) } } } catch (e) { throw new Error(`获取积分失败,${e.message}`) } } async creditExchange(credits) { try { const options = { url: `${this.url}/v3/credits-exchange`, method: 'POST', headers: this.headers, data: JSON.stringify({ amount: credits }) } const res = await wqwlkj.request(options, this.proxy) if (res.code === 0) { this.sendMessage(`兑换成功✅:约${credits / 10}元`, true) } else { this.sendMessage(`兑换失败❌: ${JSON.stringify(res)}`) } } catch (e) { throw new Error(`兑换失败,${e.message}`) } } getAES(code) { const ramdom = wqwlkj.getRandom(31, 40) const adStartTime = Date.now() + ramdom * 1000; // 假设广告 35 秒前开始 const now = Date.now(); const c = adStartTime ? Math.floor((now - adStartTime) / 1000) : 0; const deviceIdObj = { code: code || Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15), t: Math.floor(now / 1000), c: c }; const plaintext = JSON.stringify(deviceIdObj); // console.log('deviceIdObj:', deviceIdObj); const key = 'Kj8mN2pQ9rS5tU7vW3xY1zA4bC6dE8fG'; const iv = 'H7nM4kL9pQ2rS5tU'; return wqwlkj.aesEncrypt(plaintext, key, iv, 'aes-256-cbc', 'utf8', 'utf8', 'hex'); } getRandomCode() { return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}]: ${message}` if (isNotify && isPush) wqwlkj.sendMessage(message + "\n") else console.log(message) } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); const tasks = tokens.map(token => new Task(token).main()); await Promise.all(tasks); // 所有任务并发执行 console.log("全部任务已完成!"); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
294coder/Efficient-MIF
4,199
Pansharpening_Hyper_SR_Matlab_Test_Package/PNN/PNN.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % PNN algorithm for pansharpening by Masi et al. (2016). % Interface: % P = PNN(MS, PAN, sensor_model, nBits, NDxI_flag, EXP); % P = PNN(MS, PAN, sensor_model, nBits, NDxI_flag); % P = PNN(MS, PAN, sensor_model, nBits); % P = PNN(MS, PAN, sensor_model). % Input: % MS: 4- or 8-band multispectral image; % PAN: Panchromatic image (must be 4x4x larger than MS); % sensor_model: One of the following string: % 'IKONOS' % 'GeoEye1' % 'WV2' % 'WV3' % '<full-path file name of any pretrained model>' % WARNING: If an own model is used, the file must be a work % space with a cell-array variable named 'layers' % containing the sequence of weights and bias of the % three convolutional layers. Also the following % variables must be enclosed in the work space: lr, % patch_size, ratio, sensor, inputType, typeInterp. % For consistency check watch the content of any % provided model (e.g., 'IKONOS_PNN_model.mat'). % % nBits: #bits (radiometric precision). % Default = 11; % NDxI_flag: Boolean indicating the use of additional input % bands such as NDVI, NDWI, etc. % Default = true; % EXP: 4- or 8-band multispectral image upsampled to the PAN scale % Output: % P: Pansharpened image; % % References: % [Masi16] G. Masi, D. Cozzolino, L. Verdoliva and G. Scarpa, "Pansharpening by Convolutional Neural Networks", % Remote Sensing 2016, 8(7):594. % [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods", % IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function P = PNN(MS, PAN, sensor_model, nBits, NDxI_flag, EXP) if nargin < 6 EXP = []; end if nargin == 3, NDxI_flag = true; nBits = 11; end if nargin == 5, if isempty(nBits), nBits = 11; end; end MS = single(MS); PAN = single(PAN); nBits = single(nBits); EXP = single(EXP); [M,N,Nb] = size(MS); %%% LOAD PRETRAINED MODEL available_models = {'IKONOS', 'GeoEye1','WV2', 'WV3'}; if sum(ismember(available_models,sensor_model)) cd 'models' if NDxI_flag sensor_model = which([sensor_model '_PNN_model.mat']); else sensor_model = which([sensor_model '_PNN_noIDX_model.mat']); end cd .. end model = load(sensor_model); model.L = nBits; %net_scope = model_scope(model); % build list of layers if NDxI_flag if Nb == 8 Nb = Nb+4; else Nb = Nb+2; end end firstLayer = imageInputLayer([M N Nb+1],'Name','InputLayer','Normalization','none'); layers = load_layers(firstLayer,model); %scaling learning rate on last layer layers(end).WeightLearnRateFactor =0.1; % Not needed layers(end).BiasLearnRateFactor =0.1; % Not needed %layers = [layers,maeRegressionLayer('regre')]; layers = [layers, regressionLayer('Name','regre')]; % not needed pad = model.padSize; [Mpan, Npan] = size(PAN); lgraph = layerGraph(layers); lgraph = replaceLayer(lgraph,lgraph.Layers(1).Name,imageInputLayer([Mpan+pad Npan+pad Nb+1],'Name','InputLayer','Normalization','none')); net = assembleNetwork(lgraph); %% Pansharpening I_in = input_preparation(EXP,MS,PAN,model); tic; P = predict(net,I_in); %Test_time = toc; P = P*(2^model.L); P(P<0)=0; %%% %fprintf(sprintf('------> [PNN]: Prediction time = %0.4gs\n', Test_time)); end
294coder/Efficient-MIF
2,470
Pansharpening_Hyper_SR_Matlab_Test_Package/PNN/resize_images_GNyq.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Generate the low resolution PANchromatic (PAN) and MultiSpectral (MS) images according to Wald's protocol. % % Interface: % [I_MS_LR, I_PAN_LR] = resize_images_GNyq(I_MS,I_PAN,ratio,GNyqMS) % % Inputs: % I_MS: MS image upsampled at PAN scale; % I_PAN: PAN image; % ratio: Scale ratio between MS and PAN. Pre-condition: Integer value; % GNyqMS: (optional) custom MS MTF gains. % % Outputs: % I_MS_LR: Low Resolution MS image; % I_PAN_LR: Low Resolution PAN image. % % References: % [Wald97] L. Wald, T. Ranchin, and M. Mangolini, "Fusion of satellite images of different spatial resolutions: assessing the quality of resulting images," % Photogrammetric Engineering and Remote Sensing, vol. 63, no. 6, pp. 691-699, June 1997. % [Aiazzi06] B. Aiazzi, L. Alparone, S. Baronti, A. Garzelli, and M. Selva, "MTF-tailored multiscale fusion of high-resolution MS and Pan imagery," % Photogrammetric Engineering and Remote Sensing, vol. 72, no. 5, pp. 591-596, May 2006. % [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms, % IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [I_MS_LR, I_PAN_LR] = resize_images_GNyq(I_MS,I_PAN,ratio,GNyqMS) I_MS = double(I_MS); I_PAN = double(I_PAN); %%% MTF N = 41; nBands = length(GNyqMS); h = zeros(N, N, nBands); fcut = 1/ratio; for ii = 1 : nBands alpha = sqrt(((N-1)*(fcut/2))^2/(-2*log(GNyqMS(ii)))); H = fspecial('gaussian', N, alpha); Hd = H./max(H(:)); h(:,:,ii) = fwind1(Hd,kaiser(N)); end I_MS_LP = zeros(size(I_MS)); for ii = 1 : size(I_MS,3) I_MS_LP(:,:,ii) = imfilter(I_MS(:,:,ii),real(h(:,:,ii)),'replicate'); end %%% Decimation MS I_MS_LP_D = zeros(round(size(I_MS,1)/ratio),round(size(I_MS,2)/ratio),size(I_MS,3)); for idim = 1 : size(I_MS,3) I_MS_LP_D(:,:,idim) = imresize(I_MS_LP(:,:,idim),1/ratio,'nearest'); end I_MS_LR = double(I_MS_LP_D); I_PAN_LR = imresize(I_PAN, 1/ratio); end
294coder/Efficient-MIF
1,056
Pansharpening_Hyper_SR_Matlab_Test_Package/PNN/load_layers.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Load pretrained layers from network trained in Python. % Interface: % layers = load_layers(firstLayer,model) % Inputs: % firstLayer: Input layer with info for input image; % model: Struct with training details of pretrained network. % Output: % layers: List of layers. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function layers = load_layers(firstLayer,model) conv_layer = {}; k=0; layers=[firstLayer]; for i = [1:2:length(model.layers)] k=k+1; s = size(model.layers{i}); conv_layer{k}=convolution2dLayer(s(1),s(4)); conv_layer{k}.Name = sprintf('conv%d',k); conv_layer{k}.Weights = model.layers{i}; conv_layer{k}.Bias = model.layers{i+1}; if i < length(model.layers)-1 l = reluLayer('Name',sprintf('relu%d',k)); layers = [layers,conv_layer{k},l]; else layers = [layers,conv_layer{k}]; end end end
2881099/FreeSql.AdminLTE
1,154
Examples/net80_blazor/Entities/MenuEntity.cs
using FreeSql.DataAnnotations; using FreeSql.AdminLTE; using System.Text.Json.Serialization; namespace net80_blazor.Entities { public class MenuEntity : EntityFull { /// <summary> /// 父级菜单 /// </summary> public long ParentId { get; set; } /// <summary> /// 名称 /// </summary> public string Label { get; set; } /// <summary> /// 图标 /// </summary> public string Icon { get; set; } /// <summary> /// 路径 /// </summary> public string Path { get; set; } /// <summary> /// 新窗口打开 /// </summary> public bool TargetBlank { get; set; } /// <summary> /// 排序 /// </summary> public int Sort { get; set; } /// <summary> /// 类型 /// </summary> public MenuEntityType Type { get; set; } [Navigate(nameof(ParentId)), JsonIgnore] public MenuEntity Parent { get; set; } [Navigate(nameof(MenuEntity.ParentId))] public List<MenuEntity> Childs { get; set; } } public enum MenuEntityType { 菜单, 按钮, 资源 } }
298582245/wqwl_qinglong
17,448
wqwl_芃儒文章.js
/** * 脚本:wqwl_芃儒文章.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序芃儒文章 * 环境变量:wqwl_frwz,多个换行或新建多个变量 * 环境变量描述:抓包请求参数下的state,格式例如:state#备注1 * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 3 * * * 刷满为止 */ const axios = require('axios'); const fs = require('fs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || true; //并发数,默认4 let bfs = process.env["wqwl_bfs"] || 4; // 是否通知 let isNotify = true; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_frwz'; //脚本名称 const name = '微信小程序芃儒文章' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } let fileData = wqwlkj.readFile('frwz') || {}; class Task { constructor(ck) { this.index = index++; this.ck = ck this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) } async init() { const ckData = this.ck.split('#') if (ckData.length < 1) { return this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 1) { this.remark = ckData[0].slice(0, 8); } else { this.remark = ckData[1]; } this.state = ckData[0]; this.headers = { "accept": "*/*", "accept-language": "zh-CN,zh;q=0.9", "content-type": "application/x-www-form-urlencoded", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "xweb_xhr": "1", "referrer": "https://servicewechat.com/wxd03a809cfc99930b/4/page-frame.html", "referrerPolicy": "unsafe-url", } this.today = wqwlkj.formatDate(new Date()) if (!fileData[this.remark]) fileData[this.remark] = {} if (!fileData[this.remark][this.today]) fileData[this.remark][this.today] = { 'sign': false, 'ad': false, 'sp': false } if (fileData[this.remark][this.today]['sign'] && fileData[this.remark][this.today]['ad'] && fileData[this.remark][this.today]['sp']) { this.sendMessage(`✅今日任务已经全部完成啦`) return false } if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } return true } async myScoreTasks() { const options = { url: this.getUrl('MyScoreTasks'), headers: this.headers, method: 'GET' } //console.log(JSON.stringify(options)) try { let res = await this.request(options, 0) let ad, sp if (res.message === 'ok') { ad = res?.data?.videoAd sp = res?.data?.rollVideo if (sp === undefined || ad === undefined) { this.sendMessage(`🔍检查到为今天首次运行,将模拟第一次运行`) await this.scoreTaskVideoAd() await wqwlkj.sleep(wqwlkj.getRandom(8, 16)) await this.scoreTaskRollVideo() } res = await this.request(options, 0) ad = res?.data?.videoAd sp = res?.data?.rollVideo const adStep = ad?.step || 0 const adTotal_step = ad?.total_step || 0 this.sendMessage(`任务${ad?.type_text}(${adStep}/${adTotal_step})`) const spStep = sp?.step || 0 const spTotal_step = sp?.total_step || 0 this.sendMessage(`任务${sp?.type_text}(${spStep}/${spTotal_step})`) return { ad: adTotal_step - adStep, sp: spTotal_step - spStep } } else { this.sendMessage(`❌获取积分任务列表失败,${res.message}`) return 0 } } catch (e) { this.sendMessage(`❌请求获取积分任务列表失败,${e}`) console.log(e) } } async scoreTaskSignIn() { const options = { url: this.getUrl('ScoreTaskSignIn'), headers: this.headers, method: 'GET' } try { const res = await this.request(options, 0) if (res.message === 'ok') { this.sendMessage(`✅签到成功,积分+${res?.data?.reward_score}`) fileData[this.remark][this.today]['sign'] = true } else { if (res.message.includes('已签到')) fileData[this.remark][this.today]['sign'] = true this.sendMessage(`❌签到失败,${res.message}`) } } catch (e) { throw new Error(`❌请求签到失败,${e}`) } } async scoreTaskVideoAd() { const options = { url: this.getUrl('ScoreTaskVideoAd'), headers: this.headers, method: 'GET' } try { const res = await this.request(options, 0) if (res.message === 'ok') { this.sendMessage(`✅观看广告成功,积分+${res?.data?.reward_score}`) } else { this.sendMessage(`❌观看广告失败,${res.message}`) } } catch (e) { throw new Error(`❌观看广告失败,${e}`) } } async scoreTaskRollVideo() { const options = { url: this.getUrl('ScoreTaskRollVideo'), headers: this.headers, method: 'GET' } try { const res = await this.request(options, 0) if (res.message === 'ok') { this.sendMessage(`✅观看视频成功,积分+${res?.data?.reward_score}`) } else { this.sendMessage(`❌观看视频失败,${res.message}`) } } catch (e) { throw new Error(`❌观看视频请求失败,${e}`) } } async withdrawUserScore() { const options = { url: this.getUrl('WithdrawUserScore'), headers: this.headers, method: 'GET' } try { const res = await this.request(options, 0) if (res.message === 'ok') { let cash = res?.data?.max cash = Math.floor(cash * 10) / 10; this.sendMessage(`💸可提现最大余额:${cash}`, true) if (cash > 99999) { this.sendMessage(`准备提现`) await this.withdrawApply(cash) } } else { this.sendMessage(`❌获取余额失败,${res.message}`) } } catch (e) { throw new Error(`❌获取余额请求失败,${e}`) } } async withdrawApply(cash) { let url = this.getUrl('WithdrawApply', { cash: cash }) url += '&cash=' + cash const options = { url: url, headers: this.headers, method: 'GET' } try { const res = await this.request(options, 0) console.log(JSON.stringify(res)) if (res.message === 'ok') { this.sendMessage(`✅提现成功`) } else { this.sendMessage(`❌提现失败,${res.message}`) } } catch (e) { throw new Error(`❌请求提现失败,${e}`) } } async main() { const isFinish = await this.init() if (!isFinish) return await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) if (fileData[this.remark][this.today]['sign'] && fileData[this.remark][this.today]['ad'] && fileData[this.remark][this.today]['sp']) return this.sendMessage(`✅今日任务已经全部完成啦`) else await this.scoreTaskSignIn() const times = await this.myScoreTasks() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) let i = 0, j = 0 for (i = 0; i < times.ad; i++) { const sleep = wqwlkj.getRandom(30, 40) this.sendMessage(`🔁开始第${i + 1}次模拟观看广告,等待待${sleep}秒...`); await wqwlkj.sleep(sleep) await this.scoreTaskVideoAd() } if (i >= times.ad) fileData[this.remark][this.today]['ad'] = true await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) for (j = 0; j < times.sp; j++) { const sleep = wqwlkj.getRandom(8, 16) this.sendMessage(`🔁开始第${j + 1}次模拟观看视频,等待待${sleep}秒...`); await wqwlkj.sleep(sleep) await this.scoreTaskRollVideo() } if (j >= times.sp) fileData[this.remark][this.today]['sp'] = true await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.withdrawUserScore() } getUrl(Do, arg = {}) { if (!this.state || !Do) return `❌验证数据为空` let url = `https://weiqing.lingchuangwang.com/app/index.php?i=89&t=0&v=1.0.6&from=wxapp&c=entry&a=wxapp&do=${Do}&state=${this.state}&m=mof_shortvideo&_vi=76` const _t = (new Date).getTime() const _ut = _t + 1 url += `&_t=${_t}&_ut=${_ut}` const sign = this.getSign(url, arg) url += `&sign=${sign}` return url } getSign(e, t, n) { const getUrlParam = (url, param) => { const urlObj = new URL(url, 'http://dummy.com'); return urlObj.searchParams.get(param); }; const getQuery = (url) => { const urlObj = new URL(url, 'http://dummy.com'); const params = []; urlObj.searchParams.forEach((value, name) => { params.push({ name, value }); }); return params; }; let i = ""; const o = getUrlParam(e, "sign"); if (o || (t && t.sign)) { return false; } if (e) { i = getQuery(e); } if (t) { let s = []; for (let u in t) { if (t.hasOwnProperty(u) && u && t[u] !== "") { s.push({ name: u, value: t[u] }); } } i = i.concat(s); } // 替代 _.sortBy(i, "name") i.sort((a, b) => { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }); // 替代 _.uniq(i, true, "name") const seen = new Set(); i = i.filter(item => { if (!item || !item.name) return false; if (seen.has(item.name)) return false; seen.add(item.name); return true; }); let c = ""; for (let f = 0; f < i.length; f++) { if (i[f] && i[f].name && i[f].value !== "") { c += i[f].name + "=" + i[f].value; if (f < i.length - 1) { c += "&"; } } } const secret = n || 'wq_mof_short_video_by_moufer_2020'; //console.log(c, secret); return wqwlkj.md5(c + '&' + secret); } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); return data; } catch (error) { this.sendMessage(`🔐检测到请求发生错误,正在重试...`) let newProxy; if (isProxy) { newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); } else { this.sendMessage(`⚠️未使用代理`); newProxy = true } if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } wqwlkj.saveFile(fileData, 'frwz') console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
2977094657/BiliHistoryFrontend
27,675
src/components/tailwind/scheduler/TaskForm.vue
<template> <van-dialog :show="show" @update:show="$emit('update:show', $event)" :title="getDialogTitle" width="60%" :show-confirm-button="false" class="task-form-dialog" > <div class="p-2"> <form @submit.prevent="submitForm" class="space-y-2"> <!-- 表单标题和说明 --> <div class="flex items-center mb-2 pb-1 border-b border-gray-100"> <div class="p-1 bg-[#fb7299]/10 rounded-lg mr-2"> <svg class="w-3.5 h-3.5 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /> </svg> </div> <div> <h3 class="text-sm font-medium text-gray-800">{{ getFormTitle }}</h3> <p class="text-xs text-gray-500">{{ getFormDescription }}</p> </div> </div> <!-- 基本信息 --> <div class="bg-white rounded-lg p-1.5 border border-gray-200"> <h4 class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-1 flex items-center"> <svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> 基本信息 </h4> <div class="grid grid-cols-1 md:grid-cols-2 gap-2"> <div> <label for="taskId" class="block text-xs font-medium text-gray-700 mb-0.5">任务ID</label> <input id="taskId" v-model="form.task_id" type="text" :disabled="props.isEditing" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] text-xs py-1" placeholder="请输入任务ID(选择API端点后会自动填充,可修改)" required /> </div> <div> <label for="name" class="block text-xs font-medium text-gray-700 mb-0.5">任务名称 *</label> <input id="name" v-model="form.name" type="text" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] text-xs py-1" required placeholder="例如:获取B站历史记录" /> </div> </div> </div> <!-- API设置 --> <div class="bg-white rounded-lg p-1.5 border border-gray-200"> <h4 class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-1 flex items-center"> <svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" /> </svg> API设置 </h4> <div class="grid grid-cols-1 md:grid-cols-2 gap-2"> <div> <label for="endpoint" class="block text-xs font-medium text-gray-700 mb-0.5">API端点 *</label> <div class="relative"> <button type="button" @click="showApiSelector = true" class="block w-full text-left rounded-md border border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] text-xs py-1.5 px-2" > {{ form.endpoint || '请选择API端点' }} </button> </div> </div> <div> <label for="method" class="block text-xs font-medium text-gray-700 mb-0.5">请求方法</label> <input id="method" v-model="form.method" type="text" disabled class="block w-full rounded-md border-gray-300 bg-gray-50 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] text-xs py-1" /> </div> </div> </div> <!-- 调度设置 --> <div class="bg-white rounded-lg p-1.5 border border-gray-200"> <h4 class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-1 flex items-center"> <svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> 调度设置 </h4> <div class="grid grid-cols-1 md:grid-cols-2 gap-2"> <div> <label for="scheduleType" class="block text-xs font-medium text-gray-700 mb-0.5">调度类型 *</label> <select id="scheduleType" v-model="form.schedule_type" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] text-xs py-1 disabled:bg-gray-100 disabled:text-gray-500 disabled:cursor-not-allowed" required :disabled="props.parentTaskId || props.isEditing" > <option v-if="!props.parentTaskId" value="daily">每日</option> <option v-if="!props.parentTaskId" value="interval">间隔执行</option> <option value="chain">链式</option> </select> </div> <div v-if="form.schedule_type === 'daily' && !props.parentTaskId"> <label for="scheduleTime" class="block text-xs font-medium text-gray-700 mb-0.5">执行时间 *</label> <input id="scheduleTime" v-model="form.schedule_time" type="time" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] text-xs py-1" required /> </div> <div v-if="form.schedule_type === 'interval' && !props.parentTaskId" class="col-span-2 grid grid-cols-2 gap-2"> <div> <label for="intervalValue" class="block text-xs font-medium text-gray-700 mb-0.5">间隔时间 *</label> <input id="intervalValue" v-model.number="form.interval" type="number" min="1" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] text-xs py-1 disabled:bg-gray-100 disabled:text-gray-500 disabled:cursor-not-allowed" required :disabled="props.isEditing" /> <span v-if="props.isEditing" class="text-xs text-gray-500 mt-0.5 block">间隔任务的时间不可修改</span> </div> <div> <label for="intervalUnit" class="block text-xs font-medium text-gray-700 mb-0.5">时间单位 *</label> <select id="intervalUnit" v-model="form.unit" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] text-xs py-1 disabled:bg-gray-100 disabled:text-gray-500 disabled:cursor-not-allowed" required :disabled="props.isEditing" > <option value="minutes">分钟</option> <option value="hours">小时</option> <option value="days">天</option> <option value="months">月</option> <option value="years">年</option> </select> <span v-if="props.isEditing" class="text-xs text-gray-500 mt-0.5 block">间隔任务的单位不可修改</span> </div> </div> </div> </div> <!-- 依赖任务 --> <div class="bg-white rounded-lg p-1.5 border border-gray-200"> <h4 class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-1 flex items-center"> <svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" /> </svg> 依赖任务 </h4> <div> <label for="requires" class="block text-xs font-medium text-gray-700 mb-0.5">依赖任务 (可选)</label> <div class="relative"> <button type="button" @click="showDependencySelector = true" :disabled="props.parentTaskId || props.isEditing" class="block w-full text-left rounded-md border border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] text-xs py-1.5 px-2 min-h-[2rem] disabled:bg-gray-100 disabled:text-gray-500 disabled:cursor-not-allowed" > <div v-if="form.depends_on.length === 0" class="text-gray-500"> {{ props.parentTaskId ? '子任务依赖关系由系统自动设置' : (props.isEditing ? '编辑时不可修改依赖任务' : '选择依赖任务') }} </div> <div v-else class="flex flex-wrap gap-1"> <div v-for="taskId in form.depends_on" :key="taskId" class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-[#fb7299]/10 text-[#fb7299]" > <span>{{ getTaskName(taskId) }}</span> <button type="button" @click.stop="removeTask(taskId)" class="ml-1 hover:text-[#fb7299]/70" v-if="!props.parentTaskId && !props.isEditing" > <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /> </svg> </button> </div> </div> </button> </div> </div> </div> <!-- 底部按钮 --> <div class="flex justify-end space-x-2 pt-1.5 border-t border-gray-100"> <button type="button" @click="cancel" class="inline-flex items-center px-2 py-1 border border-gray-300 rounded-md text-xs font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-1 focus:ring-offset-1 focus:ring-[#fb7299]" > 取消 </button> <button type="submit" class="inline-flex items-center px-2 py-1 border border-transparent rounded-md text-xs font-medium text-white bg-[#fb7299] hover:bg-[#fb7299]/90 focus:outline-none focus:ring-1 focus:ring-offset-1 focus:ring-[#fb7299]" > {{ getSubmitButtonText }} </button> </div> </form> </div> <!-- API选择弹窗 --> <select-dialog v-model:show="showApiSelector" title="选择API端点" :items="availableEndpoints" v-model:selected="selectedEndpoint" :show-method-filter="true" search-placeholder="搜索API端点..." group-by="tags" id-field="id" name-field="name" description-field="description" @select="handleApiSelect" /> <!-- 依赖任务选择弹窗 --> <select-dialog v-model:show="showDependencySelector" title="选择依赖任务" :items="availableEndpoints" v-model:selected="form.depends_on" :multiple="false" :show-method-filter="true" search-placeholder="搜索任务..." group-by="tags" id-field="operationId" name-field="summary" description-field="path" /> </van-dialog> </template> <script setup> import { ref, computed, reactive, watch, nextTick } from 'vue' import { showNotify } from 'vant' import 'vant/es/notify/style' import SelectDialog from './SelectDialog.vue' import { createSchedulerTask, updateSchedulerTask, getSchedulerTaskDetail, getAvailableEndpoints, addSubTask } from '../../../api/api' const props = defineProps({ show: { type: Boolean, default: false }, isEditing: { type: Boolean, default: false }, taskId: { type: String, default: '' }, parentTaskId: { type: String, default: '' }, tasks: { type: Array, default: () => [] }, currentTask: { type: Object, default: () => null } }) const emit = defineEmits(['update:show', 'task-saved']) // 表单数据 const form = reactive({ task_id: '', name: '', endpoint: '', method: '', params: {}, schedule_type: 'daily', schedule_time: '00:00', interval: 1, unit: 'hours', depends_on: [], enabled: true, sub_tasks: [] }) // 参数JSON文本和错误信息 const paramsJson = ref('{}') const paramsError = ref('') // 可用的API端点 const availableEndpoints = ref([]) // 在 script setup 部分添加 const showApiSelector = ref(false) const showDependencySelector = ref(false) const apiSearchQuery = ref('') const expandedTags = reactive({}) const methodFilter = ref('ALL') const selectedEndpoint = ref('') // 按tag对API进行分组 const groupedEndpoints = computed(() => { const groups = {} availableEndpoints.value.forEach(endpoint => { const tags = endpoint.tags && endpoint.tags.length > 0 ? endpoint.tags : ['未分类'] tags.forEach(tag => { if (!groups[tag]) { groups[tag] = [] } groups[tag].push(endpoint) }) }) return groups }) // 过滤后的分组结果 const filteredGroupedEndpoints = computed(() => { const query = apiSearchQuery.value.toLowerCase() const filtered = {} Object.entries(groupedEndpoints.value).forEach(([tag, apis]) => { const filteredApis = apis.filter(endpoint => { const matchesSearch = !query || endpoint.path.toLowerCase().includes(query) || endpoint.summary?.toLowerCase().includes(query) const matchesMethod = methodFilter.value === 'ALL' || endpoint.method === methodFilter.value return matchesSearch && matchesMethod }) if (filteredApis.length > 0) { filtered[tag] = filteredApis } }) return filtered }) // 切换tag展开状态 const toggleTagExpand = (tag) => { expandedTags[tag] = !expandedTags[tag] } // 重置搜索和展开状态 const resetSearch = () => { apiSearchQuery.value = '' methodFilter.value = 'ALL' Object.keys(groupedEndpoints.value).forEach(tag => { expandedTags[tag] = true }) } // 监听搜索框变化 watch(apiSearchQuery, (newVal) => { if (!newVal) { // 当搜索框清空时,重置所有展开状态 resetSearch() } }) // 初始化所有tag为展开状态 watch(() => showApiSelector.value, (newVal) => { if (newVal) { resetSearch() } }) // 监听选中的API端点变化 watch(selectedEndpoint, (newVal) => { if (newVal) { const endpoint = availableEndpoints.value.find(e => e.id === newVal || e.operationId === newVal || e.path === newVal) if (endpoint) { form.endpoint = endpoint.description || endpoint.path form.method = endpoint.method || 'GET' if (!form.task_id) { form.task_id = endpoint.id || endpoint.operationId || endpoint.path } if (!form.name && (endpoint.name || endpoint.summary)) { form.name = endpoint.name || endpoint.summary } } } }) // 获取任务名称 const getTaskName = (taskId) => { const endpoint = availableEndpoints.value.find(e => e.operationId === taskId || e.path === taskId) return endpoint ? `${endpoint.summary || endpoint.path} (${taskId})` : taskId } // 移除依赖任务 const removeTask = (taskId) => { form.depends_on = form.depends_on.filter(id => id !== taskId) } // 计算属性:检查表单是否有效 const isFormValid = computed(() => { // 检查基本字段 if (!form.task_id.trim() || !form.name.trim() || !form.endpoint || !form.method) { return false } // 检查调度相关字段 if (form.schedule_type === 'daily' && !form.schedule_time) { return false } if (form.schedule_type === 'interval' && (!form.interval || form.interval < 1 || !form.unit)) { return false } // 检查参数JSON格式 return paramsError.value === '' }) // 重置表单 const resetForm = () => { // 根据当前的props状态设置初始值 const initialState = { task_id: '', name: '', endpoint: '', method: '', params: {}, schedule_type: props.parentTaskId ? 'chain' : 'daily', schedule_time: '00:00', interval: 1, unit: 'hours', depends_on: props.currentTask?.depends_on ? [props.currentTask.depends_on.task_id] : [], enabled: true, sub_tasks: [] } // 使用Object.keys确保所有属性都被重置 Object.keys(form).forEach(key => { if (key === 'depends_on' && props.parentTaskId && props.currentTask) { return } form[key] = initialState[key] }) // 重置其他相关状态 selectedEndpoint.value = '' paramsJson.value = '{}' paramsError.value = '' showApiSelector.value = false showDependencySelector.value = false apiSearchQuery.value = '' methodFilter.value = 'ALL' Object.keys(expandedTags).forEach(key => { expandedTags[key] = false }) } // 监听show变化 watch(() => props.show, async (newVal) => { if (newVal) { await fetchAvailableEndpoints() if (props.isEditing && props.taskId) { await loadTaskDetail(props.taskId) } else if (!props.isEditing && props.parentTaskId) { resetForm() form.schedule_type = 'chain' // 查找父任务及其子任务 const parentTask = props.tasks.find(task => task.task_id === props.parentTaskId) if (parentTask?.sub_tasks?.length > 0) { // 如果父任务有子任务,依赖最后一个子任务 const lastSubTask = parentTask.sub_tasks[parentTask.sub_tasks.length - 1] form.depends_on = [lastSubTask.task_id] // 确保依赖任务在availableEndpoints中 if (!availableEndpoints.value.find(e => e.operationId === lastSubTask.task_id)) { availableEndpoints.value.push({ operationId: lastSubTask.task_id, summary: lastSubTask.config?.name || lastSubTask.task_id, path: lastSubTask.task_id }) } } else { // 如果父任务没有子任务,依赖父任务 form.depends_on = [props.parentTaskId] // 确保父任务在availableEndpoints中 if (!availableEndpoints.value.find(e => e.operationId === props.parentTaskId)) { availableEndpoints.value.push({ operationId: props.parentTaskId, summary: parentTask?.config?.name || props.parentTaskId, path: props.parentTaskId }) } } } else { resetForm() } } else { resetForm() emit('task-saved') } }, { immediate: true }) // 监听currentTask变化 watch(() => props.currentTask, async (newVal) => { if (props.show && !props.isEditing && props.parentTaskId && newVal) { await nextTick() setDependencyFromCurrentTask(newVal) } }) // 设置依赖关系的辅助函数 const setDependencyFromCurrentTask = (task) => { if (!task) { form.depends_on = [props.parentTaskId] return } if (task.sub_tasks?.length > 0) { // 如果主任务有子任务,依赖最后一个子任务 const lastSubTask = task.sub_tasks[task.sub_tasks.length - 1] form.depends_on = [lastSubTask.task_id] // 确保依赖任务在availableEndpoints中 if (!availableEndpoints.value.find(e => e.operationId === lastSubTask.task_id)) { availableEndpoints.value.push({ operationId: lastSubTask.task_id, summary: lastSubTask.config?.name || lastSubTask.task_id, path: lastSubTask.task_id }) } } else { // 如果主任务没有子任务,依赖主任务 form.depends_on = [props.parentTaskId] // 确保父任务在availableEndpoints中 if (!availableEndpoints.value.find(e => e.operationId === props.parentTaskId)) { availableEndpoints.value.push({ operationId: props.parentTaskId, summary: props.parentTaskId, path: props.parentTaskId }) } } } // 加载任务详情 const loadTaskDetail = async (taskId) => { try { const response = await getSchedulerTaskDetail(taskId, { include_subtasks: true }) if (response.data && response.data.status === 'success') { const taskInfo = response.data.tasks[0] if (taskInfo) { // 基本信息 form.task_id = taskInfo.task_id form.name = taskInfo.config.name form.endpoint = taskInfo.config.endpoint form.method = taskInfo.config.method form.params = taskInfo.config.params || {} form.schedule_type = taskInfo.config.schedule_type form.schedule_time = taskInfo.config.schedule_time form.enabled = taskInfo.config.enabled // 间隔执行配置 if (taskInfo.config.schedule_type === 'interval') { form.interval = taskInfo.config.interval || 1 form.unit = taskInfo.config.unit || 'hours' } // 设置依赖任务 if (taskInfo.depends_on) { form.depends_on = [taskInfo.depends_on.task_id] // 确保依赖任务在availableEndpoints中 if (!availableEndpoints.value.find(e => e.operationId === taskInfo.depends_on.task_id)) { availableEndpoints.value.push({ operationId: taskInfo.depends_on.task_id, summary: taskInfo.depends_on.name, path: taskInfo.depends_on.task_id }) } } else { form.depends_on = [] } // 加载子任务 if (taskInfo.sub_tasks) { form.sub_tasks = taskInfo.sub_tasks } } } else { showNotify({ type: 'danger', message: '获取任务详情失败: ' + (response.data?.message || '未知错误') }) } } catch (error) { showNotify({ type: 'danger', message: '获取任务详情出错: ' + (error.message || '未知错误') }) } } // 获取可用的API端点 const fetchAvailableEndpoints = async () => { try { const response = await getAvailableEndpoints() if (response.data && response.data.status === 'success') { availableEndpoints.value = response.data.endpoints || [] } else { showNotify({ type: 'danger', message: '获取API端点失败: ' + (response.data?.message || '未知错误') }) } } catch (error) { showNotify({ type: 'danger', message: '获取API端点出错: ' + (error.message || '未知错误') }) } } // 监听paramsJson变化,验证JSON格式 watch(paramsJson, (newVal) => { if (!newVal.trim()) { paramsJson.value = '{}' paramsError.value = '' return } try { JSON.parse(newVal) paramsError.value = '' } catch (error) { paramsError.value = 'JSON格式错误: ' + error.message } }) // 取消按钮 const cancel = () => { resetForm() emit('update:show', false) emit('task-saved') } // 提交表单 const submitForm = async () => { try { if (props.parentTaskId) { form.schedule_type = 'chain' } // 确保任务ID不为空 if (!form.task_id.trim()) { showNotify({ type: 'danger', message: '任务ID不能为空' }) return } console.log('开始提交任务表单:', props.isEditing ? '编辑模式' : (props.parentTaskId ? '子任务模式' : '主任务模式')) const taskData = { task_id: form.task_id.trim(), name: form.name, endpoint: form.endpoint, method: form.method, params: form.params, enabled: form.enabled } // 只有在创建新任务时才设置调度类型和依赖任务 if (!props.isEditing) { taskData.schedule_type = form.schedule_type if (form.schedule_type === 'daily') { taskData.schedule_time = form.schedule_time } else if (form.schedule_type === 'interval') { taskData.interval = form.interval taskData.unit = form.unit } if (form.depends_on.length > 0) { taskData.depends_on = { task_id: form.depends_on[0], name: getTaskName(form.depends_on[0]) } } } else { // 编辑模式下,保留原有的调度类型 taskData.schedule_type = form.schedule_type // 如果是每日任务,可以修改执行时间 if (form.schedule_type === 'daily') { taskData.schedule_time = form.schedule_time } // 注意:如果是间隔任务,不允许修改间隔时间和单位,所以这里不设置这些字段 } console.log('准备提交的任务数据:', taskData) let response if (props.isEditing) { console.log('开始更新任务:', props.taskId) response = await updateSchedulerTask(props.taskId, taskData) } else if (props.parentTaskId) { console.log('开始添加子任务:', props.parentTaskId) response = await addSubTask(props.parentTaskId, { ...taskData, schedule_type: 'chain' }) } else { console.log('开始创建主任务') response = await createSchedulerTask({ task_id: form.task_id.trim(), task_type: 'main', config: { name: form.name, endpoint: form.endpoint, method: form.method, params: form.params, schedule_type: form.schedule_type, schedule_time: form.schedule_type === 'daily' ? form.schedule_time : undefined, interval: form.schedule_type === 'interval' ? form.interval : undefined, unit: form.schedule_type === 'interval' ? form.unit : undefined, enabled: form.enabled }, depends_on: taskData.depends_on }) } console.log('任务操作响应:', response.data) if (response.data && response.data.status === 'success') { const successMessage = props.isEditing ? '更新成功' : props.parentTaskId ? '子任务创建成功' : '创建成功' console.log('任务操作成功:', successMessage) showNotify({ type: 'success', message: successMessage }) emit('task-saved') emit('update:show', false) resetForm() } else { const errorMessage = (props.isEditing ? '更新失败: ' : props.parentTaskId ? '创建子任务失败: ' : '创建失败: ') + (response.data?.message || '未知错误') console.error('任务操作失败:', errorMessage) showNotify({ type: 'danger', message: errorMessage }) } } catch (error) { const errorMessage = (props.isEditing ? '更新出错: ' : props.parentTaskId ? '创建子任务出错: ' : '创建出错: ') + (error.message || '未知错误') console.error('任务操作异常:', errorMessage, error) showNotify({ type: 'danger', message: errorMessage }) } } // 添加handleApiSelect函数 const handleApiSelect = (endpoint) => { selectedEndpoint.value = endpoint.id } // 在 script setup 中添加计算属性 const getDialogTitle = computed(() => { if (props.isEditing) return '编辑任务' if (props.parentTaskId) return '创建子任务' return '创建主任务' }) const getFormTitle = computed(() => { if (props.isEditing) return '编辑任务信息' if (props.parentTaskId) return '创建新子任务' return '创建新主任务' }) const getFormDescription = computed(() => { if (props.isEditing) return '修改任务配置信息' if (props.parentTaskId) return '填写以下信息创建新的子任务' return '填写以下信息创建新的主任务' }) const getSubmitButtonText = computed(() => { if (props.isEditing) return '保存' if (props.parentTaskId) return '创建子任务' return '创建主任务' }) // 监听props变化,确保状态同步 watch(() => props.parentTaskId, (newVal) => { if (props.show) { // 如果弹窗是打开的,根据parentTaskId的变化更新schedule_type form.schedule_type = newVal ? 'chain' : 'daily' } }) watch(() => props.isEditing, (newVal) => { if (props.show && newVal && props.taskId) { // 如果弹窗是打开的且切换到编辑模式,加载任务详情 loadTaskDetail(props.taskId) } }) </script> <script> export default { name: 'TaskForm' } </script> <style scoped> .task-form-dialog :deep(.van-dialog) { max-height: 85vh; overflow: hidden; display: flex; flex-direction: column; } .task-form-dialog :deep(.van-dialog__header) { flex-shrink: 0; padding: 12px 16px; font-size: 14px; } /* 自定义滚动条样式 */ .custom-scrollbar { scrollbar-width: thin; scrollbar-color: #fb7299 #f3f4f6; } .custom-scrollbar::-webkit-scrollbar { width: 4px; } .custom-scrollbar::-webkit-scrollbar-track { background: #f3f4f6; border-radius: 2px; } .custom-scrollbar::-webkit-scrollbar-thumb { background-color: #fb7299; border-radius: 2px; } </style>
281677160/openwrt-package
13,780
luci-app-passwall2/luasrc/view/passwall2/node_list/node_list.htm
<% local api = require "luci.passwall2.api" local uci = api.uci local default_node_type = "" local shunt_rule_list = {} local node = api.uci_get_type("global", "node") if node then local node_type = api.uci_get_type_id(node, "type") local node_protocol = api.uci_get_type_id(node, "protocol") if node_type == "Xray" and node_protocol == "_shunt" then default_node_type = node_protocol uci:foreach("passwall2", "shunt_rules", function(e) if e[".name"] and e.remarks then shunt_rule_list[#shunt_rule_list + 1] = e end end) end end -%> <style> table th, .table .th { text-align: center; } table td, .table .td { text-align: center; /* white-space: nowrap; */ word-break: keep-all; } #set_node_div { display: none; width: 30rem; position: fixed; top:50%; padding-top: 30px; z-index: 99; text-align: center; background: white; box-shadow: darkgrey 10px 10px 30px 5px; } ._now_use { color: red !important; } ._now_use_bg { background: #5e72e445 !important; } .ping a:hover{ text-decoration : underline; } @media (prefers-color-scheme: dark) { ._now_use_bg { background: #4a90e2 !important; } } </style> <script type="text/javascript"> //<![CDATA[ let auto_detection_time = "<%=api.uci_get_type("global_other", "auto_detection_time", "0")%>" var node_list = {}; var node_count = 0; var ajax = { post: function(url, data, fn_success, timeout, fn_timeout) { var xhr = new XMLHttpRequest(); var code = ajax.encode(data); xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); if (timeout && timeout > 1000) { xhr.timeout = timeout; } if (fn_timeout) { xhr.ontimeout = function() { fn_timeout(xhr); } } xhr.onreadystatechange = function() { if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) { var json = null; if (xhr.getResponseHeader("Content-Type") == "application/json") { try { json = eval('(' + xhr.responseText + ')'); } catch(e) { json = null; } } fn_success(xhr, json); } }; xhr.send(code); }, encode: function(obj) { obj = obj ? obj : { }; obj['_'] = Math.random(); if (typeof obj == 'object') { var code = ''; var self = this; for (var k in obj) code += (code ? '&' : '') + k + '=' + encodeURIComponent(obj[k]); return code; } return obj; } } function copy_node(cbi_id) { window.location.href = '<%=api.url("copy_node")%>' + "?section=" + cbi_id; } var section = ""; function open_set_node_div(cbi_id) { section = cbi_id; document.getElementById("set_node_div").style.display="block"; var node_name = document.getElementById("cbid.passwall2." + cbi_id + ".remarks").value; document.getElementById("set_node_name").innerHTML = node_name; } function close_set_node_div() { document.getElementById("set_node_div").style.display="none"; document.getElementById("set_node_name").innerHTML = ""; } function _cbi_row_top(id) { var dom = document.getElementById("cbi-passwall2-" + id); if (dom) { var trs = document.getElementById("cbi-passwall2-nodes").getElementsByClassName("cbi-section-table-row"); if (trs && trs.length > 0) { for (var i = 0; i < trs.length; i++) { var up = dom.getElementsByClassName("cbi-button-up"); if (up) { cbi_row_swap(up[0], true, 'cbi.sts.passwall2.nodes'); } } } } } function checked_all_node(btn) { var doms = document.getElementById("cbi-passwall2-nodes").getElementsByClassName("nodes_select"); if (doms && doms.length > 0) { for (var i = 0 ; i < doms.length; i++) { doms[i].checked = true; } btn.value = "<%:DeSelect all%>"; btn.setAttribute("onclick", "dechecked_all_node(this)"); } } function dechecked_all_node(btn) { var doms = document.getElementById("cbi-passwall2-nodes").getElementsByClassName("nodes_select"); if (doms && doms.length > 0) { for (var i = 0 ; i < doms.length; i++) { doms[i].checked = false; } btn.value = "<%:Select all%>"; btn.setAttribute("onclick", "checked_all_node(this)"); } } function delete_select_nodes() { var ids = []; var doms = document.getElementById("cbi-passwall2-nodes").getElementsByClassName("nodes_select"); if (doms && doms.length > 0) { for (var i = 0 ; i < doms.length; i++) { if (doms[i].checked) { ids.push(doms[i].getAttribute("cbid")) } } if (ids.length > 0) { if (confirm('<%:Are you sure to delete select nodes?%>') == true){ XHR.get('<%=api.url("delete_select_nodes")%>', { ids: ids.join() }, function(x, data) { if (x && x.status == 200) { /* for (var i = 0 ; i < ids.length; i++) { var box = document.getElementById("cbi-passwall2-" + ids[i]); box.remove(); } */ window.location.href = '<%=api.url("node_list")%>'; } else { alert("<%:Error%>"); } }); } } } if (ids.length <= 0) { alert("<%:You no select nodes !%>"); } } function set_node(type, config) { if (confirm('<%:Are you sure set this server?%>')==true){ window.location.href = '<%=api.url("set_node")%>?type=' + type + '&config=' + config + '&section=' + section; } } function get_address_full(id) { try { var address = document.getElementById("cbid.passwall2." + id + ".address").value; var port = document.getElementById("cbid.passwall2." + id + ".port").value; } catch(err){} //判断是否含有汉字 var reg = new RegExp("[\\u4E00-\\u9FFF]+","g"); if ((address != null && address != "") && (port != null && port != "") && reg.test(address) == false) { return { address: address, port: port }; } else { return null; } } //获取当前使用的节点 function get_now_use_node() { XHR.get('<%=api.url("get_now_use_node")%>', null, function(x, result) { var id = result["global"]; if (id) { var dom = document.getElementById("cbi-passwall2-" + id); if (dom) { dom.title = "当前使用的节点"; dom.classList.add("_now_use_bg"); //var v = "<a style='color: red'>当前节点:</a>" + document.getElementById("cbid.passwall2." + id + ".remarks").value; //document.getElementById("cbi-passwall2-" + id + "-remarks").innerHTML = v; var dom_remarks = document.getElementById("cbi-passwall2-" + id + "-remarks"); if (dom_remarks) { dom_remarks.classList.add("_now_use"); } } } } ); } function urltest_node(cbi_id, dom) { if (cbi_id != null) { dom.onclick = null dom.innerText = "<%:Check...%>"; XHR.get('<%=api.url("urltest_node")%>', { id: cbi_id }, function(x, result) { if(x && x.status == 200) { if (result.use_time == null || result.use_time.trim() == "") { dom.outerHTML = "<font style='color:red'><%:Timeout%></font>"; } else { var color = "red"; var use_time = result.use_time; use_time = parseInt(use_time) + 1; if (use_time < 1000) { color = "green"; } else if (use_time < 2000) { color = "#fb9a05"; } else { color = "red"; } dom.outerHTML = "<font style='color:" + color + "'>" + use_time + " ms" + "</font>"; } } else { dom.outerHTML = "<font style='color:red'><%:Error%></font>"; } } ); } } function ping_node(cbi_id, dom, type) { var full = get_address_full(cbi_id); if (full != null) { dom.onclick = null dom.innerText = "<%:Check...%>"; XHR.get('<%=api.url("ping_node")%>', { address: full.address, port: full.port, type: type }, function(x, result) { if(x && x.status == 200) { if (result.ping == null || result.ping.trim() == "") { dom.outerHTML = "<font style='color:red'><%:Timeout%></font>"; } else { var ping = parseInt(result.ping); if (ping < 100) dom.outerHTML = "<font style='color:green'>" + result.ping + " ms" + "</font>"; else if (ping < 200) dom.outerHTML = "<font style='color:#fb9a05'>" + result.ping + " ms" + "</font>"; else if (ping >= 200) dom.outerHTML = "<font style='color:red'>" + result.ping + " ms" + "</font>"; } } } ); } } /* 自动Ping */ function pingAllNodes() { if (auto_detection_time == "icmp" || auto_detection_time == "tcping") { var nodes = []; const ping_value = document.getElementsByClassName(auto_detection_time == "tcping" ? 'tcping_value' : 'ping_value'); for (var i = 0; i < ping_value.length; i++) { var cbi_id = ping_value[i].getAttribute("cbiid"); var full = get_address_full(cbi_id); if (full != null) { var flag = false; //当有多个相同地址和端口时合在一起 for (var j = 0; j < nodes.length; j++) { if (nodes[j].address == full.address && nodes[j].port == full.port) { nodes[j].indexs = nodes[j].indexs + "," + i; flag = true; break; } } if (flag) continue; nodes.push({ indexs: i + "", address: full.address, port: full.port }); } } const _xhr = (index) => { return new Promise((res) => { const dom = nodes[index]; if (!dom) res() ajax.post('<%=api.url("ping_node")%>', { index: dom.indexs, address: dom.address, port: dom.port, type: auto_detection_time }, function(x, result) { if (x && x.status == 200) { var strs = dom.indexs.split(","); for (var i = 0; i < strs.length; i++) { if (result.ping == null || result.ping.trim() == "") { ping_value[strs[i]].innerHTML = "<font style='color:red'><%:Timeout%></font>"; } else { var ping = parseInt(result.ping); if (ping < 100) ping_value[strs[i]].innerHTML = "<font style='color:green'>" + result.ping + " ms" + "</font>"; else if (ping < 200) ping_value[strs[i]].innerHTML = "<font style='color:#fb9a05'>" + result.ping + " ms" + "</font>"; else if (ping >= 200) ping_value[strs[i]].innerHTML = "<font style='color:red'>" + result.ping + " ms" + "</font>"; } } } res(); }, 5000, function(x) { var strs = dom.indexs.split(","); for (var i = 0; i < strs.length; i++) { ping_value[strs[i]].innerHTML = "<font style='color:red'><%:Timeout%></font>"; } res(); } ); }) } let task = -1; const thread = () => { task = task + 1 if (nodes[task]) { _xhr(task).then(thread); } } for (let i = 0; i < 20; i++) { thread() } } } var edit_btn = document.getElementById("cbi-passwall2-nodes").getElementsByClassName("cbi-button cbi-button-edit"); for (var i = 0; i < edit_btn.length; i++) { try { var onclick_str = edit_btn[i].getAttribute("onclick"); var id = onclick_str.substring(onclick_str.lastIndexOf('/') + 1, onclick_str.length - 1); var td = edit_btn[i].parentNode; var new_div = ""; //添加"勾选"框 new_div += '<input class="cbi-input-checkbox nodes_select" type="checkbox" cbid="' + id + '" />&nbsp;&nbsp;'; //添加"置顶"按钮 new_div += '<input class="btn cbi-button" type="button" value="<%:To Top%>" onclick="_cbi_row_top(\'' + id + '\')"/>&nbsp;&nbsp;'; //添加"应用"按钮 new_div += '<input class="btn cbi-button cbi-button-apply" type="button" value="<%:Use%>" id="apply_' + id + '" onclick="open_set_node_div(\'' + id + '\')"/>&nbsp;&nbsp;'; //添加"复制"按钮 new_div += '<input class="btn cbi-button cbi-button-add" type="button" value="<%:Copy%>" onclick="copy_node(\'' + id + '\')"/>&nbsp;&nbsp;'; td.innerHTML = new_div + td.innerHTML; var obj = {}; obj.id = id; obj.type = document.getElementById("cbid.passwall2." + id + ".type").value; var address_dom = document.getElementById("cbid.passwall2." + id + ".address"); var port_dom = document.getElementById("cbid.passwall2." + id + ".port"); if (address_dom && port_dom) { obj.address = address_dom.value; obj.port = port_dom.value; } node_count++; var add_from = document.getElementById("cbid.passwall2." + id + ".add_from").value; if (node_list[add_from]) node_list[add_from].push(obj); else node_list[add_from] = []; } catch(err) { console.error(err); } } get_now_use_node(); if (true) { var str = ""; for (var add_from in node_list) { var num = node_list[add_from].length + 1; if (add_from == "") { add_from = "<%:Self add%>"; } str += add_from + " " + "<%:Node num%>: <a style='color: red'>" + num + "</a>&nbsp&nbsp&nbsp"; } document.getElementById("div_node_count").innerHTML = "<div style='margin-top:5px'>" + str + "</div>"; } //UI渲染完成后再自动Ping window.onload = function () { setTimeout(function () { pingAllNodes(); }, 800); }; //]]> </script> <div style="display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; -webkit-justify-content: center; justify-content: center;"> <div id="set_node_div"> <div class="cbi-value"><%:You choose node is:%><a style="color: red" id="set_node_name"></a></div> <div class="cbi-value"> <%- if default_node_type == "_shunt" then for i, v in ipairs(shunt_rule_list) do -%> <input class="btn cbi-button cbi-button-edit" type="button" onclick="set_node('<%=node%>', '<%=v[".name"]%>')" value="<%=v.remarks%>" /> <%- end -%> <% else %> <input class="btn cbi-button cbi-button-edit" type="button" onclick="set_node('@global[0]', 'node')" value="<%:Node%>" /> <% end %> <input class="btn cbi-button cbi-button-remove" type="button" onclick="close_set_node_div()" value="<%:Close%>" /> </div> </div> </div>
2881099/FreeSql.AdminLTE
2,144
Examples/net80_blazor/Infrastructure/Files/FileSize.cs
 using System.ComponentModel; namespace FreeSql.AdminLTE.Infrastructure.Files; public enum FileSizeUnit { /// <summary> /// 字节 /// </summary> [Description("B")] Byte, /// <summary> /// K字节 /// </summary> [Description("KB")] K, /// <summary> /// M字节 /// </summary> [Description("MB")] M, /// <summary> /// G字节 /// </summary> [Description("GB")] G } /// <summary> /// 文件大小 /// </summary> public struct FileSize { /// <summary> /// 初始化文件大小 /// </summary> /// <param name="size">文件大小</param> /// <param name="unit">文件大小单位</param> public FileSize(long size, FileSizeUnit unit = FileSizeUnit.Byte) { switch (unit) { case FileSizeUnit.K: Size = size * 1024; break; case FileSizeUnit.M: Size = size * 1024 * 1024; break; case FileSizeUnit.G: Size = size * 1024 * 1024 * 1024; break; default: Size = size; break; } } /// <summary> /// 文件字节长度 /// </summary> public long Size { get; } /// <summary> /// 获取文件大小,单位:字节 /// </summary> public long GetSize() { return Size; } /// <summary> /// 获取文件大小,单位:K /// </summary> public double GetSizeByK() { return Math.Round(Size / 1024.0, 2); } /// <summary> /// 获取文件大小,单位:M /// </summary> public double GetSizeByM() { return Math.Round(Size / 1024.0 / 1024.0, 2); } /// <summary> /// 获取文件大小,单位:G /// </summary> public double GetSizeByG() { return Math.Round(Size / 1024.0 / 1024.0 / 1024.0, 2); } /// <summary> /// 输出描述 /// </summary> public override string ToString() { if (Size >= 1024 * 1024 * 1024) return $"{GetSizeByG()} {FileSizeUnit.G.ToDescription()}"; if (Size >= 1024 * 1024) return $"{GetSizeByM()} {FileSizeUnit.M.ToDescription()}"; if (Size >= 1024) return $"{GetSizeByK()} {FileSizeUnit.K.ToDescription()}"; return $"{Size} {FileSizeUnit.Byte.ToDescription()}"; } }
2881099/FreeSql.AdminLTE
1,740
Examples/net80_blazor/Infrastructure/Files/FileInfo.cs
namespace FreeSql.AdminLTE.Infrastructure.Files; /// <summary> /// 文件信息 /// </summary> public class FileInfo { public FileInfo() { } /// <summary> /// 初始化文件信息 /// </summary> /// <param name="fileName">文件名称</param> /// <param name="size">大小</param> public FileInfo(string fileName, long size = 0L) { FileName = fileName; Size = new FileSize(size); Extension = System.IO.Path.GetExtension(FileName)?.TrimStart('.'); } /// <summary> /// 上传路径 /// </summary> public string UploadPath { get; set; } /// <summary> /// 请求路径 /// </summary> public string RequestPath { get; set; } /// <summary> /// 相对路径 /// </summary> public string RelativePath { get; set; } /// <summary> /// 文件名 /// </summary> public string FileName { get; set; } /// <summary> /// 保存名 /// </summary> public string SaveName { get; set; } /// <summary> /// 文件大小 /// </summary> public FileSize Size { get; set; } /// <summary> /// 扩展名 /// </summary> public string Extension { get; set; } /// <summary> /// 文件目录 /// </summary> public string FileDirectory => Path.Combine(UploadPath, RelativePath).Replace(@"\", "/"); /// <summary> /// 文件请求路径 /// </summary> public string FileRequestPath => Path.Combine(RequestPath, RelativePath, SaveName).Replace(@"\", "/"); /// <summary> /// 文件相对路径 /// </summary> public string FileRelativePath => Path.Combine(RelativePath, SaveName).Replace(@"\", "/"); /// <summary> /// 文件路径 /// </summary> public string FilePath => Path.Combine(UploadPath, RelativePath, SaveName).Replace(@"\", "/"); }
2977094657/BiliHistoryFrontend
10,116
src/components/tailwind/dynamic/DynamicCardNormal.vue
<template> <div class="border rounded-lg bg-white overflow-hidden"> <!-- 头部:头像 + 名称 + 时间 + 动态链接 --> <div class="flex items-center px-3 py-2"> <img v-if="faceUrl" :src="faceUrl" class="w-6 h-6 rounded-full object-cover border" alt="face" /> <div class="ml-2 min-w-0"> <div class="text-sm font-medium truncate">{{ item.author_name || `UID ${item.host_mid || ''}` }}</div> <div class="text-[11px] text-gray-500 truncate">{{ formattedTime }}</div> </div> <button v-if="item.id_str" type="button" class="ml-auto text-[11px] text-[#fb7299] hover:underline" @click="openLink(opusUrl)" >查看动态</button> </div> <!-- 主体:配文/标题内容 + 图片/实况九宫格(如有) --> <div class="px-3 pb-3"> <!-- DYNAMIC_TYPE_DRAW: 展示 opus 标题与摘要 --> <template v-if="isDraw"> <div class="text-sm font-semibold text-gray-900 leading-6" v-if="drawTitle" >{{ drawTitle }}</div> <div class="mt-1 text-sm text-gray-700 leading-6" v-if="drawSummary" > <span class="whitespace-pre-wrap"> <template v-for="(seg, i) in parsedSummary" :key="i"> <span v-if="seg.type==='text'">{{ seg.text }}</span> <img v-else :src="seg.url" :alt="seg.name" class="emoji emoji-lg inline-block align-text-bottom cursor-zoom-in hover:opacity-90 transition" role="button" tabindex="0" title="Click to preview" @click.stop="openPreview('image', seg.url)" @keydown.enter.stop="openPreview('image', seg.url)" /> </template> </span> </div> </template> <!-- 其他类型:展示 txt(解析表情) --> <div v-else-if="item.txt" role="link" tabindex="0" @click="openLink(opusUrl)" @keydown.enter="openLink(opusUrl)" class="text-sm text-gray-800 leading-6 hover:underline cursor-pointer" > <span class="whitespace-pre-wrap"> <template v-for="(seg, i) in parsedTxt" :key="'t'+i"> <span v-if="seg.type==='text'">{{ seg.text }}</span> <img v-else :src="seg.url" :alt="seg.name" class="emoji emoji-lg inline-block align-text-bottom cursor-zoom-in hover:opacity-90 transition" role="button" tabindex="0" title="Click to preview" @click.stop="openPreview('image', seg.url)" @keydown.enter.stop="openPreview('image', seg.url)" /> </template> </span> </div> <div v-if="displayMedias.length" class="mt-2 grid gap-1 md:gap-2 grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6"> <template v-for="(m, idx) in displayMedias" :key="idx"> <!-- 普通图片 --> <div v-if="m.kind==='image'" class="relative rounded-md overflow-hidden hover:opacity-90 cursor-pointer h-28 sm:h-32 md:h-36" role="button" tabindex="0" @click="openPreview('image', m.url)" @keydown.enter="openPreview('image', m.url)"> <img :src="m.url" class="block w-full h-full object-cover" /> </div> <!-- 实况照片(悬停播放) --> <div v-else class="relative rounded-md overflow-hidden hover:opacity-90 cursor-pointer h-28 sm:h-32 md:h-36" role="button" tabindex="0" @mouseenter="handleLiveEnter(idx)" @mouseleave="handleLiveLeave(idx)" @click="openPreview('video', m.videoUrl, m.coverUrl)" @keydown.enter="openPreview('video', m.videoUrl, m.coverUrl)"> <video :poster="m.coverUrl" :src="m.videoUrl" muted playsinline loop class="absolute inset-0 w-full h-full object-cover" :ref="el => setLiveRef(idx, el)" ></video> <!-- 右下角 实况 徽标 --> <div class="absolute bottom-1 right-1 px-1.5 py-0.5 bg-black/60 text-white text-[10px] flex items-center rounded"> <img src="/live.svg" class="w-3 h-3 mr-1 filter invert" alt="live" /> <span>实况</span> </div> </div> </template> </div> </div> <!-- 预览弹层 --> <Teleport to="body"> <div v-if="showPreview" class="fixed inset-0 z-50 bg-black/80 flex items-center justify-center" @click="closePreview"> <div class="max-w-[95vw] max-h-[90vh] relative" @click.stop> <img v-if="previewType==='image'" :src="previewSrc" class="max-w-[95vw] max-h-[90vh] object-contain rounded-md" /> <video v-else :src="previewSrc" :poster="previewPoster" controls autoplay loop muted class="max-w-[95vw] max-h-[90vh] rounded-md"></video> <button class="absolute -top-3 -right-3 w-8 h-8 rounded-full bg-black/70 text-white flex items-center justify-center" @click="closePreview">×</button> </div> </div> </Teleport> </div> </template> <script setup> import { computed, ref } from 'vue' import { openInBrowser } from '@/utils/openUrl' import { toStaticUrl } from '@/utils/imageUrl' const props = defineProps({ item: { type: Object, required: true }, faceUrl: { type: String, default: '' } }) // 是否图文动态 const isDraw = computed(() => String(props.item?.type || '') === 'DYNAMIC_TYPE_DRAW') const drawTitle = computed(() => props.item?.opus_title || '') const drawSummary = computed(() => props.item?.opus_summary_text || '') // 归一化扩展名检查 const isVideoPath = (p) => /\.mp4$/i.test(String(p || '').replace(/\\/g, '/')) const isImagePath = (p) => /\.(png|jpe?g|gif|webp)$/i.test(String(p || '').replace(/\\/g, '/')) const getNameFromPath = (p) => { const filename = String(p || '').split(/[/\\]/).pop() || '' const decoded = decodeURIComponent(filename) return decoded.replace(/\.[^.]+$/, '') } // 从摘要中提取 [xxx] 表情名集合 const extractEmojiNames = (text) => { const set = new Set() if (!text) return set const re = /\[([^\[\]]+?)\]/g let m while ((m = re.exec(text)) !== null) { set.add(m[1]) } return set } const emojiNamesFromSummary = computed(() => extractEmojiNames(drawSummary.value)) const emojiNamesFromTxt = computed(() => extractEmojiNames(props.item?.txt || '')) const allEmojiNames = computed(() => new Set([...emojiNamesFromSummary.value, ...emojiNamesFromTxt.value])) // 构建 emoji 名称到图片URL的映射(仅使用摘要中出现过的表情名) const emojiMap = computed(() => { const map = {} const ml = Array.isArray(props.item?.media_locals) ? props.item.media_locals : [] for (const p of ml) { if (!isImagePath(p)) continue const name = getNameFromPath(p) if (/^live_/i.test(name)) continue if (allEmojiNames.value.has(name)) { map[name] = toStaticUrl(p) } } return map }) // 将摘要解析为文本/emoji 片段 const parseWithEmoji = (text) => { const map = emojiMap.value || {} if (!text) return [] const result = [] const re = /\[([^\[\]]+?)\]/g let last = 0 let m while ((m = re.exec(text)) !== null) { const idx = m.index const raw = m[0] const name = m[1] if (idx > last) { result.push({ type: 'text', text: text.slice(last, idx) }) } if (map[name]) { result.push({ type: 'emoji', name, url: map[name] }) } else { result.push({ type: 'text', text: raw }) } last = idx + raw.length } if (last < text.length) { result.push({ type: 'text', text: text.slice(last) }) } return result } const parsedSummary = computed(() => { const text = drawSummary.value || '' return parseWithEmoji(text) }) const parsedTxt = computed(() => parseWithEmoji(props.item?.txt || '')) // 构造展示媒体:普通图片 + 实况照片(由 live_media_locals 配对 png+mp4) const displayMedias = computed(() => { const medias = [] const ml = Array.isArray(props.item?.media_locals) ? props.item.media_locals : [] for (const p of ml) { if (isImagePath(p) && !/live_/i.test(p)) { const name = getNameFromPath(p) // 过滤掉作为emoji使用的图片 if (!allEmojiNames.value.has(name)) { medias.push({ kind: 'image', url: toStaticUrl(p) }) } } } const live = Array.isArray(props.item?.live_media_locals) ? props.item.live_media_locals : [] if (live.length) { const covers = live.filter(isImagePath) const videos = live.filter(isVideoPath) const n = Math.min(covers.length, videos.length, 9) for (let i = 0; i < n; i++) { medias.push({ kind: 'live', coverUrl: toStaticUrl(covers[i]), videoUrl: toStaticUrl(videos[i]) }) } } return medias.slice(0, 12) // 限制单条最多展示若干项 }) // 网格固定为每行最多6列(随断点 3/4/5/6 列) const formattedTime = computed(() => { const ts = props.item?.publish_ts if (!ts) return '-' try { const d = new Date(ts * 1000) const pad = (n) => String(n).padStart(2, '0') return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}` } catch { return String(ts) } }) const opusUrl = computed(() => props.item?.id_str ? `https://www.bilibili.com/opus/${props.item.id_str}` : '#') const openLink = (url) => { try { openInBrowser(url) } catch { window.open(url, '_blank') } } // 实况播放控制 const liveRefs = ref({}) const setLiveRef = (idx, el) => { if (!liveRefs.value) liveRefs.value = {} if (el) liveRefs.value[idx] = el else delete liveRefs.value[idx] } const handleLiveEnter = (idx) => { const v = liveRefs.value?.[idx] if (v) { try { v.play() } catch (e) {} } } const handleLiveLeave = (idx) => { const v = liveRefs.value?.[idx] if (v) { try { v.pause(); v.currentTime = 0 } catch (e) {} } } // 预览逻辑 const showPreview = ref(false) const previewType = ref('image') const previewSrc = ref('') const previewPoster = ref('') const openPreview = (type, src, poster = '') => { previewType.value = type previewSrc.value = src previewPoster.value = poster showPreview.value = true } const closePreview = () => { showPreview.value = false } </script> <style scoped> /* 使emoji图片与文字同高 */ .emoji { height: 1em; width: 1em; margin: 0 2px; } .emoji-lg { height: 52px; width: 52px; } </style>
2977094657/BiliHistoryFrontend
3,448
src/components/tailwind/dynamic/DynamicCardVideo.vue
<template> <div class="border rounded-lg bg-white overflow-hidden"> <!-- 头部:头像 + 名称 + 时间 + 动态链接 --> <div class="flex items-center px-3 py-2"> <img v-if="faceUrl" :src="faceUrl" class="w-6 h-6 rounded-full object-cover border" alt="face" /> <div class="ml-2 min-w-0"> <div class="text-sm font-medium truncate">{{ item.author_name || `UID ${item.host_mid || ''}` }}</div> <div class="text-[11px] text-gray-500 truncate">{{ formattedTime }}</div> </div> <button v-if="item.id_str" type="button" class="ml-auto text-[11px] text-[#fb7299] hover:underline" @click="openLink(opusUrl)" >查看动态</button> </div> <!-- 主体:封面(更小) + 文本,封面/标题可跳转视频 --> <div class="px-3 pb-3"> <div class="flex items-start"> <div class="relative w-40 sm:w-48 md:w-56 flex-shrink-0 rounded-md overflow-hidden hover:opacity-90 cursor-pointer" role="link" tabindex="0" @click="openLink(videoUrl)" @keydown.enter="openLink(videoUrl)" > <div class="w-full" style="aspect-ratio: 16 / 9"> <img v-if="coverUrl" :src="coverUrl" class="block w-full h-full object-cover" alt="cover" /> <div v-else class="w-full h-full flex items-center justify-center text-gray-400 text-xs">no cover</div> </div> <div v-if="item.bvid" class="absolute bottom-1 left-1 text-[10px] bg-black/60 text-white px-1.5 py-0.5 rounded">{{ item.bvid }}</div> </div> <div class="ml-3 flex-1 min-w-0"> <div role="link" tabindex="0" @click="openLink(videoUrl)" @keydown.enter="openLink(videoUrl)" class="text-sm font-semibold leading-5 line-clamp-2 hover:underline cursor-pointer" :title="item.title || item.txt || ''" >{{ item.title || item.txt || '视频动态' }}</div> <div v-if="item.desc || item.txt" class="text-xs text-gray-600 mt-1 line-clamp-2">{{ item.desc || item.txt }}</div> </div> </div> </div> </div> </template> <script setup> import { computed } from 'vue' import { openInBrowser } from '@/utils/openUrl' import { toStaticUrl } from '@/utils/imageUrl' const props = defineProps({ item: { type: Object, required: true }, faceUrl: { type: String, default: '' } }) const coverUrl = computed(() => { const it = props.item || {} if (it.cover) return toStaticUrl(it.cover) const list = Array.isArray(it.media_locals) ? it.media_locals : [] if (list.length) return toStaticUrl(list[0]) return '' }) const formattedTime = computed(() => { const ts = props.item?.publish_ts if (!ts) return '-' try { const d = new Date(ts * 1000) const pad = (n) => String(n).padStart(2, '0') return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}` } catch { return String(ts) } }) const opusUrl = computed(() => props.item?.id_str ? `https://www.bilibili.com/opus/${props.item.id_str}` : '#') const videoUrl = computed(() => props.item?.bvid ? `https://www.bilibili.com/video/${props.item.bvid}` : opusUrl.value) const openLink = (url) => { try { openInBrowser(url) } catch { window.open(url, '_blank') } } </script> <style scoped> .line-clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } </style>
2977094657/BiliHistoryFrontend
1,202
src/components/tailwind/analytics/layout/AnalyticsLayout.vue
<!-- 年度总结通用布局组件 --> <template> <div class="absolute inset-0 bg-gradient-to-b from-[#fef6f9] to-[#fff9fa] dark:from-[#2c2c2c] dark:to-[#1f1f1f] overflow-hidden"> <!-- 背景装饰 --> <div class="absolute inset-0 overflow-hidden pointer-events-none"> <div class="absolute -top-40 -right-40 w-96 h-96 bg-gradient-to-br from-[#fb7299]/10 to-[#fc9b7a]/10 rounded-full blur-3xl animate-float"></div> <div class="absolute -bottom-20 -left-20 w-80 h-80 bg-gradient-to-tr from-[#fc9b7a]/10 to-[#fb7299]/10 rounded-full blur-3xl animate-float-delay"></div> </div> <div class="relative min-h-screen flex items-center justify-center"> <div class="max-w-7xl w-full mx-auto px-8"> <slot></slot> </div> </div> </div> </template> <script setup> // 无需额外的逻辑 </script> <style> @keyframes float { 0%, 100% { transform: translate(0, 0); } 50% { transform: translate(-20px, 20px); } } @keyframes float-delay { 0%, 100% { transform: translate(0, 0); } 50% { transform: translate(20px, -20px); } } .animate-float { animation: float 8s ease-in-out infinite; } .animate-float-delay { animation: float 8s ease-in-out infinite; animation-delay: -4s; } </style>
298582245/wqwl_qinglong
7,230
wqwl_捂碳星球.js
/** * 脚本:wqwl_捂碳星球.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序捂碳星球旧衣服回收, * 环境变量:wqwl_wtxq,多个换行或新建多个变量 * 环境变量描述:抓包Headers下的authorization,格式例如:authorization#备注1(authorization去掉Bearer ) * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 0 * * * 一天一次即可 */ /** * 没必要玩,签到第3天开始要每天邀请一个人才能签到,而且才0.1,为什么要玩呢? * 我发出来是因为我写了 */ const axios = require('axios'); const fs = require('fs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || true; //并发数,默认3 let bfs = process.env["wqwl_bfs"] || 3; // 是否通知 let isNotify = true; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_wtxq'; //脚本名称 const name = '微信小程序捂碳星球旧衣服回收' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } class Task { constructor(ck) { this.index = index++; this.baseURL = 'https://wt.api.5tan.com/api' this.ck = ck } async init(ck) { const ckData = ck.split('#') if (ckData.length < 1) { return this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 1) { this.remark = ckData[0].slice(0, 8); } else { this.remark = ckData[1]; } this.auth = ckData[0]; this.headers = { "accept": "*/*", "accept-language": "zh-CN,zh;q=0.9", "authorization": `Bearer ${this.auth}`, "content-type": "application/json", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "xweb_xhr": "1", "Referer": "https://servicewechat.com/wx54c4768a6050a90e/218/page-frame.html", "Referrer-Policy": "unsafe-url" } if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } } // 签到 async sign() { try { if (!(this.auth)) return const options = { url: `${this.baseURL}/signin/addSignIn`, headers: this.headers, method: 'POST', data: JSON.stringify({ platform: 1 }) } const result = await wqwlkj.request(options, this.proxy) //console.log(JSON.stringify(result)) if (result.code === 200) { if (result?.data?.title == '签到成功~') this.sendMessage(`✅签到成功`, true) else this.sendMessage(`❌签到失败,${result?.data?.content}`, true) } else { this.sendMessage(`❌签到失败,${result.msg}`, true) } } catch (e) { throw new Error(`❌请求签到接口失败,${e.message}`) } } // 获取用户信息 async getUserInfo() { try { if (!(this.auth)) return const options = { url: `${this.baseURL}/user/index?platform=1`, headers: this.headers, method: 'GET', } const result = await wqwlkj.request(options, this.proxy) if (result.code === 200) { this.sendMessage(`🙍用户【${result.data.nick_name}】余额:${result.data.money}元`, true) } else { this.sendMessage(`❌获取用户信息失败,${result.msg}`, true) } } catch (e) { throw new Error(`❌请求用户信息接口失败,${e.message}`) } } async main() { await this.init(this.ck) await wqwlkj.sleep(wqwlkj.getRandom(1, 3)) await this.sign() await wqwlkj.sleep(wqwlkj.getRandom(1, 3)) await this.getUserInfo() await wqwlkj.sleep(wqwlkj.getRandom(1, 3)) } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const tasks = batch.map(token => new Task(token).main()); await Promise.all(tasks); await wqwlkj.sleep(wqwlkj.getRandom(1, 3)) } console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
294coder/Efficient-MIF
2,515
Pansharpening_Hyper_SR_Matlab_Test_Package/PNN/input_preparation.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Input preparation % Interface: % I_in = input_preparation(I_MS_LR,I_PAN,model) % Inputs: % EXP: 4- or 8-band multispectral image upsampled to the PAN scale; % I_MS_LR: MS image donwgraded for Wald Protocol; % I_PAN: PAN image downgraded for Wald Protocol; % model: Struct with training details of pretrained network. % Output: % I_in: Stack of (MS,PAN) for fine tune the network. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_in = input_preparation(EXP,I_MS_LR,I_PAN,model) I_MS_LR = double(I_MS_LR); I_PAN = double(I_PAN); NDxI_LR = []; if isequal(model.inputType,'MS_PAN_NDxI') if size(I_MS_LR,3) == 8 NDxI_LR = cat(3,... (I_MS_LR(:,:,5)-I_MS_LR(:,:,8))./(I_MS_LR(:,:,5)+I_MS_LR(:,:,8)), ... (I_MS_LR(:,:,1)-I_MS_LR(:,:,8))./(I_MS_LR(:,:,1)+I_MS_LR(:,:,8)), ... (I_MS_LR(:,:,3)-I_MS_LR(:,:,4))./(I_MS_LR(:,:,3)+I_MS_LR(:,:,4)), ... (I_MS_LR(:,:,6)-I_MS_LR(:,:,1))./(I_MS_LR(:,:,6)+I_MS_LR(:,:,1)) ); else NDxI_LR = cat(3,... (I_MS_LR(:,:,4)-I_MS_LR(:,:,3))./(I_MS_LR(:,:,4)+I_MS_LR(:,:,3)), ... (I_MS_LR(:,:,2)-I_MS_LR(:,:,4))./(I_MS_LR(:,:,2)+I_MS_LR(:,:,4)) ); end NDxI_LR(find(isnan(NDxI_LR))) = 0; end mav_value = 2^double(model.L); if ~isempty(EXP) I_MS = EXP; if not(isempty(NDxI_LR)), NDxI = interp23tap(NDxI_LR,model.ratio); end else if isequal(model.typeInterp,'interp23tap') I_MS = interp23tap(I_MS_LR, double(model.ratio)); if not(isempty(NDxI_LR)), NDxI = interp23tap(NDxI_LR,model.ratio); end elseif isequal(model.typeInterp,'cubic') I_MS = imresize(I_MS_LR,size(I_PAN),'bicubic'); if not(isempty(NDxI_LR)), NDxI = imresize(NDxI_LR,size(I_PAN),'bicubic'); end else error('Interpolation not supported'); end end if isequal(model.inputType,'MS') I_in = single(I_MS)/mav_value; elseif isequal(model.inputType,'MS_PAN') I_in = single(cat(3,I_MS,I_PAN))/mav_value; elseif isequal(model.inputType,'MS_PAN_NDxI') I_in = single(cat(3,I_MS,I_PAN))/mav_value; I_in = single(cat(3,I_in,single(NDxI))); else error('Configuration not supported'); end padSize = double(model.padSize); I_in = padarray(I_in, [padSize,padSize]/2, 'replicate','both'); end
294coder/Efficient-MIF
1,169
Pansharpening_Hyper_SR_Matlab_Test_Package/PNN/ft_learning_rate.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Adapting learning rate for new image dimension % Interface: % lr = ft_learning_rate(model,net_scope,size_ms) % Inputs: % model: Struct with training details of pretrained network; % net_scope: Network scope; % size_ms: Size of ms image. % Output: % lr: Learning rate for fine tuning. % % References: % [Scarpa2018] G. Scarpa, S. Vitale, and D. Cozzolino. % Target-adaptive CNN-based pansharpening. % IEEE Transactions on Geoscience and Remote Sensing, % vol. 56, no. 9, pp. 5443-5457, Sep. 2018. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function lr = ft_learning_rate(model,net_scope,size_ms) pretrained_lr = model.lr; if isfield(model,'block_size') patch_size = double(model.block_size); else patch_size = double(model.patch_size); end lr = pretrained_lr*((patch_size-net_scope+1)^2./(size_ms(1)-net_scope+1)/(size_ms(1)-net_scope+1)); end
2881099/FreeSql.AdminLTE
1,721
Examples/net80_blazor/Infrastructure/Extensions/EnumExtension.cs
using System.ComponentModel; using System.Reflection; public static class EnumExtension { public static string ToDescription(this Enum item) { string name = item.ToString(); var desc = item.GetType().GetField(name)?.GetCustomAttribute<DescriptionAttribute>(false); return desc?.Description ?? name; } public static string ToNameWithDescription(this Enum item) { string name = item.ToString(); var desc = item.GetType().GetField(name)?.GetCustomAttribute<DescriptionAttribute>(false); return $"{name}{(desc == null || desc.Description.IsNull() ? "" : $"({desc?.Description})")}"; } public static long ToInt64(this Enum item) { return Convert.ToInt64(item); } public static List<Dictionary<string, object>> ToList(this Enum value, bool ignoreNull = false) { var enumType = value.GetType(); if (!enumType.IsEnum) return null; return Enum.GetValues(enumType).Cast<Enum>() .Where(m => !ignoreNull || !m.ToString().Equals("Null")).Select(x => new Dictionary<string,object> { ["Label"] = x.ToDescription(), ["Value"] = x }).ToList(); } public static List<Dictionary<string, object>> ToList<T>(bool ignoreNull = false) { var enumType = typeof(T); if (!enumType.IsEnum) return null; return Enum.GetValues(enumType).Cast<Enum>() .Where(m => !ignoreNull || !m.ToString().Equals("Null")).Select(x => new Dictionary<string, object> { ["Label"] = x.ToDescription(), ["Value"] = x }).ToList(); } }
294coder/Efficient-MIF
6,026
Pansharpening_Hyper_SR_Matlab_Test_Package/PNN/PNNplus.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % PNN+ algorithm for pansharpening by Scarpa et al. (2018). % Interface: % P = PNNplus(MS, PAN, sensor_model, FT_epochs, nBits, MTF, EXP); % P = PNNplus(MS, PAN, sensor_model, FT_epochs, nBits, MTF); % P = PNNplus(MS, PAN, sensor_model, FT_epochs, nBits); % P = PNNplus(MS, PAN, sensor_model, FT_epochs); % P = PNNplus(MS, PAN, sensor_model); % [P AUX] = PNNplus(MS, PAN, sensor_model, FT_epochs, nBits, MTF, EXP); % [P AUX] = PNNplus(MS, PAN, sensor_model, FT_epochs, nBits, MTF); % [P AUX] = PNNplus(MS, PAN, sensor_model, FT_epochs, nBits); % [P AUX] = PNNplus(MS, PAN, sensor_model, FT_epochs); % [P AUX] = PNNplus(MS, PAN, sensor_model). % Input: % MS: 4- or 8-band multispectral image; % PAN: Panchromatic image (must be 4x4x larger than MS); % sensor_model: one of the following string: % 'IKONOS' % 'GeoEye1' % 'WV2' % 'WV3' % '<full-path file name of any pretrained model>' % WARNING: If an own model is used, the file must be a work % space with a cell-array variable named 'layers' % containing the sequence of weights and bias of the % three convolutional layers. Also the following % variables must be enclosed in the work space: lr, % patch_size, ratio, sensor, inputType, typeInterp. % For consistency check watch the content of any % provided model (e.g., 'IKONOS_PNNplus_model.mat'). % % nBits: #bits (radiometric precision); default=11; % FT_epochs(>=0): 0->no fine tuning; default=50; % WARNING: In case of CPU-only PC it is recommended to avoid % (FT_epochs = 0) or limit to a few iterations the % fine-tuning. % MTF: Struct with custom MTF gains (GNyq and GNyqPan). % EXP: 4- or 8-band multispectral image upsampled to the PAN scale % Output: % P: Pansharpened image; % AUX: Auxiliary output variable containing the % fine-tuned model and other training details. % References: % [Scarpa18] G. Scarpa, S. Vitale, and D. Cozzolino, "Target-adaptive CNN-based pansharpening", % IEEE Transactions on Geoscience and Remote Sensing, vol. 56, no. 9, pp. 5443-5457, Sep. 2018. % [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods", % IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [P, AUX] = PNNplus(MS, PAN, sensor_model, FT_epochs, nBits, MTF, EXP) if nargin < 7 EXP = []; end MTFflag = false; if ~isempty(MTF), MTFflag = true; end if nargin<5, nBits=11; elseif isempty(nBits), nBits = 11; end if nargin<4, FT_epochs = 50; elseif isempty(FT_epochs), FT_epochs = 50; end MS = single(MS); PAN = single(PAN); nBits = single(nBits); EXP = single(EXP); [M,N,Nb] = size(MS); %%% LOAD PRETRAINED MODEL cd 'models' available_models = {'IKONOS', 'GeoEye1','WV2', 'WV3'}; if sum(ismember(available_models,sensor_model)) sensor_model = which([sensor_model '_PNNplus_model.mat']); end model = load(sensor_model); cd .. if isfield(model,'model'), model = model.model; end model.L = nBits; net_scope = model_scope(model); % build list of layers firstLayer = imageInputLayer([M N Nb+1],'Name','InputLayer','Normalization','none'); layers = load_layers(firstLayer,model); %scaling learning rate on last layer layers(end).WeightLearnRateFactor =0.1; layers(end).BiasLearnRateFactor =0.1; layers = [layers,maeRegressionLayer('regre')]; traininfo = []; pad = model.padSize; [Mpan, Npan] = size(PAN); % Train_time = 0; if FT_epochs>0 tempDir = 'temporary_pnn_plus'; delete([tempDir '/*.*']); mkdir(tempDir); tic; if MTFflag [~, traininfo] = fine_tune(MS, PAN, model, layers, FT_epochs, tempDir, MTF); else [~, traininfo] = fine_tune(MS, PAN, model, layers, FT_epochs, tempDir); end % Train_time = toc; %%%% LOAD BEST MODEL [~, best] = min(traininfo.TrainingLoss); pref = [tempDir sprintf('/net_checkpoint__%d__*',best)]; fn = dir(pref); fn = [tempDir '/' fn.name]; net = getfield(load(fn),'net'); %%%% delete([tempDir '/*.*']); rmdir(tempDir); lgraph = layerGraph(net.Layers); model.layers{1} = net.Layers(2).Weights; model.layers{2} = net.Layers(2).Bias; model.layers{3} = net.Layers(4).Weights; model.layers{4} = net.Layers(4).Bias; model.layers{5} = net.Layers(6).Weights; model.layers{6} = net.Layers(6).Bias; else lgraph = layerGraph(layers); end lgraph = replaceLayer(lgraph,lgraph.Layers(1).Name,imageInputLayer([Mpan+pad Npan+pad Nb+1],'Name','InputLayer','Normalization','none')); net = assembleNetwork(lgraph); AUX.model = model; AUX.traininfo = traininfo; %% Pansharpening I_in = input_preparation(EXP,MS,PAN,model); tic; P = predict(net,I_in); %Test_time = toc; I_MS_int = (2^model.L)*I_in(floor(net_scope/2)+1:end-floor(net_scope/2),floor(net_scope/2)+1:end-floor(net_scope/2),1:end-1,:); P = P*(2^model.L)+I_MS_int; P(P<0)=0; %%% %fprintf(sprintf('------> [PNN+]: Fine-tuning (%d it) time = %0.4gs // Prediction time = %0.4gs\n',FT_epochs, Train_time, Test_time)); end
294coder/Efficient-MIF
1,162
Pansharpening_Hyper_SR_Matlab_Test_Package/PNN/maeRegressionLayer.m
classdef maeRegressionLayer < nnet.layer.RegressionLayer % regression layer with mean-absolute-error loss. methods function layer = maeRegressionLayer(name) % layer = maeRegressionLayer(name) creates a % mean-absolute-error regression layer and specifies the layer % name. % Set layer name. layer.Name = name; % Set layer description. layer.Description = 'Mean absolute error'; end function loss = forwardLoss(layer, Y, T) % loss = forwardLoss(layer, Y, T) returns the MAE loss between % the predictions Y and the training targets T. % Calculate MAE. R = size(Y,3); flosdy = abs(Y-T); % Take mean over mini-batch. N = size(Y,4); loss = sum(flosdy(:))/N; end function dLdY = backwardLoss(layer, Y, T) % Returns the derivatives of the MAE loss with respect to the predictions Y % R = size(Y,3); N = size(Y,4); dLdY = sign(Y-T)/N; end end end
294coder/Efficient-MIF
2,479
Pansharpening_Hyper_SR_Matlab_Test_Package/PNN/fine_tune.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Fine Tuning of Pretrained network for panshaprening % Interface: % net = fine_tune(I_MS, I_PAN, model,layers,epochs,outpath,MTF) % % Inputs: % I_MS: multispectral image; % I_PAN: panchromatic image; % model: struct with training details of pretrained network; % layers: pretrained layers; % epochs: number of epochs for fine tuning; % outpath: path for storing the finetuned network; % MTF: (optional) struct with custom MTF gains (GNyq and GNyqPan). % % Outputs: % net: finetuned network; % traininfo: training infos. % % References: % [Scarpa2018] G. Scarpa, S. Vitale, and D. Cozzolino. % Target-adaptive CNN-based pansharpening. % IEEE Transactions on Geoscience and Remote Sensing, % vol. 56, no. 9, pp. 5443-5457, Sep. 2018. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [net, traininfo] = fine_tune(I_MS, I_PAN, model,layers,epochs,outpath,MTF) %% load data for fine tuning net_scope = model_scope(model); ratio = double(model.ratio); sensor = model.sensor; s = size(I_MS); lr = ft_learning_rate(model,net_scope,s); %adapting learning rate for new image dimension %% Wald protocol and input preparation if nargin == 7 [I_MS_LR,I_PAN_LR] = resize_images_GNyq(I_MS,I_PAN,ratio,MTF.GNyq); else [I_MS_LR,I_PAN_LR] = resize_images(I_MS,I_PAN,ratio,sensor); end I_MS = I_MS./(2^double(model.L)); I_in = input_preparation([],I_MS_LR,I_PAN_LR,model); I_in = I_in(floor(net_scope/2)+1:end-floor(net_scope/2),floor(net_scope/2)+1:end-floor(net_scope/2),:,:); I_ref = I_MS-I_in(:,:,1:end-1); %residual %% training options options = trainingOptions('sgdm',... 'ExecutionEnvironment','auto',... 'Momentum',0.9,... 'VerboseFrequency',1,... 'Shuffle','never',... 'InitialLearnRate',lr,... 'LearnRateDropPeriod',epochs+1,... 'LearnRateDropFactor',1,... 'L2Regularization',0.,... 'MaxEpochs',epochs,... 'CheckpointPath',outpath); %% train network [net, traininfo] = trainNetwork(I_in,I_ref(floor(net_scope/2)+1:end-floor(net_scope/2),floor(net_scope/2)+1:end-floor(net_scope/2),:),layers,options); %save losses %save([outpath,'traininfo.mat'],'traininfo'); end
2977094657/BiliHistoryFrontend
5,743
src/components/tailwind/analytics/pages/TagsPage.vue
<!-- 标签分析页组件 --> <template> <div class="space-y-6"> <h3 class="text-4xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 标签分析 </h3> <div class="text-lg text-center text-gray-600 dark:text-gray-300 mb-8 space-y-2"> <div v-if="viewingData?.insights?.tag_preference" v-html="formatInsightText(viewingData.insights.tag_preference)"> </div> <div v-if="viewingData?.insights?.tag_completion" v-html="formatInsightText(viewingData.insights.tag_completion)"> </div> </div> <div class="grid grid-cols-1 lg:grid-cols-2 gap-6"> <!-- 标签分布图表 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-6 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-4">观看分布</h4> <div class="h-[280px]"> <v-chart ref="distributionChartRef" class="h-full w-full" :option="tagDistributionOption" autoresize /> </div> </div> <!-- 标签完成率图表 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-6 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-4">完成率排行</h4> <div class="h-[280px]"> <v-chart ref="completionChartRef" class="h-full w-full" :option="tagCompletionOption" autoresize /> </div> </div> </div> </div> </template> <script setup> import { ref, computed, onMounted } from 'vue' import gsap from 'gsap' import VChart from 'vue-echarts' import * as echarts from 'echarts/core' const props = defineProps({ viewingData: { type: Object, required: true } }) const distributionChartRef = ref(null) const completionChartRef = ref(null) const tagDistributionOption = computed(() => { if (!props.viewingData?.watch_counts?.tag_distribution) return {} const data = Object.entries(props.viewingData.watch_counts.tag_distribution) .sort((a, b) => b[1] - a[1]) .map(([tag, count]) => ({ name: tag, value: count })) return { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, backgroundColor: 'rgba(28, 28, 28, 0.9)', borderColor: '#fb7299', textStyle: { color: '#fff' } }, grid: { top: '3%', left: '3%', right: '15%', bottom: '3%', containLabel: true }, xAxis: { type: 'value', axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' }, splitLine: { lineStyle: { color: 'rgba(0, 0, 0, 0.1)' } } }, yAxis: { type: 'category', data: data.map(item => item.name), axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' }, inverse: true }, series: [{ name: '视频数量', type: 'bar', data: data.map((item, index) => ({ value: item.value, itemStyle: { color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [ { offset: 0, color: `rgba(251, 114, 153, ${Math.max(0.4, 0.9 - index * 0.05)})` }, { offset: 1, color: `rgba(252, 155, 122, ${Math.max(0.4, 0.9 - index * 0.05)})` } ]) } })), label: { show: true, position: 'right', formatter: '{c} 个' } }] } }) const tagCompletionOption = computed(() => { if (!props.viewingData?.completion_rates?.tag_completion_rates) return {} const data = Object.entries(props.viewingData.completion_rates.tag_completion_rates) .map(([tag, stats]) => ({ tag, completion: stats.average_completion_rate, count: stats.video_count })) .sort((a, b) => b.completion - a.completion) .slice(0, 10) return { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: (params) => { const data = params[0].data return `${params[0].name}<br/>完成率:${data.value}%<br/>视频数:${data.count}个` } }, grid: { top: '3%', left: '3%', right: '15%', bottom: '3%', containLabel: true }, xAxis: { type: 'value', name: '完成率', axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999', formatter: '{value}%' }, splitLine: { lineStyle: { color: 'rgba(0, 0, 0, 0.1)' } } }, yAxis: { type: 'category', data: data.map(item => `${item.tag}(${item.count}个)`), axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' }, inverse: true }, series: [{ type: 'bar', data: data.map((item, index) => ({ value: item.completion, count: item.count, itemStyle: { color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [ { offset: 0, color: `rgba(64, 169, 255, ${Math.max(0.4, 0.9 - index * 0.05)})` }, { offset: 1, color: `rgba(128, 208, 255, ${Math.max(0.4, 0.9 - index * 0.05)})` } ]) } })), label: { show: true, position: 'right', formatter: '{c}%' } }] } }) onMounted(() => { const charts = [distributionChartRef.value, completionChartRef.value] if (charts.every(chart => chart)) { gsap.from(charts.map(chart => chart.$el), { opacity: 0, y: 20, duration: 0.5, stagger: 0.1, ease: 'power2.out', delay: 0.2 }) } }) // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } </script>
294coder/Efficient-MIF
1,588
Pansharpening_Hyper_SR_Matlab_Test_Package/PNN/input_preparation_.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Prepare the data for training: % 1. Interpolate I_MS_LR image in order to bring it % to PAN dimension; % 2. Create a stack of (MS,PAN) and normalize to % maximum dynimc of image. % Interface: % I_in = input_preparation_(I_MS_LR,I_PAN,model) % Inputs: % I_MS_LR: MS image donwgraded for Wald Protocol; % I_PAN: PAN image downgraded for Wald Protocol; % model: Struct with training details of pretrained network. % Output: % I_in: stack of (MS,PAN) for fine tune the network. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_in = input_preparation_(I_MS_LR,I_PAN,model) mav_value = 2^double(model.L); if isequal(model.typeInterp,'interp23tap') I_MS = interp23tap(I_MS_LR, double(model.ratio)); elseif isequal(model.typeInterp,'cubic') I_MS = imresize(I_MS_LR,size(I_PAN),'bicubic'); else error('Interpolation not supported'); end if isequal(model.inputType,'MS') I_in = single(I_MS)/mav_value; elseif isequal(model.inputType,'MS_PAN') I_in = single(cat(3,I_MS,I_PAN))/mav_value; elseif isequal(model.inputType,'MS_PAN_NDxI') I_in = single(cat(3,I_MS,I_PAN))/mav_value; I_in = single(cat(3,I_in,single(NDxI))); % CHANGE else error('Configuration not supported'); end padSize = double(model.padSize); I_in = padarray(I_in, [padSize,padSize]/2, 'replicate','both'); end
2977094657/BiliHistoryFrontend
7,631
src/components/tailwind/analytics/pages/PopularPredictionPage.vue
<template> <div class="space-y-4"> <h3 class="text-xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 热门预测能力分析 </h3> <!-- 加载状态 --> <div v-if="loading" class="flex justify-center items-center py-12"> <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-[#fb7299]"></div> </div> <!-- 错误状态 --> <div v-else-if="error" class="text-center py-12"> <div class="text-red-500 text-lg">{{ error }}</div> </div> <!-- 主要内容 --> <div v-else-if="predictionData" class="space-y-4"> <!-- 洞察文本 --> <div class="text-center text-gray-600 dark:text-gray-300"> <div class="text-sm leading-relaxed" v-html="formatInsightText(insights.join(','))"></div> </div> <!-- 可视化图表 --> <div class="grid grid-cols-1 lg:grid-cols-3 gap-4"> <!-- 预测能力统计卡片 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-base font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-2 text-center"> 预测能力分布 </h4> <div ref="chartRef" class="h-[460px]"></div> </div> <!-- 预测成功的视频列表 --> <div v-if="predictedVideos && predictedVideos.length > 0" class="lg:col-span-2 bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-base font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-2"> 预测成功的视频 (前10个,按提前天数排序) </h4> <div class="grid grid-cols-1 md:grid-cols-2 gap-2 h-[460px] overflow-y-auto"> <div v-for="(video, index) in predictedVideos" :key="index" @click="openVideo(video.bvid)" class="flex items-center p-2 bg-gray-50/50 dark:bg-gray-800/50 rounded-lg hover:bg-gray-100/50 dark:hover:bg-gray-700/50 cursor-pointer transition-colors"> <div class="flex-1 min-w-0"> <div class="font-medium text-gray-900 dark:text-gray-100 truncate text-xs">{{ video.title }}</div> <div class="text-xs text-gray-500 dark:text-gray-400 mt-1"> <span>{{ video.author }}</span> <span class="ml-2 text-blue-600">提前{{ video.advance_days }}天</span> </div> <div class="text-xs text-gray-400 mt-1"> <span>最高排名: {{ video.highest_rank || '未知' }}</span> <span class="ml-2">{{ formatDate(video.view_at) }}</span> </div> </div> </div> </div> </div> </div> </div> </div> </template> <script setup> import { ref, onMounted, watch, computed } from 'vue' import * as echarts from 'echarts' import { getPopularPredictionAbility } from '../../../../api/api.js' const props = defineProps({ selectedYear: { type: Number, default: () => new Date().getFullYear() }, data: { type: Object, default: null } }) const loading = ref(true) const error = ref(null) const predictionData = ref(null) const chartRef = ref(null) let chart = null // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299] font-semibold">$1</span>') } // 格式化日期 const formatDate = (timestamp) => { return new Date(timestamp * 1000).toLocaleDateString('zh-CN') } // 打开视频 const openVideo = (bvid) => { if (bvid) { window.open(`https://www.bilibili.com/video/${bvid}`, '_blank') } } // 计算属性 const insights = computed(() => { if (!predictionData.value) return [] return predictionData.value.insights || [] }) const predictedVideos = computed(() => { if (!predictionData.value) return [] return predictionData.value.predicted_videos || [] }) // 获取热门预测能力数据 const fetchPredictionData = async (year) => { if (!year) return // 如果父组件已经传递了数据,直接使用 if (props.data) { predictionData.value = props.data loading.value = false await initCharts() return } loading.value = true error.value = null try { const response = await getPopularPredictionAbility(year) if (response.data.status === 'success') { predictionData.value = response.data.data.prediction_analysis await initCharts() } else { error.value = response.data.message || '获取数据失败' } } catch (err) { console.error('获取热门预测能力数据出错:', err) error.value = '获取数据时发生错误' } finally { loading.value = false } } // 初始化图表 const initCharts = async () => { await new Promise(resolve => setTimeout(resolve, 100)) // 等待DOM更新 initChart() } // 初始化图表 const initChart = () => { if (!chartRef.value || !predictionData.value) return if (chart) { chart.dispose() } chart = echarts.init(chartRef.value) const predictedCount = predictionData.value.predicted_count const nonPredictedCount = predictionData.value.total_watched - predictedCount const predictionRate = predictionData.value.prediction_rate const option = { tooltip: { trigger: 'item', formatter: function(params) { const percentage = params.percent return `${params.name}: ${params.value} 个 (${percentage}%)` } }, legend: { bottom: '8%', left: 'center', textStyle: { color: '#666', fontSize: 12 } }, series: [ { name: '预测能力分布', type: 'pie', radius: '70%', center: ['50%', '45%'], label: { show: true, position: 'outside', formatter: function(params) { return `${params.name}\n${params.value}个\n${params.percent}%` }, fontSize: 11, color: '#333' }, emphasis: { label: { show: true, fontSize: '13', fontWeight: 'bold' }, itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }, labelLine: { show: true, length: 15, length2: 10 }, data: [ { value: predictedCount, name: '预测成功', itemStyle: { color: { type: 'linear', x: 0, y: 0, x2: 1, y2: 1, colorStops: [ { offset: 0, color: '#10B981' }, { offset: 1, color: '#059669' } ] } } }, { value: nonPredictedCount, name: '普通视频', itemStyle: { color: { type: 'linear', x: 0, y: 0, x2: 1, y2: 1, colorStops: [ { offset: 0, color: '#e0e0e0' }, { offset: 1, color: '#c0c0c0' } ] } } } ] } ] } chart.setOption(option) } // 监听年份变化 watch(() => props.selectedYear, (newYear) => { fetchPredictionData(newYear) }, { immediate: true }) // 监听父组件传递的数据变化 watch(() => props.data, (newData) => { if (newData) { predictionData.value = newData loading.value = false initCharts() } }, { immediate: true }) // 组件挂载时获取数据 onMounted(() => { fetchPredictionData(props.selectedYear) }) </script> <style scoped> .line-clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } </style>
298582245/wqwl_qinglong
13,847
wqwl_require.js
const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const axios = require('axios'); const https = require('https'); const { constants } = require('crypto'); //const { console } = require('inspector'); let message = ""; //获取环境变量 function checkEnv(userCookie) { try { if (!userCookie || userCookie === "" || userCookie === undefined || userCookie === "undefined" || userCookie === null || userCookie === "null") { console.log("没配置环境变量就要跑脚本啊!!!"); console.log("🔔还没开始已经结束!"); process.exit(1); } const envSplitor = ["&", "\n"]; //this.sendMessage(userCookie); let userList = userCookie .split(envSplitor.find((o) => userCookie.includes(o)) || "&") .filter((n) => n); if (!userList || userList.length === 0) { console.log("没配置环境变量就要跑脚本啊!!!"); console.log("🔔还没开始已经结束!"); process.exit(1); } console.log(`✅共找到${userList.length}个账号`); return userList; } catch (e) { console.log("环境变量格式错误,下面是报错信息") console.log(e); } } async function sleep(s) { return new Promise(resolve => setTimeout(resolve, s * 1000)); } function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function sendMessage(text, isPush = true) { if (isPush) { message += text + "\n"; } console.log(text); return text; } function getMessage() { return message; } function md5(str, uppercase = false) { const hash = crypto.createHash('md5'); hash.update(str); let result = hash.digest('hex'); return uppercase ? result.toUpperCase() : result; } function aesEncrypt(data, key, iv = '', cipher = 'aes-256-cbc', keyEncoding = 'utf8', inputEncoding = 'utf8', outputEncoding = 'hex') { let keyBuffer = Buffer.from(key, keyEncoding); const ivBuffer = iv ? Buffer.from(iv, 'utf8') : null; const cipherObj = crypto.createCipheriv(cipher, keyBuffer, ivBuffer); cipherObj.setAutoPadding(true); // 确保使用 PKCS7 填充 let encrypted = cipherObj.update(data, inputEncoding, outputEncoding); encrypted += cipherObj.final(outputEncoding); return encrypted; } function aesDecrypt(encryptedData, key, iv = '', cipher = 'aes-128-cbc', keyEncoding = 'utf8', outputEncoding = 'utf8', inputEncoding = 'hex') { const encryptedBuffer = Buffer.isBuffer(encryptedData) ? encryptedData : Buffer.from(encryptedData, inputEncoding); const keyBuffer = Buffer.from(key, keyEncoding); const ivBuffer = iv ? Buffer.from(iv, keyEncoding) : Buffer.alloc(0); const decipher = crypto.createDecipheriv(cipher, keyBuffer, ivBuffer); let decrypted = decipher.update(encryptedBuffer); decrypted = Buffer.concat([decrypted, decipher.final()]); return decrypted.toString(outputEncoding); } async function request(options, proxy = '') { let agent = new https.Agent({ ciphers: 'DEFAULT@SECLEVEL=1', secureOptions: constants.SSL_OP_LEGACY_SERVER_CONNECT, minVersion: 'TLSv1', maxVersion: 'TLSv1.2', rejectUnauthorized: false }); if (proxy) { try { // 检查模块是否存在 if (typeof require('https-proxy-agent') === 'function' || typeof require('https-proxy-agent').HttpsProxyAgent === 'function') { const { HttpsProxyAgent } = require('https-proxy-agent'); agent = new HttpsProxyAgent(`http://${proxy}`); } else { console.log('⚠️https-proxy-agent 模块未安装,将不使用代理'); } } catch (e) { console.log(`创建代理代理失败❌: ${e.message}`) } } const config = { ...options, httpsAgent: agent, httpAgent: agent, validateStatus: () => true, }; try { const response = await axios(config); return response.data; } catch (e) { throw new Error(e.message); } } async function getProxy(index, url) { const config = { method: 'get', url: url || process.env['wqwl_daili'] }; let retries = 3; let lastError; for (let attempt = 1; attempt <= retries; attempt++) { try { const response = await axios(config); //console.log(`账号[${index + 1}]: 获取到的代理✅: ${response.data.trim()}`); return response.data.trim(); // 返回代理 IP:端口 } catch (error) { lastError = error; console.error(`账号[${index + 1}]:🔐获取代理失败,正在重试...`); if (attempt < retries) { // 等待一段时间再重试(可选) await new Promise(resolve => setTimeout(resolve, 3000 * attempt)); } } } console.error(`账号[${index + 1}]:获取代理失败,已重试${retries}次❌`); return ''; } // 固定存储目录 const DATA_DIR = path.resolve(__dirname, 'wqwl_data'); // 确保目录存在 function ensureDataDirExists() { if (!fs.existsSync(DATA_DIR)) { fs.mkdirSync(DATA_DIR, { recursive: true }); } } // 保存 JSON 到 wqwl_data 目录(覆盖或新建) function saveFile(data, filename) { ensureDataDirExists(); const filePath = path.join(DATA_DIR, `wqwl_${filename}.json`); fs.writeFileSync(filePath, JSON.stringify(data, null, 4), 'utf8'); //console.log(`✅ 已保存文件到: ${filePath}`); } // 从 wqwl_data 目录读取 JSON function readFile(filename) { const filePath = path.join(DATA_DIR, `wqwl_${filename}.json`); if (!fs.existsSync(filePath)) { console.warn(`⚠️ 文件不存在: ${filePath},已自动创建文件。`); return {}; } try { const rawData = fs.readFileSync(filePath, 'utf8'); const data = JSON.parse(rawData); //console.log(`✅ 已读取文件: ${filePath}`); return data; } catch (err) { console.error(`❌ 读取或解析文件失败: ${err.message}`); return {}; } } // 生成随机版本号 function getRandomVersion() { const major = Math.floor(Math.random() * 10) + 6; // 6-15 const minor = Math.floor(Math.random() * 100); const patch = Math.floor(Math.random() * 1000); return `${major}.0.${minor}.${patch}`; } // 生成随机日期格式 function getRandomDate() { const year = 2022 + Math.floor(Math.random() * 3); // 2022-2024 const month = String(Math.floor(Math.random() * 12) + 1).padStart(2, '0'); const day = String(Math.floor(Math.random() * 28) + 1).padStart(2, '0'); return `${year}${month}${day}`; } // 生成随机微信版本 function getRandomWeChatVersion() { const major = 8; const minor = Math.floor(Math.random() * 50); // 0-49 const patch = Math.floor(Math.random() * 3000); // 0-2999 const hex = Math.floor(Math.random() * 0x3000) + 0x28000000; return `${major}.0.${minor}.${patch}(0x${hex.toString(16)})`; } // 生成随机数字ID function getRandomId(length) { return Math.floor(Math.random() * Math.pow(10, length)).toString().padStart(length, '0'); } // 生成随机UA function generateRandomUA() { const common = { prefix: 'Mozilla/5.0 (Linux; Android ', webkit: 'AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/', mobileSafari: 'Mobile Safari/537.36 ', xwebPrefix: 'XWEB/', mmwebSdkPrefix: 'MMWEBSDK/', mmwebIdPrefix: 'MMWEBID/', microMessengerPrefix: 'MicroMessenger/', wechat: 'WeChat/arm64 Weixin NetType/', language: 'Language/zh_CN ABI/arm64 MiniProgramEnv/android' }; // 设备信息池 const devices = [ { model: 'SM-G998B', build: 'TP1A.220624.014', androidVersion: '13' }, { model: 'Pixel 7', build: 'UQ1A.231205.015', androidVersion: '14' }, { model: 'MI 11', build: 'SKQ1.211006.001', androidVersion: '12' }, { model: 'Redmi Note 12', build: 'SKQ1.211006.001', androidVersion: '12' }, { model: 'OPPO Find X5', build: 'TP1A.220624.014', androidVersion: '13' } ]; // 网络类型池 const netTypes = ['WIFI', '4G', '5G']; const device = devices[Math.floor(Math.random() * devices.length)]; const netType = netTypes[Math.floor(Math.random() * netTypes.length)]; const chromeVersion = getRandomVersion(); const xwebVersion = Math.floor(Math.random() * 2000) + 5000; const mmwebSdkDate = getRandomDate(); const mmwebId = getRandomId(4); const microMessengerVersion = getRandomWeChatVersion(); return `${common.prefix}${device.androidVersion}; ${device.model} Build/${device.build}; wv) ${common.webkit}${chromeVersion} ${common.mobileSafari}${common.xwebPrefix}${xwebVersion} ${common.mmwebSdkPrefix}${mmwebSdkDate} ${common.mmwebIdPrefix}${mmwebId} ${common.microMessengerPrefix}${microMessengerVersion} ${common.wechat}${netType} ${common.language}`; } function formatDate(date, isDetail = false) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); if (isDetail) return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; return `${year}-${month}-${day}`; } function sha1(str) { if (!str) return '' return crypto.createHash('sha1').update(str).digest('hex'); } /** * 通用RSA加密函数 * @param {string|Object} data - 要加密的数据 * @param {string} publicKey - 公钥(PEM格式) * @param {string} outputEncoding - 输出编码格式:'base64', 'hex', 'buffer',默认'base64' * @param {string} inputEncoding - 输入编码,默认'utf8' * @param {number} padding - 填充方式,默认RSA_PKCS1_PADDING * @returns {string|Buffer} 加密后的数据 */ function rsaEncrypt(data, publicKey, outputEncoding = 'base64', inputEncoding = 'utf8', padding = crypto.constants.RSA_PKCS1_PADDING) { const text = typeof data === 'string' ? data : JSON.stringify(data); const buffer = crypto.publicEncrypt( { key: publicKey, padding: padding }, Buffer.from(text, inputEncoding) ); return outputEncoding === 'buffer' ? buffer : buffer.toString(outputEncoding); } /** * 通用RSA解密函数 * @param {string|Buffer} encryptedData - 加密的数据 * @param {string} privateKey - 私钥(PEM格式) * @param {string} inputEncoding - 输入编码格式:'base64', 'hex', 'buffer',默认'base64' * @param {string} outputEncoding - 输出编码,默认'utf8' * @param {number} padding - 填充方式,默认RSA_PKCS1_PADDING * @returns {string} 解密后的原始数据 */ function rsaDecrypt(encryptedData, privateKey, inputEncoding = 'base64', outputEncoding = 'utf8', padding = crypto.constants.RSA_PKCS1_PADDING) { let inputBuffer; if (inputEncoding === 'buffer') { inputBuffer = encryptedData; } else { inputBuffer = Buffer.from(encryptedData, inputEncoding); } const buffer = crypto.privateDecrypt( { key: privateKey, padding: padding }, inputBuffer ); return buffer.toString(outputEncoding); } async function findTypes(targetName) { const config = { method: 'get', url: `https://gitee.com/cobbWmy/img/raw/staticApi/type.json` }; let retries = 3; let lastError; let types = []; // 改为数组存储多个分类 for (let attempt = 1; attempt <= retries; attempt++) { try { const response = await axios(config); const data = response.data; // 清空之前的查找结果 types = []; // 在返回的数据中查找目标name所属的所有分类 for (const [category, items] of Object.entries(data)) { const found = items.find(item => item.name === targetName); if (found) { types.push(category); } } // 如果找到了分类,就跳出重试循环 break; } catch (error) { lastError = error; console.error(`🔐获取分类数据失败,正在重试... (${attempt}/${retries})`); if (attempt < retries) { // 等待一段时间再重试 await new Promise(resolve => setTimeout(resolve, 3000 * attempt)); } } } // 如果没有找到任何分类,返回"其他" if (types.length === 0) { return "其他"; } // 如果找到多个分类,用"+"连接 return types.join('+'); } function hmacSHA256(data, key, inputEncoding = 'utf8') { const hmac = crypto.createHmac('sha256', key); hmac.update(data, inputEncoding); return hmac.digest('base64'); } function disclaimer() { console.log(`⚠️免责声明 1. 本脚本中涉及的解锁解密分析脚本仅用于测试、学习和研究,禁止用于商业目的。 其合法性、准确性、完整性和有效性无法得到保证。 请根据实际情况作出自己的判断。 2. 禁止任何官方账号或自媒体以任何形式复制或发布本项目中的所有资源文件。 3. 本脚本不负责任何脚本问题,包括但不限于任何脚本错误导致的任何损失或损坏。 4. 任何间接使用该脚本的用户,包括但不限于建立 VPS 或在某些行为违反国家/地区法律或相关法规时传播该脚本,本脚本不承担由此造成的任何隐私泄露或其他后果。 5. 请勿将本脚本项目的任何内容用于商业或非法目的,否则所造成的后果由您自行承担。 6. 任何单位或个人认为项目脚本可能侵犯其权利时,应及时通知并提供身份证明和所有权证明。 我们会在收到认证文件后删除相应的脚本。 7. 任何以任何方式或直接或间接使用 wqwl_qinglong 项目的任何脚本的人都应该仔细阅读此声明。本脚本保留随时更改或补充本免责声明的权利。 一旦您使用并复制了本脚本,您就被视为接受了本免责声明。 8. 您必须在下载后 24 小时内从您的电脑或手机上彻底删除以上内容。 9. 您在本脚本使用或复制了由本人开发的任何脚本,即视为已接受此声明。请在使用前仔细阅读以上条款。 10. 脚本来源:https://github.com/298582245/wqwl_qinglong,QQ裙:960690899 ============================ ⚠️⚠️⚠️使用代理时,必须安装依赖:https-proxy-agent ⚠️⚠️⚠️使用代理时,必须安装依赖:https-proxy-agent ⚠️⚠️⚠️使用代理时,必须安装依赖:https-proxy-agent ============================\n `) } module.exports = { checkEnv: checkEnv, //获取环境变量 sleep: sleep, //等待 getRandom: getRandom, //随机数 sendMessage: sendMessage, //发送消息 getMessage: getMessage, //获取消息 md5: md5, //md5, request: request, //请求 getProxy: getProxy, //获取代理 disclaimer: disclaimer, //免责声明 saveFile: saveFile, //保存文件 readFile: readFile, //读取文件 aesEncrypt: aesEncrypt, //aes加密 aesDecrypt: aesDecrypt, //aes解密 generateRandomUA: generateRandomUA, //生成随机UA, formatDate: formatDate, //格式化时间 sha1: sha1, //sha1 rsaEncrypt: rsaEncrypt, // rsa加密 rsaDecrypt: rsaDecrypt, // rsa解密 hmacSHA256: hmacSHA256, //HMAC-SHA256签名 findTypes: findTypes, //脚本分类 };
298582245/wqwl_qinglong
6,393
wqwl_绿蜜蜂.js
/** * 脚本:wqwl_绿蜜蜂.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序绿蜜蜂旧衣服回收 * 环境变量:wqwl_lvmf,多个换行或新建多个变量 * 环境变量描述:抓包Headers下的access-token和user-token,格式例如:access-token#user-token#备注1 * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 0 * * * 一天一次即可 */ const axios = require('axios'); const fs = require('fs'); !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); const isNotify = true; // 是否通知 let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } let index = 0; const ckName = 'wqwl_lvmf'; const name = '微信小程序绿蜜蜂旧衣服回收' class Task { constructor(ck) { this.index = index++; this.baseURL = 'https://lmf.lvmifo.com/api' this.ck = ck } async init(ck) { const ckData = ck.split('#') if (ckData.length < 2) { return sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 2) { this.remark = ckData[1]; } else { this.remark = ckData[2]; } this.accessToken = ckData[0]; this.userToken = ckData[1]; this.headers = { "accept": "*/*", "accept-language": "zh-CN,zh;q=0.9", "access-token": this.accessToken, "content-type": "application/x-www-form-urlencoded", "lat": "", "lng": "", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "this-shop-id": "0", "user-token": this.userToken, "xweb_xhr": "1", "Referer": "https://servicewechat.com/wx6fcde446296d9588/289/page-frame.html", "Referrer-Policy": "unsafe-url", "version": "v1.0.0" } if (process.env["wqwl_daili"] != undefined) { this.proxy = await wqwlkj.getProxy() } else { this.proxy = '' } } // 签到 async sign() { try { if (!(this.accessToken && this.userToken)) return const options = { url: `${this.baseURL}/5dca57afa379e?m=toSign`, headers: this.headers, method: 'GET', } const result = await wqwlkj.request(options, this.proxy) if (result.code === 1) { this.sendMessage(`✅签到成功,获得积分🪙:${result.data.get_integral},获得余额💰:${result.data.get_red_packet}`, true) } else { this.sendMessage(`❌签到失败,${result.msg}`, true) } } catch (e) { throw new Error(`❌请求签到接口失败,${e.message}`) } } // 获取用户信息 async getUserInfo() { try { if (!(this.accessToken && this.userToken)) return const options = { url: `${this.baseURL}/5dca57afa379e?m=getUserInfo`, headers: this.headers, method: 'GET', } const result = await wqwlkj.request(options, this.proxy) if (result.code === 1) { this.sendMessage(`用户数据汇总\n🙍用户信息:${result.data.nick_name}(${result.data.id})\n💰用户财产:积分:${result.data.integral},余额:${result.data.amount}`, true) } else { this.sendMessage(`❌获取用户信息失败,${result.msg}`, true) } } catch (e) { throw new Error(`❌请求用户信息接口失败,${e.message}`) } } async main() { await this.init(this.ck) await wqwlkj.sleep(wqwlkj.getRandom(1, 3)) await this.sign() await wqwlkj.sleep(wqwlkj.getRandom(1, 3)) await this.getUserInfo() await wqwlkj.sleep(wqwlkj.getRandom(1, 3)) } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) wqwlkj.sendMessage(message + "\n") else console.log(message) } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); const tasks = tokens.map(token => new Task(token).main()); await Promise.all(tasks); // 所有任务并发执行 console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
294coder/Efficient-MIF
2,367
Pansharpening_Hyper_SR_Matlab_Test_Package/BT-H/BroveyRegHazeMin.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Brovey data fusion with haze correction % % Interface: % I_Fus_Brovey_Reg = BroveyRegHazeMin(I_MS,I_PAN,ratio) % % Inputs: % I_MS: MS image upsampled at PAN scale; % I_PAN: PAN image; % ratio: Scale ratio between MS and PAN. Pre-condition: Integer value. % % Outputs: % I_Fus_Brovey_Reg: Pansharpened image. % % References: % [Lolli17] S. Lolli, L. Alparone, A. Garzelli, and G. Vivone, "Haze correction for contrast-based multispectral pansharpening", % IEEE Geoscience and Remote Sensing Letters, vol. 14, no. 12, pp. 2255-2259, 2017. % [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods", % IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315. % % % % % % % % % % % % % % % Version: 1 % % % % % % % % % % % % % % % % Copyright (C) 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_Fus_Brovey_Reg = BroveyRegHazeMin(I_MS,I_PAN,ratio) if size(I_MS,3) == 4 prc = 1; minMS = zeros(1,1,4); B = I_MS(:,:,1); G = I_MS(:,:,2); R = I_MS(:,:,3); NIR = I_MS(:,:,4); minMS(1,1,1) = 0.95 * prctile(B(:),prc); minMS(1,1,2) = 0.45 * prctile(G(:),prc); minMS(1,1,3) = 0.40 * prctile(R(:),prc); minMS(1,1,4) = 0.05 * prctile(NIR(:),prc); else minMS = zeros(1,1,size(I_MS,3)); for ii = 1 : size(I_MS, 3) minMS(1,1,ii) = min(min(I_MS(:,:,ii))); end end L = repmat(minMS, [size(I_MS,1) size(I_MS,2)]); imageLR = double(I_MS); imageHR = double(I_PAN); imageHR_LR = LPfilterGauss(imageHR,ratio); h = estimation_alpha(imageLR,imageHR_LR,'global'); alpha(1,1,:) = h; I = sum((imageLR - L) .* repmat(alpha,[size(I_MS,1) size(I_MS,2) 1]),3); imageHR = (imageHR - mean2(imageHR_LR)).*(std2(I)./std2(imageHR_LR)) + mean2(I); I_MS_L = imageLR - L; I_MS_L(I_MS_L < 0) = 0; I_Fus_Brovey_Reg = I_MS_L .* repmat(imageHR./(I+eps),[1 1 size(imageLR,3)]) + L; end
294coder/Efficient-MIF
1,864
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/showImage4LR_zoomin.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Visualize and print the original four-band multispectral image. % % Interface: % showImage4LR(I_F,print,id,flag_cut_bounds,dim_cut,thvalues,L,ratio) % % Inputs: % I_MS: Four band multispectral image; % print: Flag. If print == 1, print EPS image; % id: Identifier (name) of the printed EPS image; % flag_cut_bounds: Cut the boundaries of the viewed Panchromatic image; % dim_cut: Define the dimension of the boundary cut; % th_values: Flag. If th_values == 1, apply an hard threshold to the dynamic range; % L: Radiomatric resolution of the input image; % ratio: Resize factor. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showImage4LR_zoomin(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L,ratio, location1, location2) if flag_cut_bounds I_MS = I_MS(round(dim_cut/ratio):end-round(dim_cut/ratio),round(dim_cut/ratio):end-round(dim_cut/ratio),:); end if th_values I_MS(I_MS > 2^L) = 2^L; I_MS(I_MS < 0) = 0; end IMN = viewimage(I_MS(:,:,1:3)); IMN = IMN(:,:,3:-1:1); if isempty(location2) ent=rectangleonimage(IMN,location1,1, 3, 3, 3, 1); % put close-up to up-right corner figure,imshow(ent,[]) else % type =1 (put to down-left); type =2 (put to down-right); % type =3 (put to up-right); type =4 (put to up-left); ent=rectangleonimage(IMN,location1,1, 3, 3, 3, 1); % put close-up to up-right corner ent=rectangleonimage(ent,location2,1, 3, 2, 3, 2); % put close-up to down-right corner figure,imshow(ent,[]) end if print printImage(IMN,sprintf('Outputs/%d.eps',id)); end end
294coder/Efficient-MIF
1,906
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/tight_subplot.m
function ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w) % tight_subplot creates "subplot" axes with adjustable gaps and margins % % ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w) % % in: Nh number of axes in hight (vertical direction) % Nw number of axes in width (horizontaldirection) % gap gaps between the axes in normalized units (0...1) % or [gap_h gap_w] for different gaps in height and width % marg_h margins in height in normalized units (0...1) % or [lower upper] for different lower and upper margins % marg_w margins in width in normalized units (0...1) % or [left right] for different left and right margins % % out: ha array of handles of the axes objects % starting from upper left corner, going row-wise as in % going row-wise as in % % Example: ha = tight_subplot(3,2,[.01 .03],[.1 .01],[.01 .01]) % for ii = 1:6; axes(ha(ii)); plot(randn(10,ii)); end % set(ha(1:4),'XTickLabel',''); set(ha,'YTickLabel','') % Pekka Kumpulainen 20.6.2010 @tut.fi % Tampere University of Technology / Automation Science and Engineering if nargin<3; gap = .02; end if nargin<4 || isempty(marg_h); marg_h = .05; end if nargin<5; marg_w = .05; end if numel(gap)==1; gap = [gap gap]; end if numel(marg_w)==1; marg_w = [marg_w marg_w]; end if numel(marg_h)==1; marg_h = [marg_h marg_h]; end axh = (1-sum(marg_h)-(Nh-1)*gap(1))/Nh; axw = (1-sum(marg_w)-(Nw-1)*gap(2))/Nw; py = 1-marg_h(2)-axh; ha = zeros(Nh*Nw,1); ii = 0; for ih = 1:Nh px = marg_w(1); for ix = 1:Nw ii = ii+1; ha(ii) = axes('Units','normalized', ... 'Position',[px py axw axh], ... 'XTickLabel','', ... 'YTickLabel',''); px = px+axw+gap(2); end py = py-axh-gap(1); end
294coder/Efficient-MIF
1,957
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/estimation_alpha.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Estimation coefficients linear regression model. % % Interface: % alpha = estimation_alpha(I_MS,I_PAN,type_estimation) % % Inputs: % I_MS: MS image upsampled at PAN scale; % I_PAN: PAN image; % type_estimation: Type of estimation (i.e. local or global). % % Outputs: % alpha: Coefficients estimated by the linear regression model. % % References: % [Vivone14] G. Vivone, R. Restaino, M. Dalla Mura, G. Licciardi, and J. Chanussot, Contrast and error-based fusion schemes for multispectral % image pansharpening, IEEE Geoscience and Remote Sensing Letters, vol. 11, no. 5, pp. 930934, May 2014. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function alpha = estimation_alpha(I_MS,I_PAN,type_estimation) if strcmp(type_estimation,'global') %%%%%%%% Global estimation IHc = reshape(I_PAN,[numel(I_PAN) 1]); ILRc = reshape(I_MS,[size(I_MS,1)*size(I_MS,2) size(I_MS,3)]); alpha = ILRc\IHc; else %%%%%%%% Local estimation block_win = 32; alphas = zeros(size(I_MS,3),1); cont_bl = 0; for ii = 1 : block_win : size(I_MS,1) for jj = 1 : block_win : size(I_MS,2) imHRbl = I_PAN(ii : min(size(I_MS,1),ii + block_win - 1), jj : min(size(I_MS,2),jj + block_win - 1)); imageLRbl = I_MS(ii : min(size(I_MS,1),ii + block_win - 1), jj : min(size(I_MS,2),jj + block_win - 1),:); imageHRc = reshape(imHRbl,[numel(imHRbl) 1]); ILRc = reshape(imageLRbl,[size(imageLRbl,1).*size(imageLRbl,2) size(imageLRbl,3)]); alphah = ILRc\imageHRc; alphas = alphas + alphah; cont_bl = cont_bl + 1; end end alpha = alphas/cont_bl; end end
298582245/wqwl_qinglong
10,221
wqwl_绿袋环保旧衣服回收.js
/** * 脚本:wqwl_绿袋环保旧衣服回收.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序绿袋环保旧衣服回收 * 环境变量:wqwl_lvdhb,多个换行或新建多个变量 * 环境变量描述:抓包Headers下的token,格式例如:token#备注1 * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 3 * * * 一天一次 */ const axios = require('axios'); const fs = require('fs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || true; //并发数,默认4 let bfs = process.env["wqwl_bfs"] || 4; // 是否通知 let isNotify = true; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_lvdhb'; //脚本名称 const name = '微信小程序绿袋环保旧衣服回收' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } let fileData = wqwlkj.readFile('lvdhb') || {} class Task { constructor(ck) { this.index = index++; this.ck = ck this.baseUrl = 'https://www.lvdhb.com/MiniProgramApiCore/api/v3' this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) } async init() { const ckData = this.ck.split('#') if (ckData.length < 1) { return this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 1) { this.remark = ckData[0].slice(0, 8); } else { this.remark = ckData[1]; } this.token = ckData[0]; let ua if (!fileData[this.remark]) fileData[this.remark] = {} if (!fileData[this.remark]['ua']) { ua = wqwlkj.generateRandomUA(); fileData[this.remark]['ua'] = ua } else ua = fileData[this.remark]['ua']; this.sendMessage(`🎲使用ua:${ua}`); this.headers = { "accept": "*/*", "accept-language": "zh-CN,zh;q=0.9", "content-type": "application/json", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "xweb_xhr": "1", "referrer": "https://servicewechat.com/wx55da7d089eab6cdb/139/page-frame.html", "token": this.token, }; if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } return true } async sign() { try { const options = { method: 'POST', url: `${this.baseUrl}/Login/Sign`, headers: this.headers, data: {} } const res = await this.request(options) console.log(res) if (res.Success) this.sendMessage(`✅签到成功,获得积分:${res.Data}`, true) else this.sendMessage(`❌签到失败,${res.Message}`) return true } catch (e) { this.sendMessage(`❌签到请求失败,${e.message}`) return false } } async info() { try { const options = { method: 'GET', url: `${this.baseUrl}/My/GetMyScore`, headers: this.headers, } const res = await this.request(options) console.log(res) if (res) { this.sendMessage(`🪙当前积分${parseInt(res)}`, true) if (parseInt(res) >= 100) { this.sendMessage(`🔁积分达到100以上,准备提现`) await this.withdraw(parseInt(res)) } else { this.sendMessage(`⚠️积分不足100,不提现`) } } else this.sendMessage(`❌信息获取失败,${res}`) return true } catch (e) { this.sendMessage(`❌信息获取请求失败,${e.message}`) return false } } // 提现 async withdraw(score) { try { const withdrawAmount = score const url = `${config.baseUrl}/cash/SaveCash`; const options = { url: url, headers: this.headers, method: 'POST', data: { "AliAccount": "直接到微信钱包的余额", "Score": withdrawAmount.toString() } }; const res = await this.request(options); if (res.Success) { this.sendMessage(`✅提现成功,提现积分:${withdrawAmount}`, true) } else { this.sendMessage(`❌提现失败: ${res.Message || '未知错误'}`, true) } } catch (e) { this.sendMessage(`❌提现请求失败,${e.message}`) return false } } async main() { const isFinish = await this.init() if (!isFinish) return await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) const bool = await this.sign() if (!bool) return await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.info() } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); return data; } catch (error) { this.sendMessage(`🔐检测到请求发生错误,正在重试...`) // 刷新代理 let newProxy; if (isProxy) { newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); } else { this.sendMessage(`⚠️未使用代理`); newProxy = true } if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } wqwlkj.saveFile(fileData, 'lvdhb') console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
298582245/wqwl_qinglong
872
README.md
# wqwl_qinglong 一些辣鸡的青龙脚本,QQ裙:960690899 ## 💡食用指南 - 1. 下载 [wqwl_require.js](https://github.com/298582245/wqwl_qinglong/blob/main/wqwl_require.js) - 2. 下载需要的脚本到相同的目录下 - 3. 配置脚本需要的环境变量 - 4. 运行脚本 ## ⚠️免责声明 - 本仓库发布的 wqwl_qinglong 项目中涉及的解锁解密分析脚本仅用于测试、学习和研究,禁止用于商业目的。 其合法性、准确性、完整性和有效性无法得到保证。 请根据实际情况作出自己的判断。 - 禁止任何官方账号或自媒体以任何形式复制或发布本项目中的所有资源文件。 - 本仓库不负责任何脚本问题,包括但不限于任何脚本错误导致的任何损失或损坏。 - 任何间接使用该脚本的用户,包括但不限于建立 VPS 或在某些行为违反国家/地区法律或相关法规时传播该脚本,本仓库不承担由此造成的任何隐私泄露或其他后果。 - 请勿将本脚本项目的任何内容用于商业或非法目的,否则所造成的后果由您自行承担。 - 任何单位或个人认为项目脚本可能侵犯其权利时,应及时通知并提供身份证明和所有权证明。 我们会在收到认证文件后删除相应的脚本。 - 任何以任何方式或直接或间接使用 wqwl_qinglong 项目的任何脚本的人都应该仔细阅读此声明。本仓库保留随时更改或补充本免责声明的权利。 一旦您使用并复制了 wqwl_qinglong 项目的任何相关脚本或规则,您就被视为接受了本免责声明。 - 您必须在下载后 24 小时内从您的电脑或手机上彻底删除以上内容。 > 您在本仓库使用或复制了本库中由本人开发的任何脚本,即视为已接受此声明。请在使用前仔细阅读以上条款。 ## ⚖️License [GPLv3](https://github.com/298582245/wqwl_qinglong/blob/main/LICENSE) licensed.
2881099/FreeSql.AdminLTE
16,695
Examples/net80_blazor/Infrastructure/Extensions/UtilConvertExtension.cs
using System; using System.Collections; using System.Collections.Concurrent; using System.Globalization; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Text; public static class UtilConvertExtension { #region ExpressionTree static int SetSetPropertyOrFieldValueSupportExpressionTreeFlag = 1; static ConcurrentDictionary<Type, ConcurrentDictionary<string, Action<object, string, object>>> _dicSetPropertyOrFieldValue = new ConcurrentDictionary<Type, ConcurrentDictionary<string, Action<object, string, object>>>(); public static void SetPropertyOrFieldValue(this Type entityType, object entity, string propertyName, object value) { if (entity == null) return; if (entityType == null) entityType = entity.GetType(); if (SetSetPropertyOrFieldValueSupportExpressionTreeFlag == 0) { if (GetPropertiesDictIgnoreCase(entityType).TryGetValue(propertyName, out var prop)) { prop.SetValue(entity, value, null); return; } if (GetFieldsDictIgnoreCase(entityType).TryGetValue(propertyName, out var field)) { field.SetValue(entity, value); return; } throw new Exception($"The property({propertyName}) was not found in the type({entityType.DisplayCsharp()})"); } Action<object, string, object> func = null; try { func = _dicSetPropertyOrFieldValue .GetOrAdd(entityType, et => new ConcurrentDictionary<string, Action<object, string, object>>()) .GetOrAdd(propertyName, pn => { var t = entityType; MemberInfo memberinfo = entityType.GetPropertyOrFieldIgnoreCase(pn); var parm1 = Expression.Parameter(typeof(object)); var parm2 = Expression.Parameter(typeof(string)); var parm3 = Expression.Parameter(typeof(object)); var var1Parm = Expression.Variable(t); var exps = new List<Expression>(new Expression[] { Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) }); if (memberinfo != null) { exps.Add( Expression.Assign( Expression.MakeMemberAccess(var1Parm, memberinfo), Expression.Convert( parm3, memberinfo.GetPropertyOrFieldType() ) ) ); } return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile(); }); } catch { System.Threading.Interlocked.Exchange(ref SetSetPropertyOrFieldValueSupportExpressionTreeFlag, 0); SetPropertyOrFieldValue(entityType, entity, propertyName, value); return; } func(entity, propertyName, value); } #endregion #region 常用缓存的反射方法 static ConcurrentDictionary<Type, Dictionary<string, PropertyInfo>> _dicGetPropertiesDictIgnoreCase = new ConcurrentDictionary<Type, Dictionary<string, PropertyInfo>>(); public static Dictionary<string, PropertyInfo> GetPropertiesDictIgnoreCase(this Type that) => that == null ? null : _dicGetPropertiesDictIgnoreCase.GetOrAdd(that, tp => { var props = that.GetProperties().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164 var dict = new Dictionary<string, PropertyInfo>(StringComparer.CurrentCultureIgnoreCase); foreach (var prop in props) { if (dict.TryGetValue(prop.Name, out var existsProp)) { if (existsProp.DeclaringType != prop) dict[prop.Name] = prop; continue; } dict.Add(prop.Name, prop); } return dict; }); static ConcurrentDictionary<Type, Dictionary<string, FieldInfo>> _dicGetFieldsDictIgnoreCase = new ConcurrentDictionary<Type, Dictionary<string, FieldInfo>>(); public static Dictionary<string, FieldInfo> GetFieldsDictIgnoreCase(this Type that) => that == null ? null : _dicGetFieldsDictIgnoreCase.GetOrAdd(that, tp => { var fields = that.GetFields().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164 var dict = new Dictionary<string, FieldInfo>(StringComparer.CurrentCultureIgnoreCase); foreach (var field in fields) { if (dict.ContainsKey(field.Name)) dict[field.Name] = field; else dict.Add(field.Name, field); } return dict; }); public static MemberInfo GetPropertyOrFieldIgnoreCase(this Type that, string name) { if (GetPropertiesDictIgnoreCase(that).TryGetValue(name, out var prop)) return prop; if (GetFieldsDictIgnoreCase(that).TryGetValue(name, out var field)) return field; return null; } public static Type GetPropertyOrFieldType(this MemberInfo that) { if (that is PropertyInfo prop) return prop.PropertyType; if (that is FieldInfo field) return field.FieldType; return null; } #endregion #region 类型转换 internal static string ToInvariantCultureToString(this object obj) => obj is string objstr ? objstr : string.Format(CultureInfo.InvariantCulture, @"{0}", obj); public static void MapSetListValue(this object[] list, Dictionary<string, Func<object[], object>> valueHandlers) { if (list == null) return; for (int idx = list.Length - 2, c = 0; idx >= 0 && c < 2; idx -= 2) { if (valueHandlers.TryGetValue(list[idx]?.ToString(), out var tryFunc)) { c++; var value = list[idx + 1] as object[]; if (value != null) list[idx + 1] = tryFunc(value); } } } public static T MapToClass<T>(this object[] list, Encoding encoding) { if (list == null) return default(T); if (list.Length % 2 != 0) throw new ArgumentException(nameof(list)); var ttype = typeof(T); var ret = (T)ttype.CreateInstanceGetDefaultValue(); for (var a = 0; a < list.Length; a += 2) { var name = list[a].ToString().Replace("-", "_"); var prop = ttype.GetPropertyOrFieldIgnoreCase(name); if (prop == null) continue; // throw new ArgumentException($"{typeof(T).DisplayCsharp()} undefined Property {list[a]}"); if (list[a + 1] == null) continue; ttype.SetPropertyOrFieldValue(ret, prop.Name, prop.GetPropertyOrFieldType().FromObject(list[a + 1], encoding)); } return ret; } public static Dictionary<string, T> MapToHash<T>(this object[] list, Encoding encoding) { if (list == null) return null; if (list.Length % 2 != 0) throw new ArgumentException($"Array {nameof(list)} length is not even"); var dic = new Dictionary<string, T>(); for (var a = 0; a < list.Length; a += 2) { var key = list[a].ToInvariantCultureToString(); if (dic.ContainsKey(key)) continue; var val = list[a + 1]; if (val == null) dic.Add(key, default(T)); else dic.Add(key, val is T conval ? conval : (T)typeof(T).FromObject(val, encoding)); } return dic; } public static List<KeyValuePair<string, T>> MapToKvList<T>(this object[] list, Encoding encoding) { if (list == null) return null; if (list.Length % 2 != 0) throw new ArgumentException($"Array {nameof(list)} length is not even"); var ret = new List<KeyValuePair<string, T>>(); for (var a = 0; a < list.Length; a += 2) { var key = list[a].ToInvariantCultureToString(); var val = list[a + 1]; if (val == null) ret.Add(new KeyValuePair<string, T>(key, default(T))); else ret.Add(new KeyValuePair<string, T>(key, val is T conval ? conval : (T)typeof(T).FromObject(val, encoding))); } return ret; } public static List<T> MapToList<T>(this object[] list, Func<object, object, T> selector) { if (list == null) return null; if (list.Length % 2 != 0) throw new ArgumentException($"Array {nameof(list)} length is not even"); var ret = new List<T>(); for (var a = 0; a < list.Length; a += 2) { var selval = selector(list[a], list[a + 1]); if (selval != null) ret.Add(selval); } return ret; } internal static T ConvertTo<T>(this object value) => (T)typeof(T).FromObject(value); static ConcurrentDictionary<Type, Func<string, object>> _dicFromObject = new ConcurrentDictionary<Type, Func<string, object>>(); public static object FromObject(this Type targetType, object value, Encoding encoding = null) { if (targetType == typeof(object)) return value; if (encoding == null) encoding = Encoding.UTF8; var valueIsNull = value == null; var valueType = valueIsNull ? typeof(string) : value.GetType(); if (valueType == targetType) return value; if (valueType == typeof(byte[])) //byte[] -> guid { if (targetType == typeof(Guid)) { var bytes = value as byte[]; return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty; } if (targetType == typeof(Guid?)) { var bytes = value as byte[]; return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null; } } if (targetType == typeof(byte[])) //guid -> byte[] { if (valueIsNull) return null; if (valueType == typeof(Guid) || valueType == typeof(Guid?)) { var bytes = new byte[16]; var guidN = ((Guid)value).ToString("N"); for (var a = 0; a < guidN.Length; a += 2) bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber); return bytes; } return encoding.GetBytes(value.ToInvariantCultureToString()); } else if (targetType.IsArray) { if (value is Array valueArr) { var targetElementType = targetType.GetElementType(); var sourceArrLen = valueArr.Length; var target = Array.CreateInstance(targetElementType, sourceArrLen); for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a); return target; } //if (value is IList valueList) //{ // var targetElementType = targetType.GetElementType(); // var sourceArrLen = valueList.Count; // var target = Array.CreateInstance(targetElementType, sourceArrLen); // for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a); // return target; //} } var func = _dicFromObject.GetOrAdd(targetType, tt => { if (tt == typeof(object)) return vs => vs; if (tt == typeof(string)) return vs => vs; if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray(); if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault(); if (tt == typeof(bool)) return vs => { if (vs == null) return false; switch (vs.ToLower()) { case "true": case "1": return true; } return false; }; if (tt == typeof(bool?)) return vs => { if (vs == null) return false; switch (vs.ToLower()) { case "true": case "1": return true; case "false": case "0": return false; } return null; }; if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (byte?)tryval : null); if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (decimal?)tryval : null); if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (double?)tryval : null); if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (float?)tryval : null); if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (int?)tryval : null); if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (long?)tryval : null); if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (sbyte?)tryval : null); if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (short?)tryval : null); if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (uint?)tryval : null); if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (ulong?)tryval : null); if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (ushort?)tryval : null); if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue); if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null); if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue); if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null); if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero); if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null); if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty); if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null); if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0); if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (BigInteger?)tryval : null); if (tt.NullableTypeOrThis().IsEnum) { var tttype = tt.NullableTypeOrThis(); var ttdefval = tt.CreateInstanceGetDefaultValue(); return vs => { if (string.IsNullOrWhiteSpace(vs)) return ttdefval; return Enum.Parse(tttype, vs, true); }; } var localTargetType = targetType; var localValueType = valueType; return vs => { if (vs == null) return null; throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}"); }; }); var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString()); return func(valueStr); } #endregion }
281677160/openwrt-package
64,947
luci-app-passwall2/luasrc/view/passwall2/node_list/link_share_man.htm
<%+cbi/valueheader%> <% local api = require "luci.passwall2.api" local appname = api.appname local map = self.map local has_ss = api.is_finded("ss-redir") local has_ss_rust = api.is_finded("sslocal") local has_singbox = api.finded_com("sing-box") local has_xray = api.finded_com("xray") local has_hysteria2 = api.finded_com("hysteria") local function get_core(field, candidates) local v = map:get("@global_subscribe[0]", field) if not v or v == "" then for _, c in ipairs(candidates) do if c[1] then return c[2] end end end return v end local ss_type = get_core("ss_type", {{has_ss,"shadowsocks-libev"},{has_ss_rust,"shadowsocks-rust"},{has_singbox,"sing-box"},{has_xray,"xray"}}) local trojan_type = get_core("trojan_type", {{has_singbox,"sing-box"},{has_xray,"xray"}}) local vmess_type = get_core("vmess_type", {{has_xray,"xray"},{has_singbox,"sing-box"}}) local vless_type = get_core("vless_type", {{has_xray,"xray"},{has_singbox,"sing-box"}}) local hysteria2_type = get_core("hysteria2_type", {{has_hysteria2,"hysteria2"},{has_singbox,"sing-box"}}) -%> <script src="<%=resource%>/view/<%=appname%>/qrcode.min.js"></script> <script type="text/javascript">//<![CDATA[ let has_singbox = "<%=has_singbox%>" let has_xray = "<%=has_xray%>" let has_hysteria2 = "<%=has_hysteria2%>" let ss_type = "<%=ss_type%>" let trojan_type = "<%=trojan_type%>" let vmess_type = "<%=vmess_type%>" let vless_type = "<%=vless_type%>" let hysteria2_type = "<%=hysteria2_type%>" function padright(str, cnt, pad) { return str + Array(cnt + 1).join(pad); } function b64EncodeUnicode(str) { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode('0x' + p1); })); } function b64encutf8safe(str) { return b64EncodeUnicode(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, ''); } function b64DecodeUnicode(str) { return decodeURIComponent(Array.prototype.map.call(atob(str), function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); } function b64decutf8safe(str) { var l; str = str.replace(/-/g, "+").replace(/_/g, "/"); l = str.length; l = (4 - l % 4) % 4; if (l) str = padright(str, l, "="); return b64DecodeUnicode(str); } function b64encsafe(str) { return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, '') } function b64decsafe(str) { const orig = str; try { str = str.replace(/-/g, "+").replace(/_/g, "/"); const pad = (4 - str.length % 4) % 4; if (pad) str += "=".repeat(pad); return atob(str); } catch (e) { return orig; } } function dictvalue(d, key) { var v = d[key]; if (typeof (v) === 'undefined' || v === '') return ''; return b64decsafe(v); } function parseNodeUrl(url) { let protocol = url.substring(0, url.indexOf("://")) + ":" let str = "http" + url.substring(url.indexOf("://")) const parsedUrl = new URL(str); var r = { hash: parsedUrl.hash, // #asd host: parsedUrl.host, // localhost:257 hostname: parsedUrl.hostname, // localhost port: parsedUrl.port, // 257 search: parsedUrl.search, // ?asd=asd passwd: parsedUrl.username || parsedUrl.password // username }; return r; } function genQrcode(btn, urlname, sid) { var qrcode_div = document.getElementById("qrcode_div"); qrcode_div.style.display = null; document.getElementById("qrcode").innerHTML = ""; var url = buildUrl(btn, urlname, sid); if (url) { var qrcode = new QRCode(document.getElementById("qrcode"), { width: 150, height: 150 }); qrcode.makeCode(url); } } function buildUrl(btn, urlname, sid) { var opt = { base: "cbid.passwall2", client: true, get: function (opt) { var id = this.base + "." + opt; var obj = document.getElementsByName(id)[0] || document.getElementsByClassName(id)[0] || document.getElementById(id) if (obj) { return obj; } else { return null; } }, getlist: function (opt) { var id = this.base + "." + opt; var objs = document.getElementsByName(id) || document.getElementsByClassName(id); var ret = []; if (objs) { for (var i = 0; i < objs.length; i++) { ret[i] = objs[i].value; } } else { alert("<%:Faltal on get option, please help in debug: %>" + opt); } return ret; }, query: function (param, src, default_value) { var obj = this.get(src); if (obj) { var ret = "&" + param + "="; if (obj.type === "checkbox") { return ret + (obj.checked === true ? "1" : "0"); } else { var result = encodeURIComponent(obj.value); if (result == null || result.trim() == "") { if (default_value) { return ret + default_value; } return ""; } else { return ret + result; } } } return ""; } } opt.base = "cbid." + urlname + "." + sid; opt.client = urlname.indexOf("server") === -1; var v_type = opt.get("type").value; var v_alias = opt.get("remarks"); var dom_prefix = null var protocol = "" if (v_type === "SS") { dom_prefix = "ss_" protocol = "ss" } else if (v_type === "SS-Rust") { dom_prefix = "ssrust_" protocol = "ss" } else if (v_type === "SSR") { dom_prefix = "ssr_" protocol = "ssr" } else if (v_type === "Hysteria2") { dom_prefix = "hysteria2_" protocol = "hysteria2" } else if (v_type === "Xray") { dom_prefix = "xray_" } else if (v_type === "sing-box") { dom_prefix = "singbox_" } var _address = "" if (dom_prefix && dom_prefix != null) { try { var v_server = opt.get(dom_prefix + "address"); const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; if (ipv6Regex.test(v_server.value)) { _address = "[" + v_server.value + "]" } else { _address = v_server.value } } catch (e) { } } var url = null; if (v_type === "SS" || v_type === "SS-Rust" || ((v_type === "sing-box" || v_type === "Xray") && opt.get(dom_prefix + "protocol").value === "shadowsocks")) { protocol = "ss" var v_port = opt.get(dom_prefix + "port"); var v_method = opt.get(dom_prefix + "method") || opt.get(dom_prefix + "ss_method"); var v_password = opt.get(dom_prefix + "password"); url = b64encsafe(v_method.value + ":" + v_password.value) + "@" + _address + ":" + v_port.value + "/?"; var shadow_tls; //生成SS Shadow-TLS 插件参数 const generateShadowTLSBase64 = function(paramStr) { try { let obj = {}; let list = paramStr.split(";"); for (let i = 0; i < list.length; i++) { let kv = list[i].split("="); if (kv.length === 2) { let k = kv[0].trim(), v = kv[1].trim(); let m = k.match(/^v(\d+)$/); if (m && v === "1") obj.version = m[1]; else if (k === "passwd") obj.password = v; else obj[k] = v; } } return b64encsafe(JSON.stringify(obj)); } catch (e) { return ""; } } var params = ""; var v_plugin_dom = opt.get(dom_prefix + "plugin"); if (v_plugin_dom) { var v_plugin = v_plugin_dom.value; if (v_plugin && v_plugin != "none") { if (v_plugin == "simple-obfs" || v_plugin == "obfs-local") { v_plugin = "obfs-local"; } var v_plugin_opts = opt.get(dom_prefix + "plugin_opts").value; if (v_plugin_opts && v_plugin_opts != "") { v_plugin += ";" + v_plugin_opts; } params += "&plugin=" + encodeURIComponent(v_plugin); if (v_plugin_dom.value == "shadow-tls" && v_plugin_opts && v_plugin_opts != "") { params = "shadow-tls=" + generateShadowTLSBase64(v_plugin_opts); shadow_tls = 1; } } } else if (v_type === "sing-box" || v_type === "Xray") { var v_transport = opt.get(dom_prefix + "transport").value; if (v_transport === "ws") { params += opt.query("host", dom_prefix + "ws_host"); params += opt.query("path", dom_prefix + "ws_path"); if (v_type == "sing-box" && opt.get(dom_prefix + "ws_enableEarlyData").checked) { var ws_maxEarlyData = opt.get(dom_prefix + "ws_maxEarlyData").value; params += "?ed=" + ws_maxEarlyData; } } else if (v_transport === "h2") { v_transport = "http"; params += opt.query("host", dom_prefix + "h2_host"); params += opt.query("path", dom_prefix + "h2_path"); } else if (v_transport === "raw" || v_transport === "tcp") { params += opt.query("headerType", dom_prefix + "tcp_guise"); params += opt.query("host", dom_prefix + "tcp_guise_http_host"); params += opt.query("path", dom_prefix + "tcp_guise_http_path"); } else if (v_transport === "mkcp") { v_transport = "kcp"; params += opt.query("headerType", dom_prefix + "mkcp_guise"); params += opt.query("seed", dom_prefix + "mkcp_seed"); } else if (v_transport === "quic") { params += opt.query("headerType", dom_prefix + "quic_guise"); params += opt.query("key", dom_prefix + "quic_key"); params += opt.query("quicSecurity", dom_prefix + "quic_security"); } else if (v_transport === "grpc") { params += opt.query("path", dom_prefix + "grpc_serviceName"); params += opt.query("serviceName", dom_prefix + "grpc_serviceName"); params += opt.query("mode", dom_prefix + "grpc_mode"); } params += "&type=" + v_transport; if (opt.get(dom_prefix + "tls").checked) { var v_security = "tls"; if (opt.get(dom_prefix + "fingerprint") && opt.get(dom_prefix + "fingerprint").value != "") { let v_fp = opt.get(dom_prefix + "fingerprint").value; params += "&fp=" + v_fp; } if (opt.get(dom_prefix + "reality") && opt.get(dom_prefix + "reality").checked) { v_security = "reality"; params += opt.query("pbk", dom_prefix + "reality_publicKey"); params += opt.query("sid", dom_prefix + "reality_shortId"); params += opt.query("spx", dom_prefix + "reality_spiderX"); params += opt.query("pqv", dom_prefix + "reality_mldsa65Verify"); } params += "&security=" + v_security; params += opt.query("alpn", dom_prefix + "alpn"); params += opt.query("sni", dom_prefix + "tls_serverName"); params += opt.query("allowinsecure", dom_prefix + "tls_allowInsecure"); params += opt.query("ech", dom_prefix + "ech_config"); } if (opt.get(dom_prefix + "shadowtls")?.checked) { let st_plugin_str = ""; let st_version = opt.get(dom_prefix + "shadowtls_version")?.value; if (st_version) st_plugin_str += "v" + st_version + "=1;"; let st_password = opt.get(dom_prefix + "shadowtls_password")?.value; if (st_password) st_plugin_str += "passwd=" + st_password +";"; let st_host = opt.get(dom_prefix + "shadowtls_serverName")?.value; if (st_host) st_plugin_str += "host=" + st_host +";"; if (opt.get(dom_prefix + "shadowtls_utls").checked) { let st_fingerprint = opt.get(dom_prefix + "shadowtls_fingerprint")?.value; if (st_fingerprint) st_plugin_str += "fingerprint=" + st_fingerprint; } params = "shadow-tls=" + generateShadowTLSBase64(st_plugin_str); shadow_tls = 1; } } if (shadow_tls) { url = b64encsafe(v_method.value + ":" + v_password.value + "@" + _address + ":" + v_port.value) + "?"; } else { params += "&group=" } params += "#" + encodeURIComponent(v_alias.value); if (params[0] == "&") { params = params.substring(1); } url += params; } else if (v_type === "SSR") { var v_port = opt.get(dom_prefix + "port"); var v_protocol = opt.get(dom_prefix + "protocol"); var v_method = opt.get(dom_prefix + "method"); var v_obfs = opt.get(dom_prefix + "obfs"); var v_password = opt.get(dom_prefix + "password"); var v_obfs_param = opt.get(dom_prefix + "obfs_param"); var v_protocol_param = opt.get(dom_prefix + "protocol_param"); var ssr_str = _address + ":" + v_port.value + ":" + v_protocol.value + ":" + v_method.value + ":" + v_obfs.value + ":" + b64encsafe(v_password.value) + "/?obfsparam=" + b64encsafe(v_obfs_param.value) + "&protoparam=" + b64encsafe(v_protocol_param.value) + "&remarks=" + b64encutf8safe(v_alias.value); url = b64encsafe(ssr_str); } else if ((v_type === "sing-box" || v_type === "Xray") && opt.get(dom_prefix + "protocol").value === "vmess") { protocol = "vmess"; var info = {}; info.v = "2"; info.ps = v_alias.value; info.add = opt.get(dom_prefix + "address").value; //info.add = _address; info.port = opt.get(dom_prefix + "port").value; info.id = opt.get(dom_prefix + "uuid").value; var v_transport = opt.get(dom_prefix + "transport").value; if (v_transport === "ws") { info.host = opt.get(dom_prefix + "ws_host").value; info.path = opt.get(dom_prefix + "ws_path").value; if (v_type == "sing-box" && opt.get(dom_prefix + "ws_enableEarlyData").checked) { var ws_maxEarlyData = opt.get(dom_prefix + "ws_maxEarlyData").value; info.path = info.path + "?ed=" + ws_maxEarlyData; } } else if (v_transport === "h2") { info.host = opt.get(dom_prefix + "h2_host").value; info.path = opt.get(dom_prefix + "h2_path").value; } else if (v_transport === "raw" || v_transport === "tcp") { info.type = opt.get(dom_prefix + "tcp_guise").value; if (info.type === "http") { info.host = opt.get(dom_prefix + "tcp_guise_http_host").value; info.path = opt.get(dom_prefix + "tcp_guise_http_path").value; } } else if (v_transport === "mkcp") { v_transport = "kcp"; info.type = opt.get(dom_prefix + "mkcp_guise").value; info.seed = opt.get(dom_prefix + "mkcp_seed").value; } else if (v_transport === "quic") { info.type = opt.get(dom_prefix + "quic_guise")?.value; info.key = opt.get(dom_prefix + "quic_key")?.value; info.securty = opt.get(dom_prefix + "quic_security")?.value; } else if (v_transport === "grpc") { info.path = opt.get(dom_prefix + "grpc_serviceName").value; } if (info.path && info.path != "") { info.path = encodeURI(info.path); } info.net = v_transport; info.security = opt.get(dom_prefix + "security").value || "auto"; if (opt.get(dom_prefix + "tls").checked) { var v_security = "tls"; info.tls = "tls"; info.sni = opt.get(dom_prefix + "tls_serverName").value; } url = b64EncodeUnicode(JSON.stringify(info)); } else if ((v_type === "sing-box" || v_type === "Xray") && opt.get(dom_prefix + "protocol").value === "vless") { protocol = "vless"; var v_password = opt.get(dom_prefix + "uuid"); var v_port = opt.get(dom_prefix + "port"); url = encodeURIComponent(v_password.value) + "@" + _address + ":" + v_port.value + "?"; var params = ""; var v_transport = opt.get(dom_prefix + "transport").value; if (v_transport === "ws") { params += opt.query("host", dom_prefix + "ws_host"); params += opt.query("path", dom_prefix + "ws_path"); if (v_type == "sing-box" && opt.get(dom_prefix + "ws_enableEarlyData").checked) { var ws_maxEarlyData = opt.get(dom_prefix + "ws_maxEarlyData").value; params += encodeURIComponent("?ed=" + ws_maxEarlyData); } } else if (v_transport === "h2") { v_transport = "http"; params += opt.query("host", dom_prefix + "h2_host"); params += opt.query("path", dom_prefix + "h2_path"); } else if (v_transport === "raw" || v_transport === "tcp") { params += opt.query("headerType", dom_prefix + "tcp_guise"); params += opt.query("host", dom_prefix + "tcp_guise_http_host"); params += opt.query("path", dom_prefix + "tcp_guise_http_path"); } else if (v_transport === "mkcp") { v_transport = "kcp"; params += opt.query("headerType", dom_prefix + "mkcp_guise"); params += opt.query("seed", dom_prefix + "mkcp_seed"); } else if (v_transport === "quic") { params += opt.query("headerType", dom_prefix + "quic_guise"); params += opt.query("key", dom_prefix + "quic_key"); params += opt.query("quicSecurity", dom_prefix + "quic_security"); } else if (v_transport === "grpc") { params += opt.query("path", dom_prefix + "grpc_serviceName"); params += opt.query("serviceName", dom_prefix + "grpc_serviceName"); params += opt.query("mode", dom_prefix + "grpc_mode"); } else if (v_transport === "xhttp") { params += opt.query("host", dom_prefix + "xhttp_host"); params += opt.query("path", dom_prefix + "xhttp_path"); params += opt.query("mode", dom_prefix + "xhttp_mode"); if (opt.get(dom_prefix + "use_xhttp_extra").checked) { params += opt.query("extra", dom_prefix + "xhttp_extra"); } } else if (v_transport === "httpupgrade") { v_transport = "httpupgrade"; params += opt.query("host", dom_prefix + "httpupgrade_host"); params += opt.query("path", dom_prefix + "httpupgrade_path"); } params += "&type=" + v_transport; if (v_type === "sing-box") { params += "&encryption=none"; } else { params += opt.query("encryption", dom_prefix + "encryption"); } if (opt.get(dom_prefix + "tls").checked) { var v_security = "tls"; if (opt.get(dom_prefix + "fingerprint") && opt.get(dom_prefix + "fingerprint").value != "") { let v_fp = opt.get(dom_prefix + "fingerprint").value; params += "&fp=" + v_fp; } if (opt.get(dom_prefix + "reality") && opt.get(dom_prefix + "reality").checked) { v_security = "reality"; params += opt.query("pbk", dom_prefix + "reality_publicKey"); params += opt.query("sid", dom_prefix + "reality_shortId"); params += opt.query("spx", dom_prefix + "reality_spiderX"); params += opt.query("pqv", dom_prefix + "reality_mldsa65Verify"); } if (opt.get(dom_prefix + "flow") && opt.get(dom_prefix + "flow").value) { let v_flow = opt.get(dom_prefix + "flow").value; params += "&flow=" + v_flow; } params += "&security=" + v_security; params += opt.query("alpn", dom_prefix + "alpn"); params += opt.query("sni", dom_prefix + "tls_serverName"); params += opt.query("allowinsecure", dom_prefix + "tls_allowInsecure"); params += opt.query("ech", dom_prefix + "ech_config"); } params += "#" + encodeURI(v_alias.value); if (params[0] == "&") { params = params.substring(1); } url += params; } else if ((v_type === "sing-box" || v_type === "Xray") && opt.get(dom_prefix + "protocol").value === "trojan") { protocol = "trojan"; var v_password = opt.get(dom_prefix + "password"); var v_port = opt.get(dom_prefix + "port"); url = encodeURIComponent(v_password.value) + "@" + _address + ":" + v_port.value + "/?"; var params = ""; var v_transport = opt.get(dom_prefix + "transport").value; if (v_transport === "ws") { params += opt.query("host", dom_prefix + "ws_host"); params += opt.query("path", dom_prefix + "ws_path"); if (v_type == "sing-box" && opt.get(dom_prefix + "ws_enableEarlyData").checked) { var ws_maxEarlyData = opt.get(dom_prefix + "ws_maxEarlyData").value; params += "?ed=" + ws_maxEarlyData; } } else if (v_transport === "h2") { v_transport = "http"; params += opt.query("host", dom_prefix + "h2_host"); params += opt.query("path", dom_prefix + "h2_path"); } else if (v_transport === "raw" || v_transport === "tcp") { params += opt.query("headerType", dom_prefix + "tcp_guise"); params += opt.query("host", dom_prefix + "tcp_guise_http_host"); params += opt.query("path", dom_prefix + "tcp_guise_http_path"); } else if (v_transport === "mkcp") { v_transport = "kcp"; params += opt.query("headerType", dom_prefix + "mkcp_guise"); params += opt.query("seed", dom_prefix + "mkcp_seed"); } else if (v_transport === "quic") { params += opt.query("headerType", dom_prefix + "quic_guise"); params += opt.query("key", dom_prefix + "quic_key"); params += opt.query("quicSecurity", dom_prefix + "quic_security"); } else if (v_transport === "grpc") { params += opt.query("path", dom_prefix + "grpc_serviceName"); params += opt.query("serviceName", dom_prefix + "grpc_serviceName"); params += opt.query("mode", dom_prefix + "grpc_mode"); } params += "&type=" + v_transport; if (opt.get(dom_prefix + "tls").checked) { var v_security = "tls"; if (opt.get(dom_prefix + "fingerprint") && opt.get(dom_prefix + "fingerprint").value != "") { let v_fp = opt.get(dom_prefix + "fingerprint").value; params += "&fp=" + v_fp; } if (opt.get(dom_prefix + "reality") && opt.get(dom_prefix + "reality").checked) { v_security = "reality"; params += opt.query("pbk", dom_prefix + "reality_publicKey"); params += opt.query("sid", dom_prefix + "reality_shortId"); params += opt.query("spx", dom_prefix + "reality_spiderX"); params += opt.query("pqv", dom_prefix + "reality_mldsa65Verify"); } params += "&security=" + v_security; params += opt.query("alpn", dom_prefix + "alpn"); params += opt.query("sni", dom_prefix + "tls_serverName"); params += opt.query("allowinsecure", dom_prefix + "tls_allowInsecure"); params += opt.query("ech", dom_prefix + "ech_config"); } params += "#" + encodeURI(v_alias.value); if (params[0] == "&") { params = params.substring(1); } url += params; } else if ((v_type === "Hysteria2") || (v_type === "sing-box" && opt.get(dom_prefix + "protocol").value === "hysteria2")) { protocol = "hysteria2" var v_port = opt.get(dom_prefix + "port"); var params = ""; params += opt.query("sni", dom_prefix + "tls_serverName"); params += opt.query("insecure", dom_prefix + "tls_allowInsecure"); var v_password = null; if (v_type === "Hysteria2") { v_password = opt.get("hysteria2_auth_password"); params += opt.query("pinSHA256", "hysteria2_tls_pinSHA256"); var dom_obfs = opt.get("hysteria2_obfs"); if (dom_obfs && dom_obfs.value != "") { params += "&obfs=" + "salamander"; params += opt.query("obfs-password", "hysteria2_obfs"); } params += opt.query("mport", "hysteria2_hop"); } else { v_password = opt.get(dom_prefix + "hysteria2_auth_password"); var dom_obfs_type = opt.get(dom_prefix + "hysteria2_obfs_type"); if (dom_obfs_type && dom_obfs_type.value != "") { params += opt.query("obfs", dom_prefix + "hysteria2_obfs_type"); params += opt.query("obfs-password", dom_prefix + "hysteria2_obfs_password"); } params += opt.query("mport", dom_prefix + "hysteria2_hop"); } params = params.replace(/^&/, ""); url = _address + ":" + v_port.value + "?" + params + "#" + encodeURI(v_alias.value); if (v_password) { url = encodeURIComponent(v_password.value) + "@" + url } } else if (v_type === "sing-box" && opt.get(dom_prefix + "protocol").value === "tuic") { protocol = "tuic"; var v_username = opt.get(dom_prefix + "uuid"); var v_password = opt.get(dom_prefix + "password"); var v_port = opt.get(dom_prefix + "port"); url = encodeURIComponent(v_username.value) + ":" + encodeURIComponent(v_password.value) + "@" + _address + ":" + v_port.value + "?"; var params = ""; params += opt.query("sni", dom_prefix + "tls_serverName"); params += opt.query("alpn", dom_prefix + "tuic_alpn"); params += opt.query("congestion_control", dom_prefix + "tuic_congestion_control"); params += opt.query("udp_relay_mode", dom_prefix + "tuic_udp_relay_mode"); params += opt.query("allowinsecure", dom_prefix + "tls_allowInsecure"); params += "#" + encodeURI(v_alias.value); if (params[0] == "&") { params = params.substring(1); } url += params; } else if (v_type === "sing-box" && opt.get(dom_prefix + "protocol").value === "anytls") { protocol = "anytls"; var v_password = opt.get(dom_prefix + "password"); var v_port = opt.get(dom_prefix + "port"); url = encodeURIComponent(v_password.value) + "@" + _address + ":" + v_port.value + "?"; var params = ""; if (opt.get(dom_prefix + "tls").checked) { var v_security = "tls"; if (opt.get(dom_prefix + "fingerprint") && opt.get(dom_prefix + "fingerprint").value != "") { let v_fp = opt.get(dom_prefix + "fingerprint").value; params += "&fp=" + v_fp; } if (opt.get(dom_prefix + "reality") && opt.get(dom_prefix + "reality").checked) { v_security = "reality"; params += opt.query("pbk", dom_prefix + "reality_publicKey"); params += opt.query("sid", dom_prefix + "reality_shortId"); } params += "&security=" + v_security; params += opt.query("alpn", dom_prefix + "alpn"); params += opt.query("sni", dom_prefix + "tls_serverName"); params += opt.query("allowinsecure", dom_prefix + "tls_allowInsecure"); } params += "#" + encodeURI(v_alias.value); if (params[0] == "&") { params = params.substring(1); } url += params; } if (url) { url = protocol.toLowerCase() + "://" + url; return url; } else { alert("<%:Not a supported scheme:%> " + v_type); } return false; } function exportUrl(btn, urlname, sid) { var url = buildUrl(btn, urlname, sid); if (url) { var textarea = document.createElement("textarea"); textarea.textContent = url; textarea.style.position = "fixed"; document.body.appendChild(textarea); textarea.select(); try { var s = document.getElementById(urlname + "-status"); if (!s) { alert("Never"); return false; } document.execCommand("copy"); // Security exception may be thrown by some browsers. s.innerHTML = "<font color='green'><%:Share URL to clipboard successfully.%></font>"; } catch (ex) { s.innerHTML = "<font color='red'><%:Share URL to clipboard unable.%></font>"; } finally { document.body.removeChild(textarea); } } } function unbracketIP(server) { if (!server) return ''; return server.replace(/^\[/, '').replace(/\]$/, ''); } function fromUrl(btn, urlname, sid) { var opt = { base: 'cbid.passwall2', client: true, get: function (opt) { var obj; var id = this.base + '.' + opt; obj = document.getElementsByName(id)[0] || document.getElementById(id); if (obj) { var combobox = document.getElementById('cbi.combobox.' + id); if (combobox) { obj.combobox = combobox; } var div = document.getElementById(id); if (div && div.getElementsByTagName("li").length > 0) { obj = div; } return obj; } else { return null; } }, set: function (opt, val) { var obj; obj = this.get(opt); if (obj) { var event = document.createEvent("HTMLEvents"); event.initEvent("change", true, true); if (obj.type === 'checkbox') { obj.checked = val; } else { obj.value = val; if (obj.combobox) { obj.combobox.value = val; } var list = obj.getElementsByTagName("li"); if (list.length > 0) { for (var i = 0; i < list.length; i++) { var li = list[i]; var data = li.getAttribute("data-value"); li.removeAttribute("selected"); li.removeAttribute("display"); if (data && data == val) { li.setAttribute("selected", true); li.setAttribute("display", "0"); } } var input = document.getElementsByName(obj.id)[0]; if (input) { input.value = val; } else { var input = document.createElement("input"); input.setAttribute("type", "hidden"); input.setAttribute("name", obj.id); input.setAttribute("value", val); obj.appendChild(input); } } } try { obj.dispatchEvent(event); } catch (err) {} } else { //alert('<%:Faltal on set option, please help in debug: %>' + opt + ' = ' + val); // 处理 DynamicList var fullName = this.base + '.' + opt; var lists = document.querySelectorAll('.cbi-dynlist'); for (var i = 0; i < lists.length; i++) { var parent = lists[i].closest('.cbi-value'); if (!parent) continue; // 尝试从 label 的 for 属性中提取 fullName var label = parent.querySelector('label.cbi-value-title'); var labelFor = label?.getAttribute('for'); if (labelFor === fullName) { var input = lists[i].querySelector('input[type="text"]'); var addBtn = lists[i].querySelector('.cbi-button-add'); if (input && addBtn) { input.value = val; addBtn.click(); } break; } } } }, setlist: function (opt, vlist) { var id = this.base + "." + opt; var objs = document.getElementsByName(id) || document.getElementsByClassName(id); if (objs) { var values = ""; for (var i = 0; i < vlist.length; i++) { values += vlist[i] + ", "; } alert("Manually input the option:\n" + opt + "s:\n[" + values + "]"); } else { //alert("<%:Faltal on set option, please help in debug: %>" + opt); } } } var s = document.getElementById(urlname + '-status'); if (!s) { alert("Never"); return false; } opt.base = "cbid." + urlname + "." + sid; opt.client = urlname.indexOf("server") === -1; var ssrurl = prompt('<%:Paste Share URL Here%>', ''); if (ssrurl === null || ssrurl === "") { return false; } ssrurl = ssrurl.replace(/&amp;/gi, '&').replace(/\s*#\s*/, '#').trim(); //一些奇葩的链接用"&amp;"当做"&","#"前后带空格 s.innerHTML = ""; var ssu = ssrurl.split('://'); var event = document.createEvent("HTMLEvents"); event.initEvent("change", true, true); var dom_prefix = null if (ssu[0] === "ssr") { dom_prefix = "ssr_" //var b64c = ssu[1].match(/([A-Za-z0-9_-]+)/); var sstr = b64decsafe((ssu[1] || "").replace(/#.*/, "").trim()); var ploc = sstr.indexOf("/?"); var url0 = "", param = ""; if (ploc > 0) { url0 = sstr.substr(0, ploc); param = sstr.substr(ploc + 2); } else { var url0 = sstr; } var ssm = url0.match(/^(.+):([^:]+):([^:]*):([^:]+):([^:]*):([^:]+)/); if (!ssm || ssm.length < 7) { s.innerHTML = "<font color='red'><%:Invalid Share URL Format%></font>"; return false; } var pdict = {}; if (param.length > 2) { var a = param.split('&'); for (var i = 0; i < a.length; i++) { var b = a[i].split('='); pdict[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || ''); } } opt.set('type', "SSR"); opt.set(dom_prefix + 'address', unbracketIP(ssm[1])); opt.set(dom_prefix + 'port', ssm[2]); opt.set(dom_prefix + 'protocol', ssm[3]); opt.set(dom_prefix + 'method', ssm[4]); opt.set(dom_prefix + 'obfs', ssm[5]); opt.set(dom_prefix + 'password', b64decsafe(ssm[6])); opt.set(dom_prefix + 'obfs_param', dictvalue(pdict, 'obfsparam')); opt.set(dom_prefix + 'protocol_param', dictvalue(pdict, 'protoparam')); var rem = pdict['remarks']; if (typeof (rem) !== 'undefined' && rem !== '' && rem.length > 0) opt.set('remarks', b64decutf8safe(rem)); } if (ssu[0] === "ss") { var url0 = ssu[1] || ""; param = ""; var ploc = url0.indexOf("#"); if (ploc >= 0) { param = url0.substr(ploc + 1); url0 = url0.substr(0, ploc); } var queryIndex = (url0 = url0.replace('/?', '?')).indexOf("?"); var queryStr = ""; if (queryIndex >= 0) { queryStr = url0.substr(queryIndex + 1); url0 = url0.substr(0, queryIndex); } var queryParam = {}; queryParam = Object.fromEntries(new URLSearchParams(queryStr)); var server, port, method, password, plugin, pluginOpts; var sipIndex = url0.indexOf("@"); if (sipIndex !== -1) { // SIP002 base64(method:pass)@host:port var userInfo = b64decsafe(decodeURIComponent(url0.substr(0, sipIndex))); var temp = url0.substr(sipIndex + 1); var serverInfo = temp.split(":"); server = serverInfo[0]; port = serverInfo[1]; var userInfoSplitIndex = userInfo.indexOf(":"); if (userInfoSplitIndex !== -1) { method = userInfo.substr(0, userInfoSplitIndex); password = userInfo.substr(userInfoSplitIndex + 1); } else { password = url0.substr(0, sipIndex); //一些链接用明文uuid做密码 } } else { // base64(method:pass@host:port) var sstr = b64decsafe(decodeURIComponent(url0)); var m2022 = sstr.match(/^([^:]+):([^:]+):([^@]+)@([^:]+):(\d+)$/); var mNormal = sstr.match(/^([^:]+):([^@]+)@([^:]+):(\d+)$/); if (m2022) { method = m2022[1]; password = m2022[2] + ":" + m2022[3]; server = m2022[4]; port = m2022[5]; } else if (mNormal) { method = mNormal[1]; password = mNormal[2]; server = mNormal[3]; port = mNormal[4]; } } // 判断密码是否经过url编码 const isURLEncodedPassword = function(pwd) { if (!/%[0-9A-Fa-f]{2}/.test(pwd)) return false; try { const decoded = decodeURIComponent(pwd.replace(/\+/g, "%20")); const reencoded = encodeURIComponent(decoded); return reencoded === pwd; } catch (e) { return false; } } password = isURLEncodedPassword(password) ? decodeURIComponent(password) : password; if (queryParam.plugin) { var pluginParams = decodeURIComponent(queryParam.plugin).split(";"); plugin = pluginParams.shift(); pluginOpts = pluginParams.join(";"); } if (has_xray && ((ss_type !== "xray" && ss_type !== "sing-box" && queryParam.type) || ss_type == "xray")) { dom_prefix = "xray_" opt.set('type', "Xray"); opt.set(dom_prefix + 'protocol', "shadowsocks"); } else if (has_singbox && ((ss_type !== "xray" && ss_type !== "sing-box" && queryParam.type) || ss_type == "sing-box")) { dom_prefix = "singbox_" opt.set('type', "sing-box"); opt.set(dom_prefix + 'protocol', "shadowsocks"); } else if (ss_type == "shadowsocks-rust") { dom_prefix = "ssrust_" opt.set('type', "SS-Rust"); } else { if (["2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305"].includes(method)) { dom_prefix = "ssrust_" opt.set('type', "SS-Rust"); } else { dom_prefix = "ss_" opt.set('type', "SS"); } } const _method = (method || "none").toLowerCase(); const mapping = { "chacha20-poly1305": "chacha20-ietf-poly1305", "xchacha20-poly1305": "xchacha20-ietf-poly1305", }; method = mapping[_method] || _method; opt.set(dom_prefix + 'address', unbracketIP(server)); opt.set(dom_prefix + 'port', port); opt.set(dom_prefix + 'password', password || ""); opt.set(dom_prefix + 'method', method || ""); opt.set(dom_prefix + 'ss_method', method || ""); if (plugin && plugin != "none") { plugin = (plugin === "simple-obfs") ? "obfs-local" : plugin; opt.set(dom_prefix + 'plugin_enabled', true); opt.set(dom_prefix + 'plugin', plugin || "none"); opt.set(dom_prefix + 'plugin_opts', pluginOpts || ""); //obfs-local插件转换成xray支持的格式 if (plugin == "obfs-local" && dom_prefix == "xray_") { var obfs = pluginOpts.match(/obfs=([^;]+)/); var obfs_host = pluginOpts.match(/obfs-host=([^;]+)/); obfs = obfs ? obfs[1] : ""; obfs_host = obfs_host ? obfs_host[1] : ""; if (obfs === "http") { opt.set(dom_prefix + 'transport', "raw"); opt.set(dom_prefix + 'tcp_guise', "http"); opt.set(dom_prefix + 'tcp_guise_http_host', obfs_host || ''); } else if (obfs === "tls") { opt.set(dom_prefix + 'tls', true); opt.set(dom_prefix + 'tls_serverName', obfs_host || ''); opt.set(dom_prefix + 'tls_allowInsecure', true); } } } else { opt.set(dom_prefix + 'plugin', "none"); } if (param !== undefined) { opt.set('remarks', decodeURIComponent(param)); } if (Object.keys(queryParam).length > 0 && !queryParam.plugin) { if (queryParam.security) { if (queryParam.security == "tls") { opt.set(dom_prefix + 'tls', true); opt.set(dom_prefix + 'reality', false); opt.set(dom_prefix + 'alpn', queryParam.alpn || 'default'); opt.set(dom_prefix + 'tls_serverName', queryParam.sni || ''); opt.set(dom_prefix + 'tls_allowInsecure', true); if ((queryParam.allowinsecure ?? '0') === '0' && (queryParam.insecure ?? '0') === '0') { opt.set(dom_prefix + 'tls_allowInsecure', false); } if (queryParam.fp && queryParam.fp.trim() != "") { opt.set(dom_prefix + 'utls', true); opt.set(dom_prefix + 'fingerprint', queryParam.fp); } opt.set(dom_prefix + 'ech', !!queryParam.ech); opt.set(dom_prefix + 'ech_config', queryParam.ech || ''); } if (queryParam.security == "reality") { opt.set(dom_prefix + 'tls', true); opt.set(dom_prefix + 'reality', true); opt.set(dom_prefix + 'alpn', queryParam.alpn || 'default'); opt.set(dom_prefix + 'tls_serverName', queryParam.sni || ''); if (queryParam.fp && queryParam.fp.trim() != "") { opt.set(dom_prefix + 'utls', true); opt.set(dom_prefix + 'fingerprint', queryParam.fp); } opt.set(dom_prefix + 'reality_publicKey', queryParam.pbk || ''); opt.set(dom_prefix + 'reality_shortId', queryParam.sid || ''); opt.set(dom_prefix + 'reality_spiderX', queryParam.spx || ''); opt.set(dom_prefix + 'use_mldsa65Verify', !!queryParam.pqv); opt.set(dom_prefix + 'reality_mldsa65Verify', queryParam.pqv || ''); } } queryParam.type = queryParam.type?.toLowerCase(); if (queryParam.type === "kcp") { queryParam.type = "mkcp"; } if (queryParam.type === "h2") { queryParam.type = "http"; } if (dom_prefix == "singbox_" && queryParam.type === "raw") { queryParam.type = "tcp"; } else if (dom_prefix == "xray_" && queryParam.type === "tcp") { queryParam.type = "raw"; } if (dom_prefix == "xray_" && queryParam.type === "http") { opt.set(dom_prefix + 'transport', "xhttp"); } else { opt.set(dom_prefix + 'transport', queryParam.type); } if (queryParam.type === "raw" || queryParam.type === "tcp") { opt.set(dom_prefix + 'tcp_guise', queryParam.headerType || "none"); if (queryParam.headerType && queryParam.headerType != "none") { opt.set(dom_prefix + 'tcp_guise_http_host', queryParam.host || ""); opt.set(dom_prefix + 'tcp_guise_http_path', queryParam.path || ""); } } else if (queryParam.type === "ws") { opt.set(dom_prefix + 'ws_host', queryParam.host || ""); opt.set(dom_prefix + 'ws_path', queryParam.path || ""); if (dom_prefix == "singbox_" && queryParam.path && queryParam.path.length > 1) { var ws_path_params = {}; var ws_path_dat = queryParam.path.split('?'); var ws_path = ws_path_dat[0]; var ws_path_params = {}; var ws_path_params_array = (ws_path_dat[1] || '').split('&'); for (i = 0; i < ws_path_params_array.length; i++) { var kv = ws_path_params_array[i].split('='); ws_path_params[decodeURIComponent(kv[0]).toLowerCase()] = decodeURIComponent(kv[1] || ''); } if (ws_path_params.ed) { opt.set(dom_prefix + 'ws_path', ws_path); opt.set(dom_prefix + 'ws_enableEarlyData', true); opt.set(dom_prefix + 'ws_maxEarlyData', ws_path_params.ed); opt.set(dom_prefix + 'ws_earlyDataHeaderName', 'Sec-WebSocket-Protocol'); } } } else if (queryParam.type === "http") { if (dom_prefix == "xray_") { opt.set(dom_prefix + 'xhttp_mode', "stream-one"); opt.set(dom_prefix + 'xhttp_host', queryParam.host || ""); opt.set(dom_prefix + 'xhttp_path', queryParam.path || ""); } else { opt.set(dom_prefix + 'http_host', queryParam.host || ""); opt.set(dom_prefix + 'http_path', queryParam.path || ""); } } else if (queryParam.type === "quic") { opt.set(dom_prefix + 'quic_guise', queryParam.headerType || "none"); opt.set(dom_prefix + 'quic_security', queryParam.quicSecurity); opt.set(dom_prefix + 'quic_key', queryParam.key); } else if (queryParam.type === "mkcp") { opt.set(dom_prefix + 'mkcp_guise', queryParam.headerType || "none"); opt.set(dom_prefix + 'mkcp_seed', queryParam.seed || ""); } else if (queryParam.type === "grpc") { opt.set(dom_prefix + 'grpc_serviceName', (queryParam.serviceName || queryParam.path) || ""); opt.set(dom_prefix + 'grpc_mode', queryParam.mode || "gun"); } if (queryParam["shadow-tls"]) { //解析SS Shadow-TLS 插件参数 const parseShadowTLSParams = function(base64Str, outObj) { try { let obj = JSON.parse(b64decsafe(base64Str)); if (outObj && typeof outObj === "object") { for (let k in obj) outObj[k] = obj[k]; } let out = []; if (obj.version) out.push("v" + obj.version + "=1"); if (obj.password) out.push("passwd=" + obj.password); for (let k in obj) if (k !== "version" && k !== "password") out.push(k + "=" + obj[k]); return out.join(";"); } catch (e) { return ""; } } if (dom_prefix === "ssrust_") { opt.set(dom_prefix + 'plugin_enabled', true); opt.set(dom_prefix + 'plugin', "shadow-tls"); let shadowtlsOpt = parseShadowTLSParams(queryParam["shadow-tls"]); opt.set(dom_prefix + 'plugin_opts', shadowtlsOpt || ""); } else if (dom_prefix === "singbox_") { let shadowtlsOpt = {}; parseShadowTLSParams(queryParam["shadow-tls"], shadowtlsOpt); if (Object.keys(shadowtlsOpt).length > 0) { opt.set(dom_prefix + 'shadowtls', true); opt.set(dom_prefix + 'shadowtls_version', shadowtlsOpt.version || "1"); opt.set(dom_prefix + 'shadowtls_password', shadowtlsOpt.password || ""); opt.set(dom_prefix + 'shadowtls_serverName', shadowtlsOpt.host || ""); if (shadowtlsOpt.fingerprint) { opt.set(dom_prefix + 'shadowtls_utls', true); opt.set(dom_prefix + 'shadowtls_fingerprint', shadowtlsOpt.fingerprint || "chrome"); } } } } } } if (ssu[0] === "trojan") { if (trojan_type == "sing-box" && has_singbox) { dom_prefix = "singbox_" opt.set('type', "sing-box"); opt.set(dom_prefix + 'protocol', "trojan"); } else { dom_prefix = "xray_" opt.set('type', "Xray"); opt.set(dom_prefix + 'protocol', "trojan"); } var m = parseNodeUrl(ssrurl); var password = m.passwd; if (password === "") { s.innerHTML = "<font color='red'><%:Invalid Share URL Format%></font>"; return false; } var queryParam = {}; if (m.search.length > 1) { var query = m.search.replace('/?', '?').split('?'); var queryParams = query[1]; var queryArray = queryParams.split('&'); var params; for (var i = 0; i < queryArray.length; i++) { params = queryArray[i].split('='); queryParam[decodeURIComponent(params[0]).toLowerCase()] = decodeURIComponent(params[1] || ''); } } opt.set(dom_prefix + 'mux', queryParam.mux === '1'); opt.set(dom_prefix + 'address', unbracketIP(m.hostname)); opt.set(dom_prefix + 'port', m.port || "443"); opt.set(dom_prefix + 'password', decodeURIComponent(password)); queryParam.type = queryParam.type ? queryParam.type.toLowerCase() : "tcp"; if (queryParam.type === "kcp" || queryParam.type === "mkcp") { queryParam.type = "mkcp"; } if (queryParam.type === "h2" || queryParam.type === "http") { queryParam.type = "http"; } if (dom_prefix == "singbox_" && queryParam.type === "raw") { queryParam.type = "tcp"; } else if (dom_prefix == "xray_" && queryParam.type === "tcp") { queryParam.type = "raw"; } if (dom_prefix == "xray_" && queryParam.type === "http") { opt.set(dom_prefix + 'transport', "xhttp"); } else { opt.set(dom_prefix + 'transport', queryParam.type); } if (queryParam.type === "raw" || queryParam.type === "tcp") { opt.set(dom_prefix + 'tcp_guise', queryParam.headerType || "none"); if (queryParam.headerType && queryParam.headerType != "none") { opt.set(dom_prefix + 'tcp_guise_http_host', queryParam.host || ""); opt.set(dom_prefix + 'tcp_guise_http_path', queryParam.path || ""); } } else if (queryParam.type === "ws") { opt.set(dom_prefix + 'ws_host', queryParam.host || ""); opt.set(dom_prefix + 'ws_path', queryParam.path || ""); if (dom_prefix == "singbox_" && queryParam.path && queryParam.path.length > 1) { var ws_path_params = {}; var ws_path_dat = queryParam.path.split('?'); var ws_path = ws_path_dat[0]; var ws_path_params = {}; var ws_path_params_array = (ws_path_dat[1] || '').split('&'); for (i = 0; i < ws_path_params_array.length; i++) { var kv = ws_path_params_array[i].split('='); ws_path_params[decodeURIComponent(kv[0]).toLowerCase()] = decodeURIComponent(kv[1] || ''); } if (ws_path_params.ed) { opt.set(dom_prefix + 'ws_path', ws_path); opt.set(dom_prefix + 'ws_enableEarlyData', true); opt.set(dom_prefix + 'ws_maxEarlyData', ws_path_params.ed); opt.set(dom_prefix + 'ws_earlyDataHeaderName', 'Sec-WebSocket-Protocol'); } } } else if (queryParam.type === "h2" || queryParam.type === "http") { if (dom_prefix == "xray_") { opt.set(dom_prefix + 'xhttp_mode', "stream-one"); opt.set(dom_prefix + 'xhttp_host', queryParam.host || ""); opt.set(dom_prefix + 'xhttp_path', queryParam.path || ""); } else { opt.set(dom_prefix + 'http_host', queryParam.host || ""); opt.set(dom_prefix + 'http_path', queryParam.path || ""); } } else if (queryParam.type === "quic") { opt.set(dom_prefix + 'quic_guise', queryParam.headerType || "none"); opt.set(dom_prefix + 'quic_security', queryParam.quicSecurity); opt.set(dom_prefix + 'quic_key', queryParam.key); } else if (queryParam.type === "kcp" || queryParam.type === "mkcp") { opt.set(dom_prefix + 'mkcp_guise', queryParam.headerType || "none"); opt.set(dom_prefix + 'mkcp_seed', queryParam.seed || ""); } else if (queryParam.type === "grpc") { opt.set(dom_prefix + 'grpc_serviceName', (queryParam.serviceName || queryParam.path) || ""); opt.set(dom_prefix + 'grpc_mode', queryParam.mode || "gun"); } queryParam.security = queryParam.security || "tls"; opt.set(dom_prefix + 'tls', queryParam.security === "tls"); if (queryParam.security === "tls") { var tls_serverName = queryParam.peer; if (queryParam.sni) { tls_serverName = queryParam.sni } tls_serverName = tls_serverName || ""; opt.set(dom_prefix + 'tls_serverName', tls_serverName); opt.set(dom_prefix + 'alpn', queryParam.alpn || 'default'); } opt.set(dom_prefix + 'tls_allowInsecure', true); if ((queryParam.allowinsecure ?? '0') === '0' && (queryParam.insecure ?? '0') === '0') { opt.set(dom_prefix + 'tls_allowInsecure', false); } opt.set(dom_prefix + 'mux', queryParam.mux === '1'); if (m.hash) { opt.set('remarks', decodeURIComponent(m.hash.substr(1))); } } if (ssu[0] === "vmess") { if (vmess_type == "sing-box" && has_singbox) { dom_prefix = "singbox_" opt.set('type', "sing-box"); } else { dom_prefix = "xray_" opt.set('type', "Xray"); } opt.set(dom_prefix + 'protocol', "vmess"); var sstr = b64DecodeUnicode((ssu[1] || "").replace(/#.*/, "").trim()); var ploc = sstr.indexOf("/?"); var url0, param = ""; if (ploc > 0) { url0 = sstr.substr(0, ploc); param = sstr.substr(ploc + 2); } var ssm = JSON.parse(sstr); opt.set('remarks', ssm.ps); opt.set(dom_prefix + 'address', unbracketIP(ssm.add)); opt.set(dom_prefix + 'port', ssm.port); opt.set(dom_prefix + 'uuid', ssm.id); opt.set(dom_prefix + 'tls', ssm.tls === "tls"); if (ssm.tls === "tls") { var tls_serverName = ssm.host; if (ssm.sni) { tls_serverName = ssm.sni } opt.set(dom_prefix + 'tls_serverName', tls_serverName); } ssm.net = ssm.net.toLowerCase(); if (ssm.net === "kcp" || ssm.net === "mkcp") ssm.net = "mkcp" if (dom_prefix == "singbox_" && ssm.net === "raw") { ssm.net = "tcp"; } else if (dom_prefix == "xray_" && ssm.net === "tcp") { ssm.net = "raw"; } if (ssm.net === "h2" || ssm.net === "http") { ssm.net = "http"; } if (dom_prefix == "xray_" && ssm.net === "http") { opt.set(dom_prefix + 'transport', "xhttp"); } else { opt.set(dom_prefix + 'transport', ssm.net); } if (ssm.net === "raw" || ssm.net === "tcp") { opt.set(dom_prefix + 'tcp_guise', (ssm.host && ssm.host != "") ? "http" : "none"); if (ssm.host && ssm.host != "") { opt.set(dom_prefix + 'tcp_guise_http_host', ssm.host); opt.set(dom_prefix + 'tcp_guise_http_path', ssm.path || ""); } } else if (ssm.net === "ws") { opt.set(dom_prefix + 'ws_host', ssm.host); opt.set(dom_prefix + 'ws_path', ssm.path); if (dom_prefix == "singbox_" && ssm.path && ssm.path.length > 1) { var ws_path_params = {}; var ws_path_dat = ssm.path.split('?'); var ws_path = ws_path_dat[0]; var ws_path_params = {}; var ws_path_params_array = (ws_path_dat[1] || '').split('&'); for (i = 0; i < ws_path_params_array.length; i++) { var kv = ws_path_params_array[i].split('='); ws_path_params[decodeURIComponent(kv[0]).toLowerCase()] = decodeURIComponent(kv[1] || ''); } if (ws_path_params.ed) { opt.set(dom_prefix + 'ws_path', ws_path); opt.set(dom_prefix + 'ws_enableEarlyData', true); opt.set(dom_prefix + 'ws_maxEarlyData', ws_path_params.ed); opt.set(dom_prefix + 'ws_earlyDataHeaderName', 'Sec-WebSocket-Protocol'); } } } else if (ssm.net === "http") { if (dom_prefix == "xray_") { opt.set(dom_prefix + 'xhttp_mode', "stream-one"); opt.set(dom_prefix + 'xhttp_host', ssm.host || ""); opt.set(dom_prefix + 'xhttp_path', ssm.path || ""); } else { opt.set(dom_prefix + 'http_host', ssm.host || ""); opt.set(dom_prefix + 'http_path', ssm.path || ""); } } else if (ssm.net === "quic") { opt.set(dom_prefix + 'quic_security', ssm.securty); opt.set(dom_prefix + 'quic_key', ssm.key); } else if (ssm.net === "kcp" || ssm.net === "mkcp") { opt.set(dom_prefix + 'mkcp_guise', ssm.type || "none"); opt.set(dom_prefix + 'mkcp_seed', ssm.seed || ""); } else if (ssm.net === "grpc") { opt.set(dom_prefix + 'grpc_serviceName', ssm.path); } } if (ssu[0] === "vless") { if (vless_type == "sing-box" && has_singbox) { dom_prefix = "singbox_" opt.set('type', "sing-box"); } else { dom_prefix = "xray_" opt.set('type', "Xray"); } var m = parseNodeUrl(ssrurl); var password = m.passwd; if (password === "") { s.innerHTML = "<font color='red'><%:Invalid Share URL Format%></font>"; return false; } var queryParam = {}; if (m.search.length > 1) { var query = m.search.replace('/?', '?').split('?') var queryParams = query[1]; var queryArray = queryParams.split('&'); var params; for (i = 0; i < queryArray.length; i++) { params = queryArray[i].split('='); queryParam[decodeURIComponent(params[0])] = decodeURIComponent(params[1] || ''); } } queryParam.type = queryParam.type.toLowerCase(); if (["xhttp", "kcp", "mkcp"].includes(queryParam.type) && vless_type !== "xray" && has_xray) { dom_prefix = "xray_" opt.set('type', "Xray"); } opt.set(dom_prefix + 'protocol', "vless"); opt.set(dom_prefix + 'uuid', password); opt.set(dom_prefix + 'address', unbracketIP(m.hostname)); opt.set(dom_prefix + 'port', m.port || "443"); opt.set(dom_prefix + 'encryption', queryParam.encryption || "none"); if (queryParam.security) { if (queryParam.security == "tls") { opt.set(dom_prefix + 'tls', true); opt.set(dom_prefix + 'reality', false); opt.set(dom_prefix + 'flow', (queryParam.flow || '').replace('-udp443', '')); opt.set(dom_prefix + 'alpn', queryParam.alpn || 'default'); opt.set(dom_prefix + 'tls_serverName', queryParam.sni || ''); opt.set(dom_prefix + 'tls_allowInsecure', true); if ((queryParam.allowinsecure ?? '0') === '0' && (queryParam.insecure ?? '0') === '0') { opt.set(dom_prefix + 'tls_allowInsecure', false); } if (queryParam.fp && queryParam.fp.trim() != "") { opt.set(dom_prefix + 'utls', true); opt.set(dom_prefix + 'fingerprint', queryParam.fp); } opt.set(dom_prefix + 'ech', !!queryParam.ech); opt.set(dom_prefix + 'ech_config', queryParam.ech || ''); } if (queryParam.security == "reality") { opt.set(dom_prefix + 'tls', true); opt.set(dom_prefix + 'reality', true); opt.set(dom_prefix + 'flow', (queryParam.flow || '').replace('-udp443', '')); opt.set(dom_prefix + 'alpn', queryParam.alpn || 'default'); opt.set(dom_prefix + 'tls_serverName', queryParam.sni || ''); if (queryParam.fp && queryParam.fp.trim() != "") { opt.set(dom_prefix + 'utls', true); opt.set(dom_prefix + 'fingerprint', queryParam.fp); } opt.set(dom_prefix + 'reality_publicKey', queryParam.pbk || ''); opt.set(dom_prefix + 'reality_shortId', queryParam.sid || ''); opt.set(dom_prefix + 'reality_spiderX', queryParam.spx || ''); opt.set(dom_prefix + 'use_mldsa65Verify', !!queryParam.pqv); opt.set(dom_prefix + 'reality_mldsa65Verify', queryParam.pqv || ''); } } if (queryParam.type === "kcp" || queryParam.type === "mkcp") { queryParam.type = "mkcp"; } if (queryParam.type === "h2" || queryParam.type === "http") { queryParam.type = "http"; } if (dom_prefix == "singbox_" && queryParam.type === "raw") { queryParam.type = "tcp"; } else if (dom_prefix == "xray_" && queryParam.type === "tcp") { queryParam.type = "raw"; } if (dom_prefix == "xray_" && queryParam.type === "http") { opt.set(dom_prefix + 'transport', "xhttp"); } else { opt.set(dom_prefix + 'transport', queryParam.type); } if (queryParam.type === "raw" || queryParam.type === "tcp") { opt.set(dom_prefix + 'tcp_guise', queryParam.headerType || "none"); if (queryParam.headerType && queryParam.headerType != "none") { opt.set(dom_prefix + 'tcp_guise_http_host', queryParam.host || ""); opt.set(dom_prefix + 'tcp_guise_http_path', queryParam.path || ""); } } else if (queryParam.type === "ws") { opt.set(dom_prefix + 'ws_host', queryParam.host || ""); opt.set(dom_prefix + 'ws_path', queryParam.path || ""); if (dom_prefix == "singbox_" && queryParam.path && queryParam.path.length > 1) { var ws_path_params = {}; var ws_path_dat = queryParam.path.split('?'); var ws_path = ws_path_dat[0]; var ws_path_params = {}; var ws_path_params_array = (ws_path_dat[1] || '').split('&'); for (i = 0; i < ws_path_params_array.length; i++) { var kv = ws_path_params_array[i].split('='); ws_path_params[decodeURIComponent(kv[0]).toLowerCase()] = decodeURIComponent(kv[1] || ''); } if (ws_path_params.ed) { opt.set(dom_prefix + 'ws_path', ws_path); opt.set(dom_prefix + 'ws_enableEarlyData', true); opt.set(dom_prefix + 'ws_maxEarlyData', ws_path_params.ed); opt.set(dom_prefix + 'ws_earlyDataHeaderName', 'Sec-WebSocket-Protocol'); } } } else if (queryParam.type === "h2" || queryParam.type === "http") { if (dom_prefix == "xray_") { opt.set(dom_prefix + 'xhttp_mode', "stream-one"); opt.set(dom_prefix + 'xhttp_host', queryParam.host || ""); opt.set(dom_prefix + 'xhttp_path', queryParam.path || ""); } else { opt.set(dom_prefix + 'http_host', queryParam.host || ""); opt.set(dom_prefix + 'http_path', queryParam.path || ""); } } else if (queryParam.type === "quic") { opt.set(dom_prefix + 'quic_guise', queryParam.headerType || "none"); opt.set(dom_prefix + 'quic_security', queryParam.quicSecurity); opt.set(dom_prefix + 'quic_key', queryParam.key); } else if (queryParam.type === "kcp" || queryParam.type === "mkcp") { opt.set(dom_prefix + 'mkcp_guise', queryParam.headerType || "none"); opt.set(dom_prefix + 'mkcp_seed', queryParam.seed || ""); } else if (queryParam.type === "grpc") { opt.set(dom_prefix + 'grpc_serviceName', (queryParam.serviceName || queryParam.path) || ""); opt.set(dom_prefix + 'grpc_mode', queryParam.mode || "gun"); } else if (queryParam.type === "xhttp" || queryParam.type === "splithttp") { opt.set(dom_prefix + 'xhttp_host', queryParam.host || ""); opt.set(dom_prefix + 'xhttp_path', queryParam.path || ""); opt.set(dom_prefix + 'xhttp_mode', queryParam.mode || "auto"); opt.set(dom_prefix + 'use_xhttp_extra', !!queryParam.extra); opt.set(dom_prefix + 'xhttp_extra', queryParam.extra || ""); } else if (queryParam.type === "httpupgrade") { opt.set(dom_prefix + 'httpupgrade_host', queryParam.host || ""); opt.set(dom_prefix + 'httpupgrade_path', queryParam.path || ""); } if (m.hash) { opt.set('remarks', decodeURIComponent(m.hash.substr(1))); } } if (ssu[0] === "hysteria2" || ssu[0] === "hy2") { var m = parseNodeUrl(ssrurl); var password = m.passwd; if (password === "") { s.innerHTML = "<font color='red'><%:Invalid Share URL Format%></font>"; return false; } var queryParam = {}; if (m.search.length > 1) { var query = m.search.replace('/?', '?').split('?') var queryParams = query[1]; var queryArray = queryParams.split('&'); var params; for (i = 0; i < queryArray.length; i++) { params = queryArray[i].split('='); queryParam[decodeURIComponent(params[0])] = decodeURIComponent(params[1] || ''); } } if (hysteria2_type == "sing-box" && has_singbox) { opt.set('type', "sing-box"); dom_prefix = "singbox_" opt.set(dom_prefix + 'protocol', "hysteria2"); opt.set(dom_prefix + 'hysteria2_auth_password', decodeURIComponent(password)); if (queryParam["obfs-password"] || queryParam["obfs_password"]) { opt.set(dom_prefix + 'hysteria2_obfs_type', "salamander"); opt.set(dom_prefix + 'hysteria2_obfs_password', queryParam["obfs-password"] || queryParam["obfs_password"]); } opt.set(dom_prefix + 'hysteria2_hop', queryParam.mport || ""); } else if (has_hysteria2) { opt.set('type', "Hysteria2"); dom_prefix = "hysteria2_" opt.set(dom_prefix + 'auth_password', decodeURIComponent(password)); if (queryParam["obfs-password"] || queryParam["obfs_password"]) { opt.set(dom_prefix + 'obfs', queryParam["obfs-password"] || queryParam["obfs_password"]); } if (queryParam.pinSHA256) { opt.set(dom_prefix + 'tls_pinSHA256', queryParam.pinSHA256); } opt.set(dom_prefix + 'hop', queryParam.mport || ""); } opt.set(dom_prefix + 'address', unbracketIP(m.hostname)); opt.set(dom_prefix + 'port', m.port || "443"); opt.set(dom_prefix + 'tls_serverName', queryParam.sni || ""); if (queryParam.insecure && queryParam.insecure == "1") { opt.set(dom_prefix + 'tls_allowInsecure', true); } if (m.hash) { opt.set('remarks', decodeURIComponent(m.hash.substr(1))); } } if (ssu[0] === "tuic") { if (has_singbox) { dom_prefix = "singbox_" opt.set('type', "sing-box"); } opt.set(dom_prefix + 'protocol', "tuic"); var _parsedUrl = new URL("http://" + ssu[1]); var username = _parsedUrl.username; var password = _parsedUrl.password; var hostname = _parsedUrl.hostname; var port = _parsedUrl.port; var search = _parsedUrl.search; var hash = _parsedUrl.hash; opt.set(dom_prefix + 'uuid', decodeURIComponent(username)); opt.set(dom_prefix + 'password', decodeURIComponent(password)); opt.set(dom_prefix + 'address', unbracketIP(hostname)); opt.set(dom_prefix + 'port', port || "443"); var queryParam = {}; if (search.length > 1) { var query = search.split('?') var queryParams = query[1]; var queryArray = queryParams.split('&'); var params; for (i = 0; i < queryArray.length; i++) { params = queryArray[i].split('='); queryParam[decodeURIComponent(params[0])] = decodeURIComponent(params[1] || ''); } } opt.set(dom_prefix + 'tuic_congestion_control', queryParam.congestion_control || 'cubic'); opt.set(dom_prefix + 'tuic_udp_relay_mode', queryParam.udp_relay_mode || 'native'); opt.set(dom_prefix + 'tuic_alpn', queryParam.alpn || 'default'); opt.set(dom_prefix + 'tls_serverName', queryParam.sni || ''); opt.set(dom_prefix + 'tls_allowInsecure', true); if ((queryParam.allowinsecure ?? '0') === '0' && (queryParam.insecure ?? '0') === '0') { opt.set(dom_prefix + 'tls_allowInsecure', false); } if (hash) { opt.set('remarks', decodeURIComponent(hash.substr(1))); } } if (ssu[0] === "anytls") { if (has_singbox) { dom_prefix = "singbox_" opt.set('type', "sing-box"); } opt.set(dom_prefix + 'protocol', "anytls"); var m = parseNodeUrl(ssrurl); var password = m.passwd; if (password === "") { s.innerHTML = "<font color='red'><%:Invalid Share URL Format%></font>"; return false; } opt.set(dom_prefix + 'password', password); opt.set(dom_prefix + 'address', unbracketIP(m.hostname)); opt.set(dom_prefix + 'port', m.port || "443"); var queryParam = {}; if (m.search.length > 1) { var query = m.search.replace('/?', '?').split('?') var queryParams = query[1]; var queryArray = queryParams.split('&'); var params; for (i = 0; i < queryArray.length; i++) { params = queryArray[i].split('='); queryParam[decodeURIComponent(params[0])] = decodeURIComponent(params[1] || ''); } } if ((!queryParam.security || queryParam.security == "") && queryParam.sni && queryParam.sni != "") { queryParam.security = "tls"; } if (queryParam.security) { if (queryParam.security == "tls") { opt.set(dom_prefix + 'tls', true); opt.set(dom_prefix + 'reality', false); opt.set(dom_prefix + 'alpn', queryParam.alpn || 'default'); opt.set(dom_prefix + 'tls_serverName', queryParam.sni || ''); opt.set(dom_prefix + 'tls_allowInsecure', true); if ((queryParam.allowinsecure ?? '0') === '0' && (queryParam.insecure ?? '0') === '0') { opt.set(dom_prefix + 'tls_allowInsecure', false); } if (queryParam.fp && queryParam.fp.trim() != "") { opt.set(dom_prefix + 'utls', true); opt.set(dom_prefix + 'fingerprint', queryParam.fp); } } if (queryParam.security == "reality") { opt.set(dom_prefix + 'tls', true); opt.set(dom_prefix + 'reality', true); opt.set(dom_prefix + 'alpn', queryParam.alpn || 'default'); opt.set(dom_prefix + 'tls_serverName', queryParam.sni || ''); if (queryParam.fp && queryParam.fp.trim() != "") { opt.set(dom_prefix + 'utls', true); opt.set(dom_prefix + 'fingerprint', queryParam.fp); } opt.set(dom_prefix + 'reality_publicKey', queryParam.pbk || ''); opt.set(dom_prefix + 'reality_shortId', queryParam.sid || ''); } } if (m.hash) { opt.set('remarks', decodeURIComponent(m.hash.substr(1))); } } if (dom_prefix && dom_prefix != null) { if (opt.get(dom_prefix + 'port').value) { opt.get(dom_prefix + 'port').focus(); opt.get(dom_prefix + 'port').blur(); } } else { s.innerHTML = "<font color='red'><%:Invalid Share URL Format%></font>: " + ssu[0]; return false; } s.innerHTML = "<font color='green'><%:Import Finished %></font>"; return false; } function exportConfigFile(btn, sid) { window.open('<%=api.url("gen_client_config")%>?id=' + sid, "_blank") } //]]></script> <input type="button" class="btn cbi-button cbi-button-apply" value='<%:From Share URL%>' onclick="return fromUrl(this, '<%=self.option%>', '<%=self.value%>')" /> <input type="button" class="btn cbi-button cbi-button-apply" value='<%:Build Share URL%>' onclick="return exportUrl(this, '<%=self.option%>', '<%=self.value%>')" /> <input type="button" class="btn cbi-button cbi-button-apply" value='<%:Generate QRCode%>' onclick="return genQrcode(this, '<%=self.option%>', '<%=self.value%>')" /> <input type="button" class="btn cbi-button cbi-button-apply" value='<%:Export Config File%>' onclick="return exportConfigFile(this, '<%=self.value%>')" /> <div id="qrcode_div" style="margin-top: 1rem;display:none"> <div id="qrcode"></div> </div> <span id="<%=self.option%>-status"></span> <%+cbi/valuefooter%>
2977094657/BiliHistoryFrontend
7,583
src/components/tailwind/analytics/pages/CategoryPopularDistributionPage.vue
<!-- 热门视频分区分布分析页组件 --> <template> <div class="space-y-4"> <h3 class="text-xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 热门视频分区分布分析 </h3> <!-- 加载状态 --> <div v-if="loading" class="flex justify-center items-center py-12"> <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-[#fb7299]"></div> </div> <!-- 错误状态 --> <div v-else-if="error" class="text-center py-12"> <div class="text-red-500 text-lg">{{ error }}</div> </div> <!-- 主要内容 --> <div v-else-if="distributionData" class="space-y-4"> <!-- 洞察文本 --> <div class="text-center text-gray-600 dark:text-gray-300"> <div class="text-sm leading-relaxed" v-html="formatInsightText(distributionData.insights.join(','))"></div> </div> <!-- 可视化图表 --> <div class="grid grid-cols-1 lg:grid-cols-3 gap-2 -mx-4"> <!-- 分区分布统计卡片 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-3 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-base font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-2 text-center"> 分区分布统计 </h4> <div ref="chartRef" class="h-[320px] px-4"></div> </div> <!-- 热门分区列表 --> <div v-if="distributionData.popular_categories && distributionData.popular_categories.length > 0" class="lg:col-span-2 bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-3 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-base font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-2"> 热门分区排行 (前10个) </h4> <div class="grid grid-cols-1 md:grid-cols-3 gap-2 h-[450px] overflow-y-auto"> <div v-for="(category, index) in distributionData.popular_categories" :key="index" class="flex items-center p-2 bg-gray-50/50 dark:bg-gray-800/50 rounded-lg hover:bg-gray-100/50 dark:hover:bg-gray-700/50 transition-colors"> <div class="flex-1 min-w-0"> <div class="font-medium text-gray-900 dark:text-gray-100 truncate text-sm flex items-center justify-between"> <span>{{ category.category_name }}</span> <span class="text-xs text-gray-500 dark:text-gray-400 ml-2"> <span class="text-[#fb7299] font-semibold">{{ category.total_popular }}</span> 个热门视频 </span> </div> <!-- 显示该分区的热门视频 --> <div v-if="category.videos && category.videos.length > 0" class="mt-2 space-y-1"> <div v-for="(video, vIndex) in category.videos.slice(0, 2)" :key="vIndex" @click="openVideo(video.bvid)" class="text-xs text-gray-600 dark:text-gray-400 hover:text-[#fb7299] cursor-pointer truncate"> • {{ video.title }} </div> <div v-if="category.videos.length > 2" class="text-xs text-gray-400"> 还有 {{ category.videos.length - 2 }} 个视频... </div> </div> </div> </div> </div> </div> </div> </div> </div> </template> <script setup> import { ref, onMounted, watch } from 'vue' import * as echarts from 'echarts' import { getCategoryPopularDistribution } from '../../../../api/api.js' const props = defineProps({ selectedYear: { type: Number, default: () => new Date().getFullYear() }, distributionData: { type: Object, default: null } }) const loading = ref(true) const error = ref(null) const distributionData = ref(null) const chartRef = ref(null) let chart = null // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299] font-semibold">$1</span>') } // 打开视频 const openVideo = (bvid) => { if (bvid) { window.open(`https://www.bilibili.com/video/${bvid}`, '_blank') } } // 获取分区分布数据 const fetchDistributionData = async (year) => { if (!year) return // 如果父组件已经传递了数据,直接使用 if (props.distributionData) { distributionData.value = props.distributionData.distribution_analysis loading.value = false await initCharts() return } loading.value = true error.value = null try { const response = await getCategoryPopularDistribution(year) if (response.data.status === 'success') { distributionData.value = response.data.data.distribution_analysis await initCharts() } else { error.value = response.data.message || '获取数据失败' } } catch (err) { console.error('获取热门视频分区分布数据出错:', err) error.value = '获取数据时发生错误' } finally { loading.value = false } } // 初始化图表 const initCharts = async () => { await new Promise(resolve => setTimeout(resolve, 100)) // 等待DOM更新 initChart() } // 初始化图表 const initChart = () => { if (!chartRef.value || !distributionData.value) return if (chart) { chart.dispose() } chart = echarts.init(chartRef.value) const categories = distributionData.value.popular_categories || [] // 准备饼图数据 const data = categories.map(category => ({ name: category.category_name, value: category.total_popular })) // 生成颜色数组 const colors = [ '#fb7299', '#fc9b7a', '#ff6b9d', '#f093fb', '#f5576c', '#4facfe', '#00f2fe', '#43e97b', '#38f9d7', '#ffecd2' ] const option = { tooltip: { trigger: 'item', formatter: function(params) { const percentage = params.percent return `${params.name}: ${params.value} 个热门视频 (${percentage}%)` } }, legend: { bottom: '1%', left: 'center', textStyle: { color: '#666', fontSize: 9 }, type: 'scroll', pageIconColor: '#fb7299', pageIconInactiveColor: '#ccc', pageTextStyle: { color: '#666' }, itemWidth: 12, itemHeight: 8 }, series: [ { name: '分区分布', type: 'pie', radius: '45%', center: ['50%', '48%'], label: { show: true, position: 'outside', formatter: function(params) { if (params.percent < 3) return '' // 小于3%不显示标签,避免过于拥挤 return `${params.name}\n${params.value}个` }, fontSize: 11, color: '#333', fontWeight: '500', lineHeight: 14 }, emphasis: { label: { show: true, fontSize: '13', fontWeight: 'bold' }, itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }, labelLine: { show: true, length: 20, length2: 15, smooth: true }, data: data.map((item, index) => ({ ...item, itemStyle: { color: colors[index % colors.length] } })) } ] } chart.setOption(option) } // 监听年份变化 watch(() => props.selectedYear, (newYear) => { fetchDistributionData(newYear) }, { immediate: true }) // 监听父组件传递的数据变化 watch(() => props.distributionData, (newData) => { if (newData) { distributionData.value = newData.distribution_analysis loading.value = false initCharts() } }, { immediate: true }) // 组件挂载时获取数据 onMounted(() => { fetchDistributionData(props.selectedYear) }) </script>
294coder/Efficient-MIF
2,167
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/MTF.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % MTF filters the image I_MS using a Gaussin filter matched with the Modulation Transfer Function (MTF) of the MultiSpectral (MS) sensor. % % Interface: % I_Filtered = MTF(I_MS,sensor,ratio) % % Inputs: % I_MS: MS image; % sensor: String for type of sensor (e.g. 'WV2', 'IKONOS'); % ratio: Scale ratio between MS and PAN. % % Outputs: % I_Filtered: Output filtered MS image. % % References: % [Aiazzi02] B. Aiazzi, L. Alparone, S. Baronti, and A. Garzelli, Context-driven fusion of high spatial and spectral resolution images based on % oversampled multiresolution analysis, IEEE Transactions on Geoscience and Remote Sensing, vol. 40, no. 10, pp. 23002312, October % 2002. % [Aiazzi06] B. Aiazzi, L. Alparone, S. Baronti, A. Garzelli, and M. Selva, MTF-tailored multiscale fusion of high-resolution MS and Pan imagery, % Photogrammetric Engineering and Remote Sensing, vol. 72, no. 5, pp. 591596, May 2006. % [Vivone14a] G. Vivone, R. Restaino, M. Dalla Mura, G. Licciardi, and J. Chanussot, Contrast and error-based fusion schemes for multispectral % image pansharpening, IEEE Geoscience and Remote Sensing Letters, vol. 11, no. 5, pp. 930934, May 2014. % [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms, % IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_Filtered = MTF(I_MS,sensor,ratio) h = genMTF(ratio, sensor, size(I_MS,3)); I_MS_LP = zeros(size(I_MS)); for ii = 1 : size(I_MS,3) I_MS_LP(:,:,ii) = imfilter(I_MS(:,:,ii),real(h(:,:,ii)),'replicate'); end I_Filtered = double(I_MS_LP); end
294coder/Efficient-MIF
1,977
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/showImage8LR_zoomin.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Visualize and print an eight-band multispectral image. % % Interface: % showImage8LR(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L,ratio) % % Inputs: % I_MS: Eight band multispectral image; % print: Flag. If print == 1, print EPS image; % id: Identifier (name) of the printed EPS image; % flag_cut_bounds: Cut the boundaries of the viewed Panchromatic image; % dim_cut: Define the dimension of the boundary cut; % th_values: Flag. If th_values == 1, apply an hard threshold to the dynamic range; % L: Radiomatric resolution of the input image; % ratio: Resize factor. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showImage8LR_zoomin(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L,ratio, location1, location2) if flag_cut_bounds I_MS = I_MS(round(dim_cut/ratio):end-round(dim_cut/ratio),round(dim_cut/ratio):end-round(dim_cut/ratio),:); end if th_values I_MS(I_MS > 2^L) = 2^L; I_MS(I_MS < 0) = 0; end if id == 1 IMN = viewimage(I_MS(:,:,[1,3,5])); IMN = IMN(:,:,3:-1:1); else IMN = viewimage(I_MS(:,:,[1,3,5]),[0.01 0.995]); IMN = IMN(:,:,3:-1:1); end if isempty(location2) ent=rectangleonimage(IMN,location1,1, 3, 3, 3, 1); % put close-up to up-right corner figure,imshow(ent,[]) else % type =1 (put to down-left); type =2 (put to down-right); % type =3 (put to up-right); type =4 (put to up-left); ent=rectangleonimage(IMN,location1,1, 3, 3, 3, 1); % put close-up to up-right corner ent=rectangleonimage(ent,location2,1, 3, 2, 3, 2); % put close-up to down-right corner figure,imshow(ent,[]) end if print printImage(IMN,sprintf('Outputs/%d.eps',id)); end end
2977094657/BiliHistoryFrontend
8,685
src/components/tailwind/analytics/pages/OverviewPage.vue
<!-- 数据概览页组件 --> <template> <div class="space-y-12"> <h3 class="text-3xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 年度观看数据 </h3> <div class="text-base text-center text-gray-600 dark:text-gray-300 space-y-3"> <!-- 总体活动总结(放在最前面) --> <div v-if="viewingData?.insights?.overall_activity" v-html="formatInsightText(viewingData.insights.overall_activity)" > </div> <!-- 按指定顺序合并所有总结,用逗号分隔 --> <div> <span v-if="viewingBehaviorData?.report?.total_summary" v-html="formatInsightText(viewingBehaviorData.report.total_summary)"></span> <span v-if="viewingBehaviorData?.report?.total_summary && viewingBehaviorData?.report?.category_summary">, </span> <span v-if="viewingBehaviorData?.report?.category_summary" v-html="formatInsightText(viewingBehaviorData.report.category_summary)"></span> <span v-if="(viewingBehaviorData?.report?.total_summary || viewingBehaviorData?.report?.category_summary) && viewingBehaviorData?.report?.device_summary">, </span> <span v-if="viewingBehaviorData?.report?.device_summary" v-html="formatInsightText(viewingBehaviorData.report.device_summary)"></span> <span v-if="(viewingBehaviorData?.report?.total_summary || viewingBehaviorData?.report?.category_summary || viewingBehaviorData?.report?.device_summary) && viewingBehaviorData?.report?.up_summary">, </span> <span v-if="viewingBehaviorData?.report?.up_summary" v-html="formatInsightText(viewingBehaviorData.report.up_summary)"></span> <span v-if="(viewingBehaviorData?.report?.total_summary || viewingBehaviorData?.report?.category_summary || viewingBehaviorData?.report?.device_summary || viewingBehaviorData?.report?.up_summary) && viewingBehaviorData?.report?.time_slot_summary">, </span> <span v-if="viewingBehaviorData?.report?.time_slot_summary" v-html="formatInsightText(viewingBehaviorData.report.time_slot_summary)"></span> <span v-if="(viewingBehaviorData?.report?.total_summary || viewingBehaviorData?.report?.category_summary || viewingBehaviorData?.report?.device_summary || viewingBehaviorData?.report?.up_summary || viewingBehaviorData?.report?.time_slot_summary) && viewingBehaviorData?.report?.late_night_summary">, </span> <span v-if="viewingBehaviorData?.report?.late_night_summary" v-html="formatInsightText(viewingBehaviorData.report.late_night_summary)"></span> </div> </div> <!-- 年度观看热力图 --> <div class="space-y-8"> <div class="flex justify-center items-center text-sm text-gray-500 dark:text-gray-400 space-x-6"> <div class="flex items-center"> <span class="inline-block w-3 h-3 rounded-sm bg-[#FFECF1] mr-1"></span> <span>1-10</span> </div> <div class="flex items-center"> <span class="inline-block w-3 h-3 rounded-sm bg-[#FFB3CA] mr-1"></span> <span>11-50</span> </div> <div class="flex items-center"> <span class="inline-block w-3 h-3 rounded-sm bg-[#FF8CB0] mr-1"></span> <span>51-100</span> </div> <div class="flex items-center"> <span class="inline-block w-3 h-3 rounded-sm bg-[#FF6699] mr-1"></span> <span>101-200</span> </div> <div class="flex items-center"> <span class="inline-block w-3 h-3 rounded-sm bg-[#E84B85] mr-1"></span> <span>201+</span> </div> </div> <div ref="heatmapChartRef" class="w-full h-[320px]"></div> </div> </div> </template> <script setup> import { ref, onMounted, watch } from 'vue' import * as echarts from 'echarts' import { getYearlyAnalysis, getViewingBehavior } from '@/api/api.js' const props = defineProps({ viewingData: { type: Object, required: true } }) const heatmapChartRef = ref(null) let heatmapChart = null const yearlyData = ref(null) const viewingBehaviorData = ref(null) // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } // 获取日期范围内的所有日期 const getDateRange = (year) => { const start = new Date(Date.UTC(year, 0, 1)) const end = new Date(Date.UTC(year, 11, 31)) const dates = [] let current = start while (current <= end) { const date = current.toISOString().split('T')[0] dates.push(date) current = new Date(Date.UTC(current.getUTCFullYear(), current.getUTCMonth(), current.getUTCDate() + 1)) } return dates } // 获取年度分析数据 const fetchYearlyData = async (year) => { if (!year) return try { const response = await getYearlyAnalysis(year) if (response.data.status === 'success') { yearlyData.value = response.data initHeatmapChart() } else { console.error('获取年度数据失败:', response.data.message) } } catch (error) { console.error('获取年度数据出错:', error) } } // 获取观看行为数据 const fetchViewingBehavior = async (year) => { if (!year) return try { const response = await getViewingBehavior(year, true) if (response.data && response.data.status === 'success') { viewingBehaviorData.value = response.data.data } } catch (error) { console.error('获取观看行为数据失败:', error) } } const initHeatmapChart = () => { if (!heatmapChartRef.value || !yearlyData.value?.data?.daily_count) return const year = props.viewingData?.year if (!year) return const dailyData = yearlyData.value.data.daily_count const allDates = getDateRange(year) // 将数据转换为热力图所需的格式 const data = allDates.map(date => { const count = dailyData[date] || 0 return [date, count] }) // 如果已经存在图表实例,先销毁它 if (heatmapChart) { heatmapChart.dispose() } heatmapChart = echarts.init(heatmapChartRef.value) const option = { animation: true, tooltip: { show: true, trigger: 'item', formatter: function(params) { const date = params.value[0] const count = params.value[1] const secondsMap = (yearlyData.value && yearlyData.value.data && yearlyData.value.data.daily_watch_seconds) || {} const seconds = secondsMap[date] || 0 const h = Math.floor(seconds / 3600) const m = Math.floor((seconds % 3600) / 60) const s = seconds % 60 let timeStr if (h > 0) { timeStr = `${h}小时${String(m).padStart(2, '0')}分${String(s).padStart(2, '0')}秒` } else if (m > 0) { timeStr = `${m}分${String(s).padStart(2, '0')}秒` } else { timeStr = `${s}秒` } return `${date} : ${count}个视频 · 观看时长 ${timeStr}` }, textStyle: { fontSize: 14 } }, visualMap: { show: false, type: 'piecewise', pieces: [ { min: 1, max: 10, color: '#FFECF1' }, { min: 11, max: 50, color: '#FFB3CA' }, { min: 51, max: 100, color: '#FF8CB0' }, { min: 101, max: 200, color: '#FF6699' }, { min: 201, max: 9999, color: '#E84B85' } ] }, calendar: { top: 30, left: 60, right: 60, cellSize: [16, 16], range: [`${year}-01-01`, `${year}-12-31`], itemStyle: { color: 'rgba(255, 255, 255, 0.5)', borderColor: 'rgba(238, 238, 238, 0.8)', borderWidth: 1 }, yearLabel: { show: false }, dayLabel: { firstDay: 0, nameMap: ['日', '一', '二', '三', '四', '五', '六'], color: '#666', fontSize: 12, margin: 12 }, monthLabel: { nameMap: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'], color: '#666', fontSize: 12, align: 'center', margin: 15 }, splitLine: { show: false } }, series: [{ type: 'heatmap', coordinateSystem: 'calendar', data: data, label: { show: false }, emphasis: { itemStyle: { borderColor: '#fb7299', borderWidth: 2 } } }] } heatmapChart.setOption(option) } onMounted(() => { if (props.viewingData?.year) { fetchYearlyData(props.viewingData.year) fetchViewingBehavior(props.viewingData.year) } // 监听窗口大小变化 window.addEventListener('resize', () => { heatmapChart?.resize() }) }) // 监听数据变化 watch(() => yearlyData.value, () => { if (props.viewingData?.year) { initHeatmapChart() } }, { deep: true }) // 监听年份变化 watch(() => props.viewingData?.year, (newYear) => { if (newYear) { fetchYearlyData(newYear) fetchViewingBehavior(newYear) } }, { immediate: true }) </script> <style> .dark .echarts { filter: brightness(0.9); } </style>
2977094657/BiliHistoryFrontend
3,952
src/components/tailwind/analytics/pages/DurationAnalysisPage.vue
<!-- 视频时长分析页组件 --> <template> <div class="space-y-6"> <h3 class="text-4xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 视频时长分析 </h3> <div v-if="viewingData?.insights?.duration_preference" class="text-lg text-center text-gray-600 dark:text-gray-300 mb-8" v-html="formatInsightText(viewingData.insights.duration_preference)" > </div> <!-- 时长分布图表 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-6 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-4">时长分布</h4> <div class="h-[300px]"> <v-chart ref="chartRef" class="h-full w-full" :option="durationDistributionOption" autoresize /> </div> </div> </div> </template> <script setup> import { computed, onMounted, ref } from 'vue' import gsap from 'gsap' import VChart from 'vue-echarts' import * as echarts from 'echarts/core' const props = defineProps({ viewingData: { type: Object, required: true } }) const chartRef = ref(null) const durationDistributionOption = computed(() => { if (!props.viewingData?.duration_correlation) return {} const periods = ['凌晨', '上午', '下午', '晚上'] const types = ['短视频', '中等视频', '长视频'] const data = periods.map(period => { const periodData = props.viewingData.duration_correlation[period] return types.map(type => ({ period, type, value: periodData[type].video_count, avg_duration: Math.round(periodData[type].avg_duration / 60) })) }).flat() const typeColors = { '短视频': { from: 'rgba(251, 114, 153, 0.9)', to: 'rgba(252, 155, 122, 0.9)' }, '中等视频': { from: 'rgba(64, 169, 255, 0.9)', to: 'rgba(128, 208, 255, 0.9)' }, '长视频': { from: 'rgba(82, 196, 26, 0.9)', to: 'rgba(144, 217, 79, 0.9)' } } return { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, backgroundColor: 'rgba(28, 28, 28, 0.9)', borderColor: '#fb7299', textStyle: { color: '#fff' }, formatter: (params) => { const period = params[0].axisValue let result = `${period}<br/>` params.forEach(param => { const data = param.data result += `${param.seriesName}:${data.value}个 (平均${data.avg_duration}分钟)<br/>` }) return result } }, legend: { data: types, top: 0, textStyle: { color: '#666' }, itemStyle: { borderWidth: 0 } }, grid: { top: '15%', left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'category', data: periods, axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' } }, yAxis: { type: 'value', name: '视频数量', axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' }, splitLine: { lineStyle: { color: 'rgba(0, 0, 0, 0.1)' } } }, series: types.map(type => ({ name: type, type: 'bar', stack: 'total', emphasis: { focus: 'series' }, itemStyle: { color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [ { offset: 0, color: typeColors[type].from }, { offset: 1, color: typeColors[type].to } ]) }, data: periods.map(period => { return data.find(d => d.period === period && d.type === type) }) })) } }) onMounted(() => { if (chartRef.value) { gsap.from(chartRef.value.$el, { opacity: 0, y: 20, duration: 0.5, ease: 'power2.out', delay: 0.2 }) } }) // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } </script>
298582245/wqwl_qinglong
14,173
wqwl_冲刺鸭云打印.js
/** * 脚本:wqwl_冲刺鸭云打印.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序冲刺鸭云打印 * 环境变量:wqwl_ccy,多个换行或新建多个变量 * 环境变量描述:抓包https://cloudprint.chongci.shop参数的openid,格式:openid#备注 * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 3 * * * 一天一次 */ /** * 写脚本不易走个头谢谢:https://gitee.com/cobbWmy/img/blob/master/chongciya.jpg */ const axios = require('axios'); const fs = require('fs'); const qs = require('qs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || false; //并发数,默认4 let bfs = process.env["wqwl_bfs"] || 4; // 是否通知 let isNotify = true; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_ccy'; //脚本名称 const name = '微信小程序冲刺鸭云打印' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } let fileData = wqwlkj.readFile('ccy') || {} class Task { constructor(ck) { this.index = index++; this.ck = ck this.baseUrl = 'https://cloudprint.chongci.shop' this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) this.pointsRules = { pointToMoneyRatio: 0.1 // 1积分=0.1元 }; } async init() { const ckData = this.ck.split('#') if (ckData.length < 1) { return this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 1) { this.remark = ckData[0].slice(0, 8); } else { this.remark = ckData[1]; } this.token = ckData[0]; let ua if (!fileData[this.remark]) fileData[this.remark] = {} if (!fileData[this.remark]['ua']) { ua = wqwlkj.generateRandomUA(); fileData[this.remark]['ua'] = ua } else ua = fileData[this.remark]['ua']; this.sendMessage(`🎲使用ua:${ua}`); // this.sendMessage(`🎲使用随机ua:${ua}`); this.headers = { 'Host': 'jiuyixiaoer.fzjingzhou.com', 'Connection': 'keep-alive', 'xweb_xhr': '1', 'platform': 'MP-WEIXIN', 'User-Agent': ua, 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*/*', 'Sec-Fetch-Site': 'cross-site', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty', 'Referer': 'https://servicewechat.com/wx7d1787ad17f2d932/19/page-frame.html', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate' } if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } return true } async getUserInfo() { try { const url = `${this.baseUrl}/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=member&app=1&openid=${this.token}`; const options = { url: url, headers: this.headers, method: 'GET', responseType: 'buffer' }; let res = await this.request(options); res = JSON.parse(res) if (!res?.mobile) { return this.sendMessage(`❌获取用户信息失败,原因:${res?.msg}`) } else { let points = res?.credit1 if (points >= 1) { this.sendMessage(`🎉积分可以提现了,准备提现`) await this.withdrawPoints(points) let tempRes = await this.request(options); tempRes = JSON.parse(tempRes) points = tempRes?.credit1 } else { this.sendMessage(`⚠️积分不足以提现`) } this.sendMessage(`ℹ️用户积分:${points}≈${(parseFloat(points) * 0.1).toFixed(2)}元,累计收益:${res?.credit2}元`, true) } } catch (e) { this.sendMessage(`❌获取用户信请求失败,原因,${e.message}`) } } async withdrawPoints(points) { try { const url = `${this.baseUrl}/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=api.index.jf_exchange&app=1&openid=${this.token}&points=${points}`; const options = { url: url, headers: this.headers, method: 'POST', responseType: 'buffer' }; const res = await this.request(options); // 解析提现结果 let withdrawInfo = "提现结果解析失败"; try { const jsonRes = JSON.parse(resStr); if (jsonRes.status === 1 || jsonRes.success) { withdrawInfo = `提现成功,到账金额: ${(points * this.pointsRules.pointToMoneyRatio).toFixed(2)}元`; this.sendMessage(`✅${withdrawInfo}`, true); } else { withdrawInfo = `提现失败: ${jsonRes.message || '系统提示失败'}`; } } catch (e) { if (resStr.includes('成功')) { withdrawInfo = `提现成功,到账金额: ${(points * this.pointsRules.pointToMoneyRatio).toFixed(2)}元`; this.sendMessage(`✅${withdrawInfo}`); } else { withdrawInfo = `提现失败: 系统返回非预期结果`; this.sendMessage(`❌${withdrawInfo},${e.message}`); } } } catch (e) { const message = `提现过程异常: ${e.message}`; this.sendMessage(`❌${message}`); } } async checkSignStatus() { try { const url = `${this.baseUrl}/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=sign&app=1&openid=${this.token}`; const options = { url: url, headers: this.headers, method: 'GET', responseType: 'buffer' }; const res = await this.request(options); // console.log(options) const resStr = typeof res === 'string' ? res : res.toString('utf8'); // 解析签到状态并输出清晰信息 let statusInfo = "未查询到签到状态"; try { const jsonRes = JSON.parse(resStr); if (jsonRes.sign_data && jsonRes.sign_data.length > 0) { const signDates = jsonRes.sign_data.map(item => item.date).join(', '); statusInfo = `已签到日期: ${signDates}`; // 检查是否包含今天的日期 this.today = wqwlkj.formatDate(new Date()); const hasToday = jsonRes.sign_data.some(item => item.date === this.today); return { hasSigned: hasToday, message: hasToday ? "今天已经签到过了" : "今日尚未签到" }; } else { statusInfo = "暂无签到记录"; } } catch (e) { statusInfo = "签到状态解析失败"; } this.sendMessage(`ℹ️签到状态: ${statusInfo}`); return { hasSigned: false }; } catch (e) { this.sendMessage(`❌检查签到状态失败: ${e.message}`); return { hasSigned: false }; } } async signIn() { const signStatus = await this.checkSignStatus(); if (signStatus.hasSigned) { const message = `今日已完成签到`; return this.sendMessage(`✅${message}`); } try { const url = `${this.baseUrl}/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=sign.dosign&app=1&openid=${this.token}`; const options = { url: url, headers: this.headers, method: 'GET', responseType: 'buffer' }; // console.log(options) let res = await this.request(options); res = JSON.parse(res) if (res?.status === 1) { this.sendMessage(`✅签到成功`) } else if (res?.status === 2) { this.sendMessage(`❌签到失败,今日已经签到过啦`) } else { this.sendMessage(`❌签到失败,未知的错误`) } } catch (e) { this.sendMessage(`❌签到请求失败,原因,${e.message}`) } } async main() { const isFinish = await this.init() if (!isFinish) return await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) const bool = await this.signIn() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.getUserInfo() } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); return data; } catch (error) { this.sendMessage(`🔐检测到请求发生错误,正在重试...`) // 刷新代理 let newProxy; if (isProxy) { newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); } else { this.sendMessage(`⚠️未使用代理`); newProxy = true } if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } wqwlkj.saveFile(fileData, 'ccy') console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
281677160/openwrt-package
2,786
luci-app-passwall2/luasrc/view/passwall2/node_subscribe/js.htm
<% local api = require "luci.passwall2.api" -%> <script type="text/javascript"> //<![CDATA[ var appname = "<%= api.appname %>" function confirmDeleteNode(remark) { if (!confirm("<%:Delete the subscribed node%>: " + remark + " ?")) return false; fetch('<%= api.url("subscribe_del_node") %>?remark=' + encodeURIComponent(remark), { method: "GET" }).then(res => { if (res.ok) { location.reload(); } else { alert("<%:Failed to delete.%>"); } }); return false; } function confirmDeleteAll() { if (!confirm("<%:Are you sure you want to delete all subscribed nodes?%>")) return false; fetch('<%= api.url("subscribe_del_all") %>', { method: "GET" }).then(res => { if (res.ok) { location.reload(); } else { alert("<%:Failed to delete.%>"); } }); return false; } function ManualSubscribe(sectionId) { var urlInput = document.querySelector("input[name='cbid." + appname + "." + sectionId + ".url']"); var currentUrl = urlInput ? urlInput.value.trim() : ""; if (!currentUrl) { alert("<%:Subscribe URL cannot be empty.%>"); return; } fetch('<%= api.url("subscribe_manual") %>?section=' + encodeURIComponent(sectionId) + '&url=' + encodeURIComponent(currentUrl)) .then(response => response.json()) .then(data => { if (!data.success) { alert(data.msg || "Operation failed"); } else { window.location.href = '<%= api.url("log") %>' } }); } function ManualSubscribeAll() { var sectionIds = []; var urls = []; var table = document.getElementById("cbi-" + appname + "-subscribe_list"); var editBtns = table ? table.getElementsByClassName("cbi-button cbi-button-edit") : []; for (var i = 0; i < editBtns.length; i++) { var btn = editBtns[i]; var onclickStr = btn.getAttribute("onclick"); if (!onclickStr) continue; var id = onclickStr.substring(onclickStr.lastIndexOf('/') + 1, onclickStr.length - 1); if (!id) continue; var urlInput = document.querySelector("input[name='cbid." + appname + "." + id + ".url']"); var currentUrl = urlInput ? urlInput.value.trim() : ""; if (!currentUrl) { alert("<%:Subscribe URL cannot be empty.%>"); return; } sectionIds.push(id); urls.push(currentUrl); } if (sectionIds.length === 0) { //alert("No subscriptions found."); return; } var params = new URLSearchParams(); params.append("sections", sectionIds.join(",")); params.append("urls", urls.join(",")); fetch('<%= api.url("subscribe_manual_all") %>', { method: 'POST', body: params }) .then(response => response.json()) .then(data => { if (!data.success) { alert(data.msg || "Operation failed"); } else { window.location.href = '<%= api.url("log") %>' } }); } //]]> </script>
2977094657/BiliHistoryFrontend
5,954
src/components/tailwind/analytics/pages/TitleInteractionAnalysisPage.vue
<template> <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8"> <div class="max-w-7xl mx-auto"> <!-- 标题和总结部分 --> <div class="text-center mb-8"> <h2 class="text-3xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 标题互动分析 </h2> <div class="mt-4 text-gray-600 max-w-3xl mx-auto" v-if="titleAnalytics && titleAnalytics.interaction_analysis"> <p class="mb-2" v-if="titleAnalytics.interaction_analysis.insights && titleAnalytics.interaction_analysis.insights[0]" v-html="formatInsightText(titleAnalytics.interaction_analysis.insights[0])"></p> <p v-if="titleAnalytics.interaction_analysis.insights && titleAnalytics.interaction_analysis.insights[1]" v-html="formatInsightText(titleAnalytics.interaction_analysis.insights[1])"></p> </div> </div> <!-- 互动数据分析 --> <div class="grid grid-cols-1 lg:grid-cols-2 gap-6"> <!-- 左侧:关键词互动率排名 --> <div class="bg-white/5 backdrop-blur-sm rounded-xl p-6"> <h3 class="text-xl font-semibold text-gray-600 mb-4">关键词互动率排名</h3> <div ref="keywordInteractionChartRef" class="w-full h-[360px]"></div> </div> <!-- 右侧:互动类型分布 --> <div class="bg-white/5 backdrop-blur-sm rounded-xl p-6"> <h3 class="text-xl font-semibold text-gray-600 mb-4">互动类型分布</h3> <div ref="interactionTypeChartRef" class="w-full h-[360px]"></div> </div> </div> </div> </div> </template> <script setup> import { ref, onMounted, watch } from 'vue' import * as echarts from 'echarts' const props = defineProps({ titleAnalytics: { type: Object, required: true } }) const keywordInteractionChartRef = ref(null) const interactionTypeChartRef = ref(null) let keywordInteractionChart = null let interactionTypeChart = null // 初始化关键词互动率图表 const initKeywordInteractionChart = () => { if (!keywordInteractionChartRef.value || !props.titleAnalytics?.interaction_analysis?.interaction_stats) return keywordInteractionChart = echarts.init(keywordInteractionChartRef.value) const stats = props.titleAnalytics.interaction_analysis.interaction_stats const data = Object.entries(stats) .filter(([key]) => key !== '其他') // 过滤掉"其他"类别 .map(([type, data]) => ({ name: type, value: data.avg_completion_rate, keywords: data.keywords || [] })) .sort((a, b) => b.value - a.value) const option = { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: (params) => { const [param] = params const keywords = data.find(item => item.name === param.name)?.keywords || [] return `${param.name}<br/> 互动率: ${(param.value * 100).toFixed(1)}%<br/> 关键词: ${keywords.join('、') || '暂无关键词'}` }, confine: true }, grid: { left: '15%', right: '8%', bottom: '8%', top: '8%', containLabel: true }, xAxis: { type: 'value', axisLabel: { formatter: (value) => `${(value * 100).toFixed(1)}%`, color: '#4B5563' }, splitLine: { lineStyle: { color: '#E5E7EB' } } }, yAxis: { type: 'category', data: data.map(item => item.name), axisLabel: { color: '#4B5563', width: 80, overflow: 'truncate' } }, series: [ { name: '互动率', type: 'bar', data: data.map(item => item.value), itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [ { offset: 0, color: '#fb7299' }, { offset: 1, color: '#fc9b7a' } ]) } } ] } keywordInteractionChart.setOption(option) } // 初始化互动类型分布图表 const initInteractionTypeChart = () => { if (!interactionTypeChartRef.value || !props.titleAnalytics?.interaction_analysis?.interaction_stats) return interactionTypeChart = echarts.init(interactionTypeChartRef.value) const stats = props.titleAnalytics.interaction_analysis.interaction_stats const data = Object.entries(stats) .map(([type, data]) => ({ name: type, value: data.count, rate: data.avg_completion_rate })) .sort((a, b) => b.value - a.value) const option = { tooltip: { trigger: 'item', formatter: (params) => { return `${params.name}<br/> 数量: ${params.value}个视频<br/> 平均完成率: ${(data.find(item => item.name === params.name)?.rate * 100).toFixed(1)}%` }, confine: true }, legend: { orient: 'vertical', right: '5%', top: 'center', textStyle: { color: '#4B5563' } }, grid: { left: '10%', containLabel: true }, series: [ { type: 'pie', radius: ['30%', '60%'], center: ['45%', '50%'], avoidLabelOverlap: false, itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 }, label: { show: false }, emphasis: { label: { show: true, formatter: '{b}\n{d}%', fontSize: '14', fontWeight: 'bold' } }, data: data } ] } interactionTypeChart.setOption(option) } // 监听窗口大小变化 const handleResize = () => { keywordInteractionChart?.resize() interactionTypeChart?.resize() } onMounted(() => { initKeywordInteractionChart() initInteractionTypeChart() window.addEventListener('resize', handleResize) }) // 监听数据变化 watch( () => props.titleAnalytics, () => { initKeywordInteractionChart() initInteractionTypeChart() }, { deep: true } ) // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } </script>
2977094657/BiliHistoryFrontend
9,817
src/components/tailwind/analytics/pages/TimeAnalysisPage.vue
<!-- 时间分析页组件 --> <template> <div class="space-y-4 h-screen overflow-hidden"> <h3 class="text-2xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 观看时间分析 </h3> <!-- 时间洞察卡片 - 压缩高度 --> <div class="text-center text-sm max-w-4xl mx-auto"> <div v-if="viewingData?.insights?.daily_record" class="text-gray-600 dark:text-gray-300" v-html="formatInsightText(viewingData.insights.daily_record)"> </div> </div> <!-- 时间统计卡片矩阵 - 压缩高度 --> <div class="grid grid-cols-4 gap-3"> <div class="bg-gradient-to-br from-[#fb7299]/10 to-[#fc9b7a]/10 backdrop-blur-sm rounded-lg p-3 border border-gray-300/30 dark:border-gray-500/30"> <div class="flex items-center justify-between"> <div> <p class="text-xs text-gray-600 dark:text-gray-400">单日最长</p> <p class="text-lg font-bold text-[#fb7299]">{{ formatDurationShort(viewingData?.time_investment?.max_duration_day?.total_duration || 0) }} <span class="text-xs text-gray-500 font-normal">{{ formatDate(viewingData?.time_investment?.max_duration_day?.date || '') }}</span></p> </div> <div class="w-8 h-8 bg-[#fb7299]/20 rounded-full flex items-center justify-center"> <svg class="w-4 h-4 text-[#fb7299]" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd"/> </svg> </div> </div> </div> <div class="bg-gradient-to-br from-[#fc9b7a]/10 to-[#fb7299]/10 backdrop-blur-sm rounded-lg p-3 border border-gray-300/30 dark:border-gray-500/30"> <div class="flex items-center justify-between"> <div> <p class="text-xs text-gray-600 dark:text-gray-400">日均时长</p> <p class="text-lg font-bold text-[#fc9b7a]">{{ formatDurationShort(viewingData?.time_investment?.avg_daily_duration || 0) }}</p> </div> <div class="w-8 h-8 bg-[#fc9b7a]/20 rounded-full flex items-center justify-center"> <svg class="w-4 h-4 text-[#fc9b7a]" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"/> </svg> </div> </div> </div> <div class="bg-gradient-to-br from-[#fb7299]/10 to-[#fc9b7a]/10 backdrop-blur-sm rounded-lg p-3 border border-gray-300/30 dark:border-gray-500/30"> <div class="flex items-center justify-between"> <div> <p class="text-xs text-gray-600 dark:text-gray-400">最活跃时段</p> <p class="text-lg font-bold text-[#fb7299]">{{ getPeakTimeSlot() }}</p> </div> <div class="w-8 h-8 bg-[#fb7299]/20 rounded-full flex items-center justify-center"> <svg class="w-4 h-4 text-[#fb7299]" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M11.3 1.046A1 1 0 0112 2v5h4a1 1 0 01.82 1.573l-7 10A1 1 0 018 18v-5H4a1 1 0 01-.82-1.573l7-10a1 1 0 011.12-.38z" clip-rule="evenodd"/> </svg> </div> </div> </div> <div class="bg-gradient-to-br from-[#fc9b7a]/10 to-[#fb7299]/10 backdrop-blur-sm rounded-lg p-3 border border-gray-300/30 dark:border-gray-500/30"> <div class="flex items-center justify-between"> <div> <p class="text-xs text-gray-600 dark:text-gray-400">深夜观看</p> <p class="text-lg font-bold text-[#fc9b7a]">{{ getNightWatchCount() }}次</p> </div> <div class="w-8 h-8 bg-[#fc9b7a]/20 rounded-full flex items-center justify-center"> <svg class="w-4 h-4 text-[#fc9b7a]" fill="currentColor" viewBox="0 0 20 20"> <path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z"/> </svg> </div> </div> </div> </div> <!-- 主要图表区域 - 单个柱状图 --> <div class="flex-1"> <!-- 24小时观看分布柱状图 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-6 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-4 text-center">24小时观看分布</h4> <div ref="barChartRef" class="h-[280px]"></div> </div> </div> </div> </template> <script setup> import { ref, onMounted, watch, computed } from 'vue' import * as echarts from 'echarts' import gsap from 'gsap' const props = defineProps({ viewingData: { type: Object, required: true }, selectedYear: { type: Number, default: () => new Date().getFullYear() } }) // 图表引用 const barChartRef = ref(null) // 图表实例 let barChart = null // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } const formatDuration = (seconds) => { const hours = Math.floor(seconds / 3600) const minutes = Math.floor((seconds % 3600) / 60) return `${hours}小时${minutes}分钟` } // 短格式时长显示 const formatDurationShort = (seconds) => { const hours = Math.floor(seconds / 3600) const minutes = Math.floor((seconds % 3600) / 60) if (hours > 0) { return `${hours}h${minutes}m` } return `${minutes}m` } const formatDate = (dateStr) => { const date = new Date(dateStr) return `${date.getMonth() + 1}月${date.getDate()}日` } // 获取最活跃时段 const getPeakTimeSlot = () => { if (!props.viewingData?.daily_time_slots) return '未知' const timeData = props.viewingData.daily_time_slots const maxHour = Object.keys(timeData).reduce((a, b) => timeData[a] > timeData[b] ? a : b) const hour = parseInt(maxHour.replace('时', '')) if (hour >= 6 && hour < 12) return '上午' if (hour >= 12 && hour < 18) return '下午' if (hour >= 18 && hour < 24) return '晚上' return '深夜' } // 获取深夜观看次数 const getNightWatchCount = () => { if (!props.viewingData?.daily_time_slots) return 0 const timeData = props.viewingData.daily_time_slots let nightCount = 0 Object.keys(timeData).forEach(hour => { const h = parseInt(hour.replace('时', '')) if (h >= 0 && h < 6) { nightCount += timeData[hour] } }) return nightCount } // 获取时段对应的颜色 const getTimeSlotColor = (hour) => { const h = parseInt(hour.replace('时', '')) if (h >= 6 && h < 12) return '#7afc8c' // 上午-绿色 if (h >= 12 && h < 18) return '#fc9b7a' // 下午-橙色 if (h >= 18 && h < 24) return '#fb7299' // 晚上-粉色 return '#7a9efc' // 深夜-蓝色 } // 初始化24小时柱状图 const initBarChart = () => { if (!barChartRef.value || !props.viewingData?.daily_time_slots) return barChart = echarts.init(barChartRef.value) const timeData = props.viewingData.daily_time_slots // 准备24小时数据 const hours = [] const counts = [] for (let i = 0; i < 24; i++) { const hour = `${i}时` hours.push(`${i}:00`) counts.push(timeData[hour] || 0) } const barOption = { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: function(params) { const hour = parseInt(params[0].name.split(':')[0]) let period = '深夜' if (hour >= 6 && hour < 12) period = '上午' else if (hour >= 12 && hour < 18) period = '下午' else if (hour >= 18 && hour < 24) period = '晚上' return `${params[0].name} (${period})<br/>观看次数: ${params[0].value}` } }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'category', data: hours, axisLabel: { color: '#666', fontSize: 12, interval: 2 // 每隔2小时显示一个标签 }, axisLine: { lineStyle: { color: '#ddd' } } }, yAxis: { type: 'value', axisLabel: { color: '#666', fontSize: 12 }, axisLine: { lineStyle: { color: '#ddd' } }, splitLine: { lineStyle: { color: '#f0f0f0' } } }, series: [{ name: '观看次数', type: 'bar', data: counts.map((count, index) => ({ value: count, itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: getTimeSlotColor(`${index}时`) }, { offset: 1, color: getTimeSlotColor(`${index}时`) + '80' } ]) } })), barWidth: '60%', emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowOffsetY: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } }] } barChart.setOption(barOption) } onMounted(() => { initBarChart() // 监听窗口大小变化 window.addEventListener('resize', () => { barChart?.resize() }) }) // 监听数据变化 watch(() => props.viewingData, () => { if (props.viewingData) { initBarChart() } }, { deep: true }) </script> <style> /* 流光动画效果 */ @keyframes flow-light { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } } .animate-flow-light { position: relative; } .animate-flow-light::before, .animate-flow-light-delay-1::before, .animate-flow-light-delay-2::before { content: ''; position: absolute; top: 0; left: -100%; width: 200%; height: 100%; background: linear-gradient( 90deg, transparent, rgba(255, 255, 255, 0.1), transparent ); animation: flow-light 5s infinite linear; } .animate-flow-light-delay-1::before { animation-delay: 1s; } .animate-flow-light-delay-2::before { animation-delay: 2s; } </style>
2977094657/BiliHistoryFrontend
5,473
src/components/tailwind/analytics/pages/TimeDistributionPage.vue
<!-- 时间分布页组件 --> <template> <div class="space-y-6"> <h3 class="text-4xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 时间分布分析 </h3> <div class="text-lg text-center text-gray-600 dark:text-gray-300 mb-8 space-y-2"> <div v-if="viewingData?.insights?.weekly_pattern" v-html="formatInsightText(viewingData.insights.weekly_pattern)"></div> <div v-if="viewingData?.insights?.seasonal_pattern" v-html="formatInsightText(viewingData.insights.seasonal_pattern)"></div> </div> <!-- 图表容器 --> <div class="grid grid-cols-1 lg:grid-cols-2 gap-6"> <!-- 周度分布图表 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-6 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-4">周度分布</h4> <div class="h-[220px]"> <v-chart ref="weeklyChartRef" class="h-full w-full" :option="weeklyOption" autoresize /> </div> </div> <!-- 季节分布图表 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-6 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-4">季节分布</h4> <div class="h-[220px]"> <v-chart ref="seasonalChartRef" class="h-full w-full" :option="seasonalOption" autoresize /> </div> </div> </div> </div> </template> <script setup> import { ref, computed, onMounted } from 'vue' import gsap from 'gsap' import VChart from 'vue-echarts' import * as echarts from 'echarts/core' const props = defineProps({ viewingData: { type: Object, required: true } }) const weeklyChartRef = ref(null) const seasonalChartRef = ref(null) // 周度分布配置 const weeklyOption = computed(() => { if (!props.viewingData?.weekly_stats) return {} const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] const data = weekdays.map(day => props.viewingData.weekly_stats[day] || 0) return { tooltip: { trigger: 'axis', backgroundColor: 'rgba(28, 28, 28, 0.9)', borderColor: '#fb7299', textStyle: { color: '#fff' } }, grid: { top: '15%', left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'category', data: weekdays, axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' } }, yAxis: { type: 'value', name: '观看次数', axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' }, splitLine: { lineStyle: { color: 'rgba(0, 0, 0, 0.1)' } } }, series: [{ data: data, type: 'bar', barWidth: '60%', itemStyle: { color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [ { offset: 0, color: 'rgba(251, 114, 153, 0.9)' }, { offset: 1, color: 'rgba(252, 155, 122, 0.9)' } ]), borderRadius: [8, 8, 0, 0] }, label: { show: true, position: 'top', color: '#666', formatter: '{c}次' } }] } }) // 季节分布配置 const seasonalOption = computed(() => { if (!props.viewingData?.seasonal_patterns) return {} const data = Object.entries(props.viewingData.seasonal_patterns) .map(([season, stats]) => ({ name: season, value: stats.view_count, avg_duration: Math.round(stats.avg_duration) })) return { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, backgroundColor: 'rgba(28, 28, 28, 0.9)', borderColor: '#fb7299', textStyle: { color: '#fff' }, formatter: (params) => { const data = params[0] return `${data.name}<br/> 观看次数:${data.value}<br/> 平均时长:${data.data.avg_duration}秒` } }, grid: { top: '15%', left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'category', data: data.map(item => item.name), axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' } }, yAxis: { type: 'value', name: '观看次数', axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' }, splitLine: { lineStyle: { color: 'rgba(0, 0, 0, 0.1)' } } }, series: [{ data: data.map((item, index) => ({ ...item, itemStyle: { color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [ { offset: 0, color: `rgba(251, 114, 153, ${Math.max(0.4, 0.9 - index * 0.05)})` }, { offset: 1, color: `rgba(252, 155, 122, ${Math.max(0.4, 0.9 - index * 0.05)})` } ]) } })), type: 'bar', barWidth: '60%', label: { show: true, position: 'top', color: '#666', formatter: '{c}次' } }] } }) onMounted(() => { if (weeklyChartRef.value && seasonalChartRef.value) { gsap.from([ weeklyChartRef.value.$el, seasonalChartRef.value.$el ], { opacity: 0, y: 20, duration: 0.5, stagger: 0.1, ease: 'power2.out', delay: 0.2 }) } }) // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } </script>
2977094657/BiliHistoryFrontend
1,352
src/components/tailwind/analytics/pages/HeroPage.vue
<!-- 开场页组件 --> <template> <div class="absolute inset-0"> <div class="h-full flex items-center justify-center relative"> <div class="text-center space-y-8" ref="heroContent"> <div class="relative inline-block"> <h2 class="text-6xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent">你的B站时光机</h2> <div class="absolute -inset-1 bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] opacity-10 blur-xl"></div> </div> <p class="text-2xl text-gray-600 dark:text-gray-300">让我们开启{{ year }}年的回忆之旅</p> <div class="text-gray-500 dark:text-gray-400 animate-bounce mt-12"> <span class="block">向下滑动开始探索</span> <svg class="w-6 h-6 mx-auto mt-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3" /> </svg> </div> </div> </div> </div> </template> <script setup> import { ref, onMounted } from 'vue' import gsap from 'gsap' const props = defineProps({ year: { type: Number, required: true } }) const heroContent = ref(null) onMounted(() => { // 开场动画 gsap.from(heroContent.value.children, { opacity: 0, y: 30, duration: 1, stagger: 0.2, ease: 'power3.out' }) }) </script>
294coder/Efficient-MIF
2,952
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/showImagesAllOld.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Visualize all the images applying the same stretching for visual comparison. % % Interface: % MatrixPrint = showImagesAll(MatrixImage,titleImages,vect_index_RGB,flag_cut_bounds,dim_cut,flagPAN) % % Inputs: % MatrixImage: Matrix that contains all the images to visualize; Size: [M x N x B x Z], where [M x N] is the % dimension of a single image band, B represents the number of bands for each image, and Z is the number of images to plot. % titleImages: Vector of strings that represents the titles for each image to plot; Size: [1 x Z]. % vect_index_RGB: Identify the bands to plot to obtain an RGB representation of the multispectral data; % flag_cut_bounds: Cut the boundaries of the images to plot; % dim_cut: Define the dimension of the boundary cut; % flagPAN: Flag. If flagPAN == 1, the first image to plot is the panchromatic image otherwise it is the ground-truth. % % Outputs: % MatrixPrint: Matrix, with the same structure of MatrixImage, which contains the plotted images. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function MatrixPrint = showImagesAll(MatrixImage,titleImages,vect_index_RGB,flag_cut_bounds,dim_cut,flagPAN) if flag_cut_bounds MatrixImageCat = zeros(numel(dim_cut:size(MatrixImage,1)-dim_cut),numel(dim_cut:size(MatrixImage,2)-dim_cut),size(MatrixImage,3),size(MatrixImage,4)); for ii = 1 : size(MatrixImageCat,4) t = MatrixImage(:,:,:,ii); MatrixImageCat(:,:,:,ii) = t(dim_cut:end-dim_cut,dim_cut:end-dim_cut,:); end else MatrixImageCat = MatrixImage; end [r,c,~] = size(MatrixImageCat(:,:,:,1)); if flagPAN T = []; for ii = 2 : size(MatrixImageCat,4) T = cat(2,T,MatrixImageCat(:,:,vect_index_RGB,ii)); end else T = []; for ii = 1 : size(MatrixImageCat,4) T = cat(2,T,MatrixImageCat(:,:,vect_index_RGB,ii)); end end IMN = viewimage2(T); if flagPAN MatrixPrint = zeros(size(MatrixImageCat(:,:,vect_index_RGB,:))); MatrixPrint(:,:,:,1) = viewimage2(MatrixImageCat(:,:,vect_index_RGB,1)); ind_c = 1; for ii = 2 : size(MatrixImageCat,4) MatrixPrint(:,:,:,ii) = IMN(1 : r,ind_c : ind_c + c - 1,:); ind_c = ind_c + c; end else MatrixPrint = zeros(size(MatrixImageCat(:,:,vect_index_RGB,:))); ind_c = 1; for ii = 1 : size(MatrixImageCat,4) MatrixPrint(:,:,:,ii) = IMN(1 : r,ind_c : ind_c + c - 1,:); ind_c = ind_c + c; end end ha = tight_subplot(5,5,[.06 .03],[.01 .06],[.01 .01]); % ha = tight_subplot(5,5,[.02 0],[.01 .03],[.0 .0]); for ii = 1 : size(MatrixImageCat,4) axes(ha(ii)); imshow(MatrixPrint(:,:,:,ii),[]); title(ha(ii),titleImages{ii}); end end
294coder/Efficient-MIF
2,481
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/viewimage.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Visualization [3-2-1] of images with 3 bands by exploiting linear stretching and fixing the saturation. % % Interface: % ImageToView = viewimage(ImageToView,tol) % % Inputs: % ImageToView: Image to view; % tol: Saturation; Default values: [0.01 0.99] equal for all the three bands. % % Outputs: % ImageToView: Image to view. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ImageToView = viewimage(ImageToView,tol1,tol2,tol3) iptsetpref('ImshowBorder', 'tight') ImageToView = double(ImageToView); L=size(ImageToView,3); if (L<3) ImageToView=ImageToView(:,:,[1 1 1]); end if nargin == 1 tol1 = [0.01 0.99]; end if nargin <= 2 tol = [tol1;tol1;tol1]; ImageToView = linstretch(ImageToView,tol); figure,imshow(ImageToView(:,:,3:-1:1),[]) elseif nargin == 4 if sum(tol1(2)+tol2(2)+tol3(2)) <= 3 tol = [tol1;tol2;tol3]; ImageToView = linstretch(ImageToView,tol); figure,imshow(ImageToView(:,:,3:-1:1),[]) else tol = [tol1;tol2;tol3]; [N,M,~] = size(ImageToView); NM = N*M; for i=1:3 b = reshape(double(uint16(ImageToView(:,:,i))),NM,1); b(b<tol(i,1))=tol(i,1); b(b>tol(i,2))=tol(i,2); b = (b-tol(i,1))/(tol(i,2)-tol(i,1)); ImageToView(:,:,i) = reshape(b,N,M); end figure,imshow(ImageToView(:,:,3:-1:1),[]) end end iptsetpref('ImshowBorder', 'loose') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Linear Stretching. % % Interface: % ImageToView = linstretch(ImageToView,tol) % % Inputs: % ImageToView: Image to stretch; % tol: ; % % Outputs: % ImageToView: Stretched image. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ImageToView = linstretch(ImageToView,tol) [N,M,~] = size(ImageToView); NM = N*M; for i=1:3 b = reshape(double(uint16(ImageToView(:,:,i))),NM,1); [hb,levelb] = hist(b,max(b)-min(b)); chb = cumsum(hb); t(1)=ceil(levelb(find(chb>NM*tol(i,1), 1 ))); t(2)=ceil(levelb(find(chb<NM*tol(i,2), 1, 'last' ))); b(b<t(1))=t(1); b(b>t(2))=t(2); b = (b-t(1))/(t(2)-t(1)); ImageToView(:,:,i) = reshape(b,N,M); end end
294coder/Efficient-MIF
2,951
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/showImagesAll.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Visualize all the images applying the same stretching for visual comparison. % % Interface: % MatrixPrint = showImagesAll(MatrixImage,titleImages,vect_index_RGB,flag_cut_bounds,dim_cut,flagPAN) % % Inputs: % MatrixImage: Matrix that contains all the images to visualize; Size: [M x N x B x Z], where [M x N] is the % dimension of a single image band, B represents the number of bands for each image, and Z is the number of images to plot. % titleImages: Vector of strings that represents the titles for each image to plot; Size: [1 x Z]. % vect_index_RGB: Identify the bands to plot to obtain an RGB representation of the multispectral data; % flag_cut_bounds: Cut the boundaries of the images to plot; % dim_cut: Define the dimension of the boundary cut; % flagPAN: Flag. If flagPAN == 1, the first image to plot is the panchromatic image otherwise it is the ground-truth. % % Outputs: % MatrixPrint: Matrix, with the same structure of MatrixImage, which contains the plotted images. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function MatrixPrint = showImagesAll(MatrixImage,titleImages,vect_index_RGB,flag_cut_bounds,dim_cut,flagPAN) if flag_cut_bounds MatrixImageCat = zeros(numel(dim_cut:size(MatrixImage,1)-dim_cut),numel(dim_cut:size(MatrixImage,2)-dim_cut),size(MatrixImage,3),size(MatrixImage,4)); for ii = 1 : size(MatrixImageCat,4) t = MatrixImage(:,:,:,ii); MatrixImageCat(:,:,:,ii) = t(dim_cut:end-dim_cut,dim_cut:end-dim_cut,:); end else MatrixImageCat = MatrixImage; end [r,c,~] = size(MatrixImageCat(:,:,:,1)); if flagPAN T = []; for ii = 2 : size(MatrixImageCat,4) T = cat(2,T,MatrixImageCat(:,:,vect_index_RGB,ii)); end else T = []; for ii = 1 : size(MatrixImageCat,4) T = cat(2,T,MatrixImageCat(:,:,vect_index_RGB,ii)); end end IMN = viewimage2(T); if flagPAN MatrixPrint = zeros(size(MatrixImageCat(:,:,vect_index_RGB,:))); MatrixPrint(:,:,:,1) = viewimage2(MatrixImageCat(:,:,vect_index_RGB,1)); ind_c = 1; for ii = 2 : size(MatrixImageCat,4) MatrixPrint(:,:,:,ii) = IMN(1 : r,ind_c : ind_c + c - 1,:); ind_c = ind_c + c; end else MatrixPrint = zeros(size(MatrixImageCat(:,:,vect_index_RGB,:))); ind_c = 1; for ii = 1 : size(MatrixImageCat,4) MatrixPrint(:,:,:,ii) = IMN(1 : r,ind_c : ind_c + c - 1,:); ind_c = ind_c + c; end end % ha = tight_subplot(5,5,[.06 .03],[.01 .06],[.01 .01]); ha = tight_subplot(4,7,[.02 0],[.01 .03],[.0 .0]); for ii = 1 : size(MatrixImageCat,4) axes(ha(ii)); imshow(MatrixPrint(:,:,:,ii),[]); title(ha(ii),titleImages{ii}); end end
294coder/Efficient-MIF
5,091
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/matrix2latex.m
function matrix2latex(matrix, filename, varargin) % function: matrix2latex(...) % Author: M. Koehler % Contact: [email protected] % Version: 1.1 % Date: May 09, 2004 % This software is published under the GNU GPL, by the free software % foundation. For further reading see: http://www.gnu.org/licenses/licenses.html#GPL % Usage: % matrix2late(matrix, filename, varargs) % where % - matrix is a 2 dimensional numerical or cell array % - filename is a valid filename, in which the resulting latex code will % be stored % - varargs is one ore more of the following (denominator, value) combinations % + 'rowLabels', array -> Can be used to label the rows of the % resulting latex table % + 'columnLabels', array -> Can be used to label the columns of the % resulting latex table % + 'alignment', 'value' -> Can be used to specify the alginment of % the table within the latex document. Valid arguments are: 'l', 'c', % and 'r' for left, center, and right, respectively % + 'format', 'value' -> Can be used to format the input data. 'value' % has to be a valid format string, similar to the ones used in % fprintf('format', value); % + 'size', 'value' -> One of latex' recognized font-sizes, e.g. tiny, % HUGE, Large, large, LARGE, etc. % % Example input: % matrix = [1.5 1.764; 3.523 0.2]; % rowLabels = {'row 1', 'row 2'}; % columnLabels = {'col 1', 'col 2'}; % matrix2latex(matrix, 'out.tex', 'rowLabels', rowLabels, 'columnLabels', columnLabels, 'alignment', 'c', 'format', '%-6.2f', 'size', 'tiny'); % % The resulting latex file can be included into any latex document by: % /input{out.tex} % % Enjoy life!!! rowLabels = []; colLabels = []; alignment = 'l'; format = []; textsize = []; if (rem(nargin,2) == 1 || nargin < 2) error('matrix2latex: ', 'Incorrect number of arguments to %s.', mfilename); end okargs = {'rowlabels','columnlabels', 'alignment', 'format', 'size'}; for j=1:2:(nargin-2) pname = varargin{j}; pval = varargin{j+1}; k = strmatch(lower(pname), okargs); if isempty(k) error('matrix2latex: ', 'Unknown parameter name: %s.', pname); elseif length(k)>1 error('matrix2latex: ', 'Ambiguous parameter name: %s.', pname); else switch(k) case 1 % rowlabels rowLabels = pval; if isnumeric(rowLabels) rowLabels = cellstr(num2str(rowLabels(:))); end case 2 % column labels colLabels = pval; if isnumeric(colLabels) colLabels = cellstr(num2str(colLabels(:))); end case 3 % alignment alignment = lower(pval); if alignment == 'right' alignment = 'r'; end if alignment == 'left' alignment = 'l'; end if alignment == 'center' alignment = 'c'; end if alignment ~= 'l' && alignment ~= 'c' && alignment ~= 'r' alignment = 'l'; warning('matrix2latex: ', 'Unkown alignment. (Set it to \''left\''.)'); end case 4 % format format = lower(pval); case 5 % format textsize = pval; end end end fid = fopen(filename, 'a'); width = size(matrix, 2); height = size(matrix, 1); if isnumeric(matrix) matrix = num2cell(matrix); for h=1:height for w=1:width if(~isempty(format)) matrix{h, w} = num2str(matrix{h, w}, format); else matrix{h, w} = num2str(matrix{h, w}); end end end end if(~isempty(textsize)) fprintf(fid, '\\begin{%s}', textsize); end fprintf(fid, '\\begin{tabular}{|'); if(~isempty(rowLabels)) fprintf(fid, 'l|'); end for i=1:width fprintf(fid, '%c|', alignment); end fprintf(fid, '}\r\n'); fprintf(fid, '\\hline\r\n'); if(~isempty(colLabels)) if(~isempty(rowLabels)) fprintf(fid, '&'); end for w=1:width-1 fprintf(fid, '\\textbf{%s}&', colLabels{w}); end fprintf(fid, '\\textbf{%s}\\\\\\hline\r\n', colLabels{width}); end for h=1:height if(~isempty(rowLabels)) fprintf(fid, '\\textbf{%s}&', rowLabels{h}); end for w=1:width-1 fprintf(fid, '%s&', matrix{h, w}); end fprintf(fid, '%s\\\\\\hline\r\n', matrix{h, width}); end fprintf(fid, '\\end{tabular}\r\n'); if(~isempty(textsize)) fprintf(fid, '\\end{%s}', textsize); end fclose(fid);
294coder/Efficient-MIF
3,250
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/indwt2_working.m
function X = indwt2_working(W,varargin) %INDWT2 Inverse nondecimated 2-D wavelet transform. % INDWT2 will be removed in a future release of MATLAB. Use the % following function instead: % <a href="matlab:help iswt2">iswt2</a> % Error in R2015a % error(message('Wavelet:warnobsolete:ErrorReplaceINDWT2')); nbIN = nargin-1; idxCFS = -1; cfsFLAG = false; if nbIN>0 nbCELL = numel(W.dec); type = varargin{1}; if ~ischar(type) error(message('Wavelet:FunctionArgVal:Invalid_ArgTyp')) end type = upper(type); cfsFLAG = isequal(upper(type(1)),'C'); if cfsFLAG , type = type(2:end); end switch type case {'D','H'} , idxCFS = 0; case {'AA','LL','A','L'} , idxCFS = 1; case {'AD','LH'} , idxCFS = 2; case {'DA','HL'} , idxCFS = 3; case {'DD','HH'} , idxCFS = 4; end if nbIN>1 , levREC = varargin{2}; else levREC = W.level; end if idxCFS>1 idxCFS = idxCFS + 3*(W.level-levREC); if ~cfsFLAG for j=1:nbCELL if ~isequal(j,idxCFS); W.dec{j} = zeros(size(W.dec{j})); end end else X = W.dec{idxCFS}; % Coefficients return end elseif idxCFS==1 % Approximations (AA or LL) if cfsFLAG && levREC==W.level X = W.dec{1}; return; % Coefficients of Approximation at level MAX end idxMinToKill = 1 + 3*(W.level-levREC)+1; for j=idxMinToKill:nbCELL W.dec{j} = zeros(size(W.dec{j})); end elseif idxCFS==0 idxMaxToKill = 1 + 3*(W.level-levREC); for j=1:idxMaxToKill W.dec{j} = zeros(size(W.dec{j})); end else end end % Initialization. Lo = W.filters.LoR; Hi = W.filters.HiR; dwtEXTM = W.mode; perFLAG = isequal(dwtEXTM,'per'); cfs = W.dec; sizes = W.sizes; level = W.level; maxloop = level; if idxCFS==1 && cfsFLAG , maxloop = (level-levREC); end idxBeg = 1; for k=1:maxloop idxEnd = idxBeg+3; dec = reshape(cfs(idxBeg:idxEnd),2,2); sizerec = sizes(k+1,:); X = recFUNC(dec,sizerec,Lo,Hi,perFLAG); cfs(1:idxEnd-1) = {[]}; cfs{idxEnd} = X; idxBeg = idxEnd; end if abs(idxCFS)==1 && ~cfsFLAG && length(W.sizeINI)==3 % X = uint8(X); end %-----------------------------------------------------------------------% function X = recFUNC(dec,sINI,Lo,Hi,perFLAG) % Reconstruction. perm = [2,1,3]; W = cell(1,2); for i = 1:2 W{i} = wrec1D(dec{i,1},Lo{2},perm,perFLAG) + ... wrec1D(dec{i,2},Hi{2},perm,perFLAG); end X = (wrec1D(W{1},Lo{1},[],perFLAG) + wrec1D(W{2},Hi{1},[],perFLAG))/4; % Extraction of central part sREC = size(X); F = floor((sREC-sINI)/2); C = ceil((sREC-sINI)/2); X = X(1+F(1):end-C(1),1+F(2):end-C(2),:); %-----------------------------------------------------------------------% function X = wrec1D(X,F,perm,perFLAG) if ~isempty(perm) , X = permute(X,perm); end if perFLAG nb = length(F)-1; X = [X X(:,1:nb,:)]; end X = convn(X,F); if ~isempty(perm) , X = permute(X,perm); end %-----------------------------------------------------------------------%
294coder/Efficient-MIF
2,495
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/gen_LP_image.m
% Description: % gen_LP_image generates the Low Resolution version of the PAN image required for the calculation of the % segmentation-based version of the Gram-Schmidt algorithm, based on the segmentation S. % % Interface: % I_LR_input = gen_LP_image(Local_algorithm,I_MS,I_PAN,I_MS_LR,ratio,sensor,S) % % Inputs: % PS_algorithm: Employed segmentation-based algorithm % ('GSA','GS2GLP') % I_MS: MS image upsampled at PAN scale % I_PAN: PAN image % I_MS_LR: MS image % ratio: Scale ratio between MS and PAN. Pre-condition: Integer value. % sensor: String for type of sensor (e.g. 'WV2','IKONOS'); % % Outputs: % I_LR_input: Low Resolution version of the PAN image % % References: % % [Restaino17] R. Restaino, M. Dalla Mura, G. Vivone, J. Chanussot, Context-Adaptive Pansharpening Based on Image Segmentation, % IEEE Transactions on Geoscience and Remote Sensing, vol. 55, no. 2, pp. 753766, February 2017. % [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms, % IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_LR_input = gen_LP_image(PS_algorithm,I_MS,I_PAN,I_MS_LR,ratio,sensor) switch PS_algorithm case 'GSA' %%%%%%%%% Generation of LR PAN image PAN_LP = LPfilterGauss(I_PAN,ratio); %%%%%%%%%% Estimation of weights PAN_LP2 = imresize(PAN_LP,1/ratio,'nearest'); alpha= estimation_alpha(cat(3,I_MS_LR,ones(size(I_MS_LR,1),size(I_MS_LR,2))),PAN_LP2,'global'); [Height,Width,Bands] = size(I_MS); I_MS_col = reshape(double(I_MS), Height*Width, Bands); alpha = repmat(alpha', [size(I_MS_col,1),1]); I_LR_col = sum([I_MS_col, ones(size(I_MS_col,1),1)] .* alpha, 2); I_LR_input = reshape(I_LR_col, Height, Width); case 'GS2GLP' h = genMTF(ratio, sensor, size(I_MS,3)); for ii=1:size(h, 3) PAN_LP(:,:,ii) = imfilter(I_PAN,real(h(:,:,ii)),'replicate'); end PAN_LP2 = imresize(PAN_LP,1/ratio,'nearest'); I_LR_input = interp23tap(PAN_LP2,ratio); end
2977094657/BiliHistoryFrontend
6,407
src/components/tailwind/analytics/pages/PopularHitRatePage.vue
<!-- 热门视频命中率分析页组件 --> <template> <div class="space-y-4"> <h3 class="text-xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 热门视频命中率分析 </h3> <!-- 加载状态 --> <div v-if="loading" class="flex justify-center items-center py-12"> <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-[#fb7299]"></div> </div> <!-- 错误状态 --> <div v-else-if="error" class="text-center py-12"> <div class="text-red-500 text-lg">{{ error }}</div> </div> <!-- 主要内容 --> <div v-else-if="hitRateData" class="space-y-4"> <!-- 洞察文本 --> <div class="text-center text-gray-600 dark:text-gray-300"> <div class="text-sm leading-relaxed" v-html="formatInsightText(hitRateData.insights.join(','))"></div> </div> <!-- 可视化图表 --> <div class="grid grid-cols-1 lg:grid-cols-3 gap-4"> <!-- 命中率统计卡片 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-base font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-2 text-center"> 观看时机分析 </h4> <div ref="chartRef" class="h-[460px]"></div> </div> <!-- 热门视频列表 --> <div v-if="hitRateData.popular_videos && hitRateData.popular_videos.length > 0" class="lg:col-span-2 bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-base font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-2"> 你观看过的热门视频 (前10个) </h4> <div class="grid grid-cols-1 md:grid-cols-2 gap-2 h-[460px] overflow-y-auto"> <div v-for="(video, index) in hitRateData.popular_videos" :key="index" @click="openVideo(video.bvid)" class="flex items-center p-2 bg-gray-50/50 dark:bg-gray-800/50 rounded-lg hover:bg-gray-100/50 dark:hover:bg-gray-700/50 cursor-pointer transition-colors"> <div class="flex-1 min-w-0"> <div class="font-medium text-gray-900 dark:text-gray-100 truncate text-xs">{{ video.title }}</div> <div class="text-xs text-gray-500 dark:text-gray-400 mt-1"> <span>{{ video.author }}</span> <span class="ml-2">{{ formatDate(video.view_at) }}</span> </div> </div> </div> </div> </div> </div> </div> </div> </template> <script setup> import { ref, onMounted, watch } from 'vue' import * as echarts from 'echarts' import { getPopularHitRate } from '../../../../api/api.js' const props = defineProps({ selectedYear: { type: Number, default: () => new Date().getFullYear() }, hitRateData: { type: Object, default: null } }) const loading = ref(true) const error = ref(null) const hitRateData = ref(null) const chartRef = ref(null) let chart = null // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299] font-semibold">$1</span>') } // 格式化日期 const formatDate = (timestamp) => { return new Date(timestamp * 1000).toLocaleDateString('zh-CN') } // 打开视频 const openVideo = (bvid) => { if (bvid) { window.open(`https://www.bilibili.com/video/${bvid}`, '_blank') } } // 获取热门命中率数据 const fetchHitRateData = async (year) => { if (!year) return // 如果父组件已经传递了数据,直接使用 if (props.hitRateData) { hitRateData.value = props.hitRateData.hit_rate_analysis loading.value = false await initCharts() return } loading.value = true error.value = null try { const response = await getPopularHitRate(year) if (response.data.status === 'success') { hitRateData.value = response.data.data.hit_rate_analysis await initCharts() } else { error.value = response.data.message || '获取数据失败' } } catch (err) { console.error('获取热门命中率数据出错:', err) error.value = '获取数据时发生错误' } finally { loading.value = false } } // 初始化图表 const initCharts = async () => { await new Promise(resolve => setTimeout(resolve, 100)) // 等待DOM更新 initChart() } // 初始化图表 const initChart = () => { if (!chartRef.value || !hitRateData.value) return if (chart) { chart.dispose() } chart = echarts.init(chartRef.value) const timingData = hitRateData.value.time_pattern_analysis || {} const data = [ { name: '立即观看', value: timingData.immediate_watch || 0 }, { name: '热门期观看', value: timingData.trending_watch || 0 } ] const option = { tooltip: { trigger: 'item', formatter: function(params) { const percentage = params.percent return `${params.name}: ${params.value} 个 (${percentage}%)` } }, legend: { bottom: '8%', left: 'center', textStyle: { color: '#666', fontSize: 12 } }, series: [ { name: '观看时机', type: 'pie', radius: '70%', center: ['50%', '45%'], label: { show: true, position: 'outside', formatter: function(params) { return `${params.name}\n${params.value}个\n${params.percent}%` }, fontSize: 11, color: '#333' }, emphasis: { label: { show: true, fontSize: '13', fontWeight: 'bold' }, itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }, labelLine: { show: true, length: 15, length2: 10 }, data: data.map((item, index) => ({ ...item, itemStyle: { color: ['#fb7299', '#fc9b7a'][index] } })) } ] } chart.setOption(option) } // 监听年份变化 watch(() => props.selectedYear, (newYear) => { fetchHitRateData(newYear) }, { immediate: true }) // 监听父组件传递的数据变化 watch(() => props.hitRateData, (newData) => { if (newData) { hitRateData.value = newData.hit_rate_analysis loading.value = false initCharts() } }, { immediate: true }) // 组件挂载时获取数据 onMounted(() => { fetchHitRateData(props.selectedYear) }) </script>
2977094657/BiliHistoryFrontend
5,685
src/components/tailwind/analytics/pages/TitleSentimentAnalysisPage.vue
<template> <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8"> <div class="max-w-7xl mx-auto"> <!-- 标题和总结部分 --> <div class="text-center mb-8"> <h2 class="text-3xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 标题情感分析 </h2> <div class="mt-4 text-gray-600 max-w-3xl mx-auto" v-if="titleAnalytics && titleAnalytics.sentiment_analysis"> <p class="mb-2" v-if="titleAnalytics.sentiment_analysis.insights && titleAnalytics.sentiment_analysis.insights[0]" v-html="formatInsightText(titleAnalytics.sentiment_analysis.insights[0])"></p> <p v-if="titleAnalytics.sentiment_analysis.insights && titleAnalytics.sentiment_analysis.insights[1]" v-html="formatInsightText(titleAnalytics.sentiment_analysis.insights[1])"></p> </div> </div> <!-- 主要内容区域 - 使用网格布局 --> <div class="grid grid-cols-1 lg:grid-cols-2 gap-6"> <!-- 左侧:情感分布饼图 --> <div class="bg-white/5 backdrop-blur-sm rounded-xl p-6"> <h3 class="text-xl font-semibold text-gray-600 mb-4">情感分布</h3> <div ref="distributionChartRef" class="w-full h-[300px]"></div> </div> <!-- 右侧:完成率对比图 --> <div class="bg-white/5 backdrop-blur-sm rounded-xl p-6"> <h3 class="text-xl font-semibold text-gray-600 mb-4">情感与完成率关系</h3> <div ref="completionChartRef" class="w-full h-[300px]"></div> </div> </div> </div> </div> </template> <script setup> import { ref, onMounted, watch, onUnmounted } from 'vue' import * as echarts from 'echarts/core' const props = defineProps({ titleAnalytics: { type: Object, required: true } }) const distributionChartRef = ref(null) const completionChartRef = ref(null) let distributionChart = null let completionChart = null // 初始化情感分布饼图 const initDistributionChart = () => { if (!distributionChartRef.value || !props.titleAnalytics?.sentiment_analysis?.sentiment_stats) return distributionChart = echarts.init(distributionChartRef.value) const sentimentStats = props.titleAnalytics.sentiment_analysis.sentiment_stats const data = Object.entries(sentimentStats).map(([sentiment, stats]) => ({ name: sentiment, value: stats.count })) const option = { tooltip: { trigger: 'item', formatter: '{b}: {c}个视频 ({d}%)' }, legend: { orient: 'vertical', right: 10, top: 'center', textStyle: { color: '#4B5563' } }, series: [ { type: 'pie', radius: ['40%', '70%'], avoidLabelOverlap: false, itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 }, label: { show: false, position: 'center' }, emphasis: { label: { show: true, fontSize: 20, fontWeight: 'bold', color: '#4B5563' } }, labelLine: { show: false }, data: data.map(item => ({ ...item, itemStyle: { color: item.name === '积极' ? '#fb7299' : item.name === '消极' ? '#fc9b7a' : '#9ca3af' } })) } ] } distributionChart.setOption(option) } // 初始化完成率对比图 const initCompletionChart = () => { if (!completionChartRef.value || !props.titleAnalytics?.sentiment_analysis?.sentiment_stats) return completionChart = echarts.init(completionChartRef.value) const sentimentStats = props.titleAnalytics.sentiment_analysis.sentiment_stats const data = Object.entries(sentimentStats) .sort(([, a], [, b]) => b.avg_completion_rate - a.avg_completion_rate) .map(([sentiment, stats]) => ({ name: sentiment, value: (stats.avg_completion_rate * 100).toFixed(1) })) const option = { tooltip: { trigger: 'axis', formatter: '{b}: {c}%' }, grid: { top: '10%', left: '15%', right: '5%', bottom: '15%' }, xAxis: { type: 'category', data: data.map(item => item.name), axisLabel: { color: '#4B5563' } }, yAxis: { type: 'value', name: '平均完成率', axisLabel: { color: '#4B5563', formatter: '{value}%' } }, series: [ { data: data.map(item => ({ value: item.value, itemStyle: { color: item.name === '积极' ? '#fb7299' : item.name === '消极' ? '#fc9b7a' : '#9ca3af' } })), type: 'bar', barWidth: '40%', label: { show: true, position: 'top', color: '#4B5563', formatter: '{c}%' } } ] } completionChart.setOption(option) } // 监听窗口大小变化 const handleResize = () => { if (distributionChart) { distributionChart.resize() } if (completionChart) { completionChart.resize() } } onMounted(() => { initDistributionChart() initCompletionChart() window.addEventListener('resize', handleResize) }) onUnmounted(() => { window.removeEventListener('resize', handleResize) if (distributionChart) { distributionChart.dispose() } if (completionChart) { completionChart.dispose() } }) // 监听数据变化 watch(() => props.titleAnalytics, () => { if (distributionChart) { initDistributionChart() } if (completionChart) { initCompletionChart() } }, { deep: true }) // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } </script>
298582245/wqwl_qinglong
15,512
wqwl_打卡赚小钱钱.js
/** * 脚本:wqwl_打卡赚小钱钱.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序打卡赚小钱钱 * 环境变量:wqwl_dkzxqq,多个换行或新建多个变量 * 环境变量描述:抓包请求参数下的token,格式例如:token#备注1 * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 3 * * * 一天一次 */ /** * 入口:https://gitee.com/cobbWmy/img/blob/master/dakazhuanxiaoqianiqian.png * 写本不易走个头呗 */ const axios = require('axios'); const fs = require('fs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || true; //并发数,默认4 let bfs = process.env["wqwl_bfs"] || 4; // 是否通知 let isNotify = true; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_dkzxqq'; //脚本名称 const name = '微信小程序打卡赚小钱钱' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } // let fileData = wqwlkj.readFile('dkzxqq') class Task { constructor(ck) { this.index = index++; this.ck = ck this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) } async init() { const ckData = this.ck.split('#') if (ckData.length < 1) { return this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 1) { this.remark = ckData[0].slice(0, 8); } else { this.remark = ckData[1]; } this.token = ckData[0]; this.headers = { "accept": "*/*", "accept-language": "zh-CN,zh;q=0.9", "content-type": "application/x-www-form-urlencoded", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "xweb_xhr": "1", "referrer": "https://servicewechat.com/wxd03a809cfc99930b/4/page-frame.html", "referrerPolicy": "unsafe-url", } /* this.today = wqwlkj.formatDate(new Date()) if (!fileData[this.remark]) fileData[this.remark] = {} if (!fileData[this.remark][this.today]) fileData[this.remark][this.today] = { 'sign': false, 'ad': false, 'sp': false } if (fileData[this.remark][this.today]['sign'] && fileData[this.remark][this.today]['ad'] && fileData[this.remark][this.today]['sp']) { this.sendMessage(`✅今日任务已经全部完成啦`) return false } */ if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } return true } async info() { try { const url = this.getUrl('today', 'index') const options = { url: url, headers: this.headers, method: 'GET' } const res = await this.request(options, 0); this.sendMessage(`✅获取信息成功,打卡币:${res?.info?.today?.currency},余额:${res?.info?.today?.money},今日打卡次数:${res?.info?.today?.clock}`) return { currency: res?.info?.today?.currency, money: res?.info?.today?.money, clock: res?.info?.today?.clock } } catch (e) { throw new Error(`❌获取信息失败,${e.message}`) } } async start() { try { const url = this.getUrl('addTips', 'my') const options = { url: url, headers: this.headers, method: 'GET' } const res = await this.request(options, 0); if (res?.status === 1) return true else return false //this.sendMessage(`✅获取信息成功,打卡币:${res?.info?.today?.currency},余额:${res?.info?.today?.money},今日打卡次数:${res?.info?.today?.clock}`) //return { currency: res?.info?.today?.currency, money: res?.info?.today?.money, clock: res?.info?.today?.clock } } catch (e) { throw new Error(`❌获取信息失败,${e.message}`) } } async end() { try { let url = this.getUrl('sign', 'clock', { captcha_code: '', click_ad: 1 }) url += `&captcha_code=&click_ad=1` const options = { url: url, headers: this.headers, method: 'GET' } const res = await this.request(options, 0); // console.log(res) if (res?.status === 1) return this.sendMessage(`✅模拟打卡成功`) else return this.sendMessage(`❌模拟打卡失败,原因:: ${JSON.stringify(res)}`) //this.sendMessage(`✅获取信息成功,打卡币:${res?.info?.today?.currency},余额:${res?.info?.today?.money},今日打卡次数:${res?.info?.today?.clock}`) //return { currency: res?.info?.today?.currency, money: res?.info?.today?.money, clock: res?.info?.today?.clock } } catch (e) { throw new Error(`❌获取信息失败,${e.message}`) } } async Moneyinfo() { try { let url = this.getUrl('cash', 'my') const options = { url: url, headers: this.headers, method: 'GET' } const res = await this.request(options, 0); // console.log(res) if (res?.status === 1) { const money = res?.info?.member?.money const least_money = res?.info?.least_money this.sendMessage(`✅获取信息成功,余额:${money},提现最低金额:${least_money}`, true) if (money >= least_money) await this.withdraw(money) } else { return this.sendMessage(`❌获取信息失败,原因:: ${JSON.stringify(res)}`) } } catch (e) { throw new Error(`❌获取信息请求失败,${e.message}`) } } async withdraw(money) { try { let url = this.getUrl('withdrawals', 'my', { money: money }) url += `&money=${money}` const options = { url: url, headers: this.headers, method: 'GET' } const res = await this.request(options, 0); // console.log(res) if (res?.status === 1) { return this.sendMessage(`✅提现成功`) } else { return this.sendMessage(`❌提现失败,原因: ${JSON.stringify(res)}`) } } catch (e) { throw new Error(`❌提现请求失败,${e.message}`) } } async main() { const isFinish = await this.init() if (!isFinish) return //await this.withdraw(0.04) await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) const { clock } = await this.info() if (clock < 5) { let i = parseInt(clock) for (; i < 5; i++) { this.sendMessage(`📝开始第 ${i + 1} 次打卡`) const isStart = await this.start() if (isStart) { await wqwlkj.sleep(wqwlkj.getRandom(30, 40)) await this.end() } await wqwlkj.sleep(wqwlkj.getRandom(10, 16)) } await this.info() } await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.Moneyinfo() } getUrl(action, contr, arg = {}) { if (!this.token || !action) return `❌验证数据为空` let url = `https://rr.qq66.cn/app/index.php?i=157&t=0&v=1.0.1&from=wxapp&c=entry&a=wxapp&do=distribute&m=bh_rising&action=${action}&contr=${contr}&token=${this.token}&version=3.5.4` const sign = this.getSign(url, arg) url += `&sign=${sign}` return url } getSign(e, t, n) { const getUrlParam = (url, param) => { const urlObj = new URL(url, 'http://rr.qq66.cn'); return urlObj.searchParams.get(param); }; const getQuery = (url) => { const urlObj = new URL(url, 'http://rr.qq66.cn'); const params = []; urlObj.searchParams.forEach((value, name) => { params.push({ name, value }); }); return params; }; let i = ""; const o = getUrlParam(e, "sign"); if (o || (t && t.sign)) { return false; } if (e) { i = getQuery(e); } if (t) { let s = []; for (let u in t) { if (t.hasOwnProperty(u) && u && t[u] !== "") { s.push({ name: u, value: t[u] }); } } i = i.concat(s); } // 替代 _.sortBy(i, "name") i.sort((a, b) => { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }); // 替代 _.uniq(i, true, "name") const seen = new Set(); i = i.filter(item => { if (!item || !item.name) return false; if (seen.has(item.name)) return false; seen.add(item.name); return true; }); let c = ""; for (let f = 0; f < i.length; f++) { if (i[f] && i[f].name && i[f].value !== "") { c += i[f].name + "=" + i[f].value; if (f < i.length - 1) { c += "&"; } } } const secret = n || undefined; //console.log(c, secret); return wqwlkj.md5(c + '&' + secret); } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); return data; } catch (error) { this.sendMessage(`🔐检测到请求发生错误,正在重试...`) // 刷新代理 const newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } // wqwlkj.saveFile(fileData, 'dkzxqq') console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
2881099/FreeSql.AdminLTE
4,302
Examples/net80_blazor/Infrastructure/Extensions/StringExtension.cs
using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; public static class StringExtension { /// <summary> /// 判断字符串是否为Null、空 /// </summary> /// <param name="s"></param> /// <returns></returns> public static bool IsNull(this string s) { return string.IsNullOrWhiteSpace(s); } /// <summary> /// 与字符串进行比较,忽略大小写 /// </summary> /// <param name="s"></param> /// <param name="value"></param> /// <returns></returns> public static bool EqualsIgnoreCase(this string s, string value) { return s.Equals(value, StringComparison.OrdinalIgnoreCase); } /// <summary> /// 首字母转小写 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string FirstCharToLower(this string s) { if (string.IsNullOrEmpty(s)) return s; string str = s.First().ToString().ToLower() + s.Substring(1); return str; } /// <summary> /// 首字母转大写 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string FirstCharToUpper(this string s) { if (string.IsNullOrEmpty(s)) return s; string str = s.First().ToString().ToUpper() + s.Substring(1); return str; } /// <summary> /// 转为Base64,UTF-8格式 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string ToBase64(this string s) { return s.ToBase64(Encoding.UTF8); } /// <summary> /// 转为Base64 /// </summary> /// <param name="s"></param> /// <param name="encoding">编码</param> /// <returns></returns> public static string ToBase64(this string s, Encoding encoding) { if (s.IsNull()) return string.Empty; var bytes = encoding.GetBytes(s); return Convert.ToBase64String(bytes); } /// <summary> /// 转换为16进制 /// </summary> /// <param name="bytes"></param> /// <param name="lowerCase">是否小写</param> /// <returns></returns> public static string ToHex(this byte[] bytes, bool lowerCase = true) { if (bytes == null) return null; var result = new StringBuilder(); var format = lowerCase ? "x2" : "X2"; for (var i = 0; i < bytes.Length; i++) { result.Append(bytes[i].ToString(format)); } return result.ToString(); } /// <summary> /// 16进制转字节数组 /// </summary> /// <param name="s"></param> /// <returns></returns> public static byte[] HexToBytes(this string s) { if (s.IsNull()) return null; var bytes = new byte[s.Length / 2]; for (int x = 0; x < s.Length / 2; x++) { int i = (Convert.ToInt32(s.Substring(x * 2, 2), 16)); bytes[x] = (byte)i; } return bytes; } public static string ToMask(this string s) { if (s.IsNull()) return string.Empty; return Regex.Replace( Regex.Replace( Regex.Replace(s, @"(\d{3})\d{4}(\d{4})", m => $"{m.Groups[1]?.Value}****{m.Groups[2]?.Value}"), "(?<=.{2})[^@]+(?=.{2}@)", "****"), @"(\d{1,3})\.\d{1,3}\.\d{1,3}\.\d{1,3}", m => $"{m.Groups[1]?.Value}.*.*.{m.Groups[4]?.Value}"); } private static readonly string _chars = "0123456789"; private static readonly char[] _constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; /// <summary> /// 生成随机字符串,默认32位 /// </summary> /// <param name="length">随机数长度</param> /// <returns></returns> public static string GenerateRandom(this string _, int length = 32) { var newRandom = new StringBuilder(); var rd = new Random(); for (int i = 0; i < length; i++) { newRandom.Append(_constant[rd.Next(_constant.Length)]); } return newRandom.ToString(); } /// <summary> /// 生成随机6位数 /// </summary> /// <param name="length"></param> /// <returns></returns> public static string GenerateRandomNumber(this string _, int length = 6) { var random = new Random(); return new string(Enumerable.Repeat(_chars, length).Select(s => s[random.Next(s.Length)]).ToArray()); } }
298582245/wqwl_qinglong
13,535
wqwl_老板机器.js
/** * 脚本:wqwl_老板机器.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序老板机器 * 环境变量:wqwl_lbjq,多个换行或新建多个变量 * 环境变量描述:抓包Headers下的authorization,格式例如:authorization#备注1(authorization去掉Bearer ) * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 3 * * * 一天一次 */ /* * 单纯签到领积分 * 写本不易,走个人头谢谢:https://gitee.com/cobbWmy/img/blob/master/laobanjiqi.jpg * */ const axios = require('axios'); const fs = require('fs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || true; //并发数,默认4 let bfs = process.env["wqwl_bfs"] || 4; // 是否通知 let isNotify = true; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_lbjq'; //脚本名称 const name = '微信小程序老板机器' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } let fileData = wqwlkj.readFile('lbjq') class Task { constructor(ck) { this.index = index++; this.ck = ck this.baseUrl = 'https://aio.myroki.com/api/v1' this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) } async init() { const ckData = this.ck.split('#') if (ckData.length < 1) { return this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 1) { this.remark = `${ckData[0].slice(0, 8)}-${index}`; } else { this.remark = ckData[1]; } this.token = ckData[0]; let ua if (!fileData[this.remark]) fileData[this.remark] = {} if (!fileData[this.remark]['ua']) { ua = wqwlkj.generateRandomUA(); fileData[this.remark]['ua'] = ua } else ua = fileData[this.remark]['ua']; this.sendMessage(`🎲使用ua:${ua}`); this.headers = { 'app-version': 5000, 'app-id': 'roki_app', Connection: 'keep-alive', 'xweb_xhr': 1, 'User-Agent': ua, 'X-App-Env': 'release', 'X-USER-TOKEN': this.token, 'Content-Type': 'application/json', Accept: '*/*', Referer: 'https://servicewechat.com/wxba70fb8e3eb3aab9/350/page-frame.html', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate', } if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } return true } async checkIn() { const encryptData = this.getHeaders('POST', {}) //console.log(encryptData) const headers = { ...this.headers, ...encryptData.headers } try { const options = { url: `${this.baseUrl}/mini-app/user/check-in-record/check-in`, headers: headers, method: 'POST', data: JSON.stringify({}) } // console.log(options) const res = await this.request(options) if (res?.success) { return this.sendMessage(`✅签到成功`, true) } else { return this.sendMessage(`❌签到失败,${res?.message || 'ck可能不对或者过期了'}`, true) } } catch (e) { return this.sendMessage(`❌签到请求失败,${e.message}`) } } //https://aio.myroki.com/api/v1/mini-app/user/profile async profile() { const encryptData = this.getHeaders('GET', {}) //console.log(encryptData) const headers = { ...this.headers, ...encryptData.headers } try { const options = { url: `${this.baseUrl}/mini-app/user/profile`, headers: headers, method: 'GET', } //console.log(options) const res = await this.request(options) if (res?.success) { return this.sendMessage(`✅【${res?.data?.nickName || '默认昵称'}】积分:${res?.data?.points}`, true) } else { return this.sendMessage(`❌个人信息获取失败,${res?.message || 'ck可能不对或者过期了'}`, true) } } catch (e) { return this.sendMessage(`❌个人请求失败,${e.message}`, true) } } async main() { await this.init() const b1 = await this.checkIn() if (b1.includes('过期')) return await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); await this.profile() } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); return data; } catch (error) { console.log(error) this.sendMessage(`🔐检测到请求发生错误,正在重试...`) let newProxy; if (isProxy) { newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); } else { this.sendMessage(`⚠️未使用代理`); newProxy = true } if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } jiami(data = '1234567890123456', publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQwjPnvbv5nPPUrCdo167kcYd+7UqWYuedCNhLQradkfVJ0Ce8qkqTEmD9aWH1+t6gYQVmaPWIjZCW0U1DqacYKJ6JZzUsFWzYaSIr+OXoJ5OvNNxWqAGMz/GkJkeXWcQ+dLLnMmLzNIhbakdXoZzzvdde5IOj5YWk2/nK97pHGwIDAQAB') { let cleanedPublicKey = publicKey.trim(); if (!cleanedPublicKey.includes('-----BEGIN')) { cleanedPublicKey = `-----BEGIN PUBLIC KEY-----\n${cleanedPublicKey}\n-----END PUBLIC KEY-----`; } return wqwlkj.rsaEncrypt(data, cleanedPublicKey, 'hex'); } jiemi(encryptedData, privateKey) { return wqwlkj.rsaDecrypt(encryptedData, privateKey, 'hex'); } hmacSHAsign(e = 'ee8694419924a22f04ac0e01368683521daa659f', r) { return wqwlkj.hmacSHA256(r, e) } getStrFun(e) { return Object.keys(e).sort() .map(key => `${key}=${e[key]}`) .join('&'); } getHeaders(method = 'GET', requestData = {}) { const p = '1234567890123456'; const publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQwjPnvbv5nPPUrCdo167kcYd+7UqWYuedCNhLQradkfVJ0Ce8qkqTEmD9aWH1+t6gYQVmaPWIjZCW0U1DqacYKJ6JZzUsFWzYaSIr+OXoJ5OvNNxWqAGMz/GkJkeXWcQ+dLLnMmLzNIhbakdXoZzzvdde5IOj5YWk2/nK97pHGwIDAQAB'; // 第一层加密(基础header) const a1 = this.jiami(p, publicKey); const n1 = Date.now(); const c1 = { aesEncryptSecret: a1, appId: "roki_app", nonce: p, secret: "ee8694419924a22f04ac0e01368683521daa659f", timestamp: n1 }; const d1 = this.getStrFun(c1); const f1 = this.hmacSHAsign("ee8694419924a22f04ac0e01368683521daa659f", d1); const baseHeaders = { timestamp: n1, nonce: p, secret: a1, signature: encodeURIComponent(f1), "app-version": 5000 }; // 第二层加密(数据加密部分) const a2 = this.jiami(p, publicKey); const n2 = Date.now(); const c2 = { aesEncryptSecret: a2, appId: "roki_app", nonce: p, secret: "ee8694419924a22f04ac0e01368683521daa659f", timestamp: n2.toString() }; const d2 = this.getStrFun(c2); // console.log(d2) const f2 = this.hmacSHAsign("ee8694419924a22f04ac0e01368683521daa659f", d2); const encryptHeaders = { "app-id": "roki_app", timestamp: n2.toString(), nonce: p, secret: a2, signature: encodeURIComponent(f2), "app-version": 5000 }; // 合并headers const finalHeaders = { ...baseHeaders, ...encryptHeaders }; let encryptedData = null; // 处理数据加密 if (method.toLowerCase() === 'post' || method.toLowerCase() === 'put') { if (Object.keys(requestData).length > 0) { encryptedData = this.jiami(JSON.stringify(requestData), p); } } else if (Object.keys(requestData).length > 0) { // GET请求的参数加密 encryptedData = this.jiami(JSON.stringify(requestData), p); } return { headers: finalHeaders, encryptedData: encryptedData }; } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } wqwlkj.saveFile(fileData, 'lbjq') console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
294coder/Efficient-MIF
1,855
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/showImage8_zoomin.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Visualize and print an eight-band multispectral image. % % Interface: % showImage8(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L) % % Inputs: % I_MS: Eight band multispectral image; % print: Flag. If print == 1, print EPS image; % id: Identifier (name) of the printed EPS image; % flag_cut_bounds: Cut the boundaries of the viewed Panchromatic image; % dim_cut: Define the dimension of the boundary cut; % th_values: Flag. If th_values == 1, apply an hard threshold to the dynamic range; % L: Radiomatric resolution of the input image. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showImage8_zoomin(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L, location1, location2) if flag_cut_bounds I_MS = I_MS(dim_cut:end-dim_cut,dim_cut:end-dim_cut,:); end if th_values I_MS(I_MS > 2^L) = 2^L; I_MS(I_MS < 0) = 0; end if id == 1 IMN = viewimage(I_MS(:,:,[1,3,5])); IMN = IMN(:,:,3:-1:1); else IMN = viewimage(I_MS(:,:,[1,3,5]),[0.01 0.995]); IMN = IMN(:,:,3:-1:1); end if isempty(location2) ent=rectangleonimage(IMN,location1,1, 3, 3, 2, 1); % put close-up to up-right corner figure,imshow(ent,[]) else % type =1 (put to down-left); type =2 (put to down-right); % type =3 (put to up-right); type =4 (put to up-left); ent=rectangleonimage(IMN,location1,1, 3, 3, 3, 1); % put close-up to up-right corner ent=rectangleonimage(ent,location2,1, 3, 2, 3, 2); % put close-up to down-right corner figure,imshow(ent,[]) end if print printImage(IMN,sprintf('Outputs/%d.eps',id)); end end
294coder/Efficient-MIF
2,817
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/resize_images.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Resize_images generates the low resolution panchromatic (PAN) and multispectral (MS) images according to Wald's protocol. % % Interface: % [I_MS_LR, I_PAN_LR] = resize_images(I_MS,I_PAN,ratio,sensor) % % Inputs: % I_MS: MS image upsampled at PAN scale; % I_PAN: PAN image; % ratio: Scale ratio between MS and PAN. Pre-condition: Integer value; % sensor: String for type of sensor (e.g. 'WV2', 'IKONOS'). % % Outputs: % I_MS_LR: Low Resolution MS image; % I_PAN_LR: Low Resolution PAN image. % % References: % [Wald97] L. Wald, T. Ranchin, and M. Mangolini, Fusion of satellite images of different spatial resolutions: assessing the quality of resulting images, % Photogrammetric Engineering and Remote Sensing, vol. 63, no. 6, pp. 691699, June 1997. % [Aiazzi02] B. Aiazzi, L. Alparone, S. Baronti, and A. Garzelli, Context-driven fusion of high spatial and spectral resolution images based on % oversampled multiresolution analysis, IEEE Transactions on Geoscience and Remote Sensing, vol. 40, no. 10, pp. 23002312, October % 2002. % [Aiazzi06] B. Aiazzi, L. Alparone, S. Baronti, A. Garzelli, and M. Selva, MTF-tailored multiscale fusion of high-resolution MS and Pan imagery, % Photogrammetric Engineering and Remote Sensing, vol. 72, no. 5, pp. 591596, May 2006. % [Vivone14a] G. Vivone, R. Restaino, M. Dalla Mura, G. Licciardi, and J. Chanussot, Contrast and error-based fusion schemes for multispectral % image pansharpening, IEEE Geoscience and Remote Sensing Letters, vol. 11, no. 5, pp. 930934, May 2014. % [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms, % IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [I_MS_LR, I_PAN_LR] = resize_images(I_MS,I_PAN,ratio,sensor) I_MS = double(I_MS); I_PAN = double(I_PAN); I_MS_LP = MTF(I_MS,sensor,ratio); %%% Decimation MS I_MS_LP_D = zeros(round(size(I_MS,1)/ratio),round(size(I_MS,2)/ratio),size(I_MS,3)); for idim = 1 : size(I_MS,3) I_MS_LP_D(:,:,idim) = imresize(I_MS_LP(:,:,idim),1/ratio,'nearest'); end I_MS_LR = double(I_MS_LP_D); I_PAN_LR = imresize(I_PAN, 1/ratio); end
294coder/Efficient-MIF
3,262
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/rectangleonimage.m
function ent=rectangleonimage(pic,sw,n, ch, c, scale, type) % sw: the location of the up-left, down-right % n: the width of the line % ch: ch = 1 (gray image); ch = 3 (color image) % c: the color of the line: c=1(red); c=2(green); c=3(blue);c=others % scale: the salce of zooming in for SR % type =1 (put to down-left); type =2 (put to down-right); % type =3 (put to up-right); type =4 (put to up-left); % Liang-Jian Deng (UESTC) % improved time: 2017-3-11 %==============================% if nargin< 5 scale = []; end x0=sw(1);x1=sw(2);y0=sw(3);y1=sw(4); [p q ch]=size(pic); max_val = 1; %ch=1:gray image; ch=3: color image if ch==1 if c==1 pic(x0:x1,y0:y0+n)=max_val; pic(x0:x1,y1-n:y1)=max_val; pic(x0:x0+n,y0:y1)=max_val; pic(x1-n:x1,y0:y1)=max_val; elseif c==2 pic(x0:x1,y0:y0+n)=0; pic(x0:x1,y1-n:y1)=0; pic(x0:x0+n,y0:y1)=0; pic(x1-n:x1,y0:y1)=0; else pic(x0:x1,y0:y0+n)=max_val-pic(x0:x1,y0:y0+n); %ȡ pic(x0:x1,y1-n:y1)=max_val- pic(x0:x1,y1-n:y1); pic(x0:x0+n,y0:y1)=max_val-pic(x0:x0+n,y0:y1); pic(x1-n:x1,y0:y1)=max_val-pic(x1-n:x1,y0:y1); end end if ch==3 if c==1 pic(x0:x1,y0:y0+n,1)=max_val; pic(x0:x1,y0:y0+n,2)=0; pic(x0:x1,y0:y0+n,3)=0; pic(x0:x1,y1-n:y1,1)=max_val; pic(x0:x1,y1-n:y1,2)=0; pic(x0:x1,y1-n:y1,3)=0; pic(x0:x0+n,y0:y1,1)=max_val; pic(x0:x0+n,y0:y1,2)=0; pic(x0:x0+n,y0:y1,3)=0; pic(x1-n:x1,y0:y1,1)=max_val; pic(x1-n:x1,y0:y1,2)=0; pic(x1-n:x1,y0:y1,3)=0; elseif c==2 pic(x0:x1,y0:y0+n,1)=0;pic(x0:x1,y0:y0+n,2)=max_val;pic(x0:x1,y0:y0+n,3)=0; pic(x0:x1,y1-n:y1,1)=0;pic(x0:x1,y1-n:y1,2)=max_val;pic(x0:x1,y1-n:y1,3)=0; pic(x0:x0+n,y0:y1,1)=0;pic(x0:x0+n,y0:y1,2)=max_val;pic(x0:x0+n,y0:y1,3)=0; pic(x1-n:x1,y0:y1,1)=0;pic(x1-n:x1,y0:y1,2)=max_val;pic(x1-n:x1,y0:y1,3)=0; elseif c==3 pic(x0:x1,y0:y0+n,1)=0;pic(x0:x1,y0:y0+n,2)=0;pic(x0:x1,y0:y0+n,3)=max_val; pic(x0:x1,y1-n:y1,1)=0;pic(x0:x1,y1-n:y1,2)=0;pic(x0:x1,y1-n:y1,3)=max_val; pic(x0:x0+n,y0:y1,1)=0;pic(x0:x0+n,y0:y1,2)=0;pic(x0:x0+n,y0:y1,3)=max_val; pic(x1-n:x1,y0:y1,1)=0;pic(x1-n:x1,y0:y1,2)=0;pic(x1-n:x1,y0:y1,3)=max_val; else %inverse pic(x0:x1,y0:y0+n,1:3)=max_val-pic(x0:x1,y0:y0+n,1:3); pic(x0:x1,y1-n:y1,1:3)=max_val-pic(x0:x1,y1-n:y1,1:3); pic(x0:x0+n,y0:y1,1:3)=max_val-pic(x0:x0+n,y0:y1,1:3); pic(x1-n:x1,y0:y1,1:3)=max_val-pic(x1-n:x1,y0:y1,1:3); end end ent=pic; sampIm = pic(x0:x1, y0:y1, :); SampIm = imresize(sampIm, scale,'nearest'); % nearest to zooming in the local part switch type case 1 % put zoom in image on the down-left [a, b, third] = size(SampIm); ent((p-a+1):p,1:b, :) = SampIm; case 2 % put zoom in image on the down-left [a, b, third] = size(SampIm); ent((p-a+1):p,(q-b+1):q, :) = SampIm; case 3 % put zoom in image on the up-right [a, b, third] = size(SampIm); ent(1:a,(q-b+1):q, :) = SampIm; case 4 % put zoom in image on the up-right [a, b, third] = size(SampIm); ent(1:a,1:b, :) = SampIm; end
294coder/Efficient-MIF
2,684
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/genMTF.m
% Description: % Generate a bank of filters shaped on the MTF of the sensor. Each filter % corresponds to a band acquired by the sensor. % % Interface: % h = genMTF(ratio, sensor, nbands) % % Inputs: % ratio: Scale ratio between MS and PAN. Pre-condition: Integer value. % sensor: String for type of sensor (e.g. 'WV2','IKONOS'); % nbands: Number of spectral bands. % % Outputs: % h: Gaussian filter mimicking the MTF of the MS sensor % % References: % [Aiazzi02] B. Aiazzi, L. Alparone, S. Baronti, and A. Garzelli, Context-driven fusion of high spatial and spectral resolution images based on % oversampled multiresolution analysis,? IEEE Transactions on Geoscience and Remote Sensing, vol. 40, no. 10, pp. 2300?2312, October % 2002. % [Aiazzi06] B. Aiazzi, L. Alparone, S. Baronti, A. Garzelli, and M. Selva, MTF-tailored multiscale fusion of high-resolution MS and Pan imagery,? % Photogrammetric Engineering and Remote Sensing, vol. 72, no. 5, pp. 591?596, May 2006. % [Vivone14a] G. Vivone, R. Restaino, M. Dalla Mura, G. Licciardi, and J. Chanussot, Contrast and error-based fusion schemes for multispectral % image pansharpening,? IEEE Geoscience and Remote Sensing Letters, vol. 11, no. 5, pp. 930?934, May 2014. % [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms?, % IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 2565?2586, May 2015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = genMTF(ratio, sensor, nbands) switch sensor case 'QB' GNyq = [0.34 0.32 0.30 0.22]; % Band Order: B,G,R,NIR case 'IKONOS' GNyq = [0.26,0.28,0.29,0.28]; % Band Order: B,G,R,NIR case {'GeoEye1','WV4'} GNyq = [0.23,0.23,0.23,0.23]; % Band Order: B,G,R,NIR case 'WV2' GNyq = [0.35 .* ones(1,7), 0.27]; case 'WV3' GNyq = [0.325 0.355 0.360 0.350 0.365 0.360 0.335 0.315]; otherwise GNyq = 0.3 .* ones(1, nbands); end %%% MTF N = 41; nBands = length(GNyq); h = zeros(N, N, nBands); fcut = 1/ratio; for ii = 1 : nBands alpha = sqrt(((N-1)*(fcut/2))^2/(-2*log(GNyq(ii)))); H = fspecial('gaussian', N, alpha); Hd = H./max(H(:)); h(:,:,ii) = fwind1(Hd,kaiser(N)); end
2977094657/BiliHistoryFrontend
6,604
src/components/tailwind/analytics/pages/TitleAnalysisPage.vue
<template> <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8"> <div class="max-w-7xl mx-auto"> <!-- 标题和总结部分 --> <div class="text-center mb-8"> <h2 class="text-3xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 标题关键词分析 </h2> <div class="mt-4 text-gray-600 max-w-3xl mx-auto" v-if="titleAnalytics && titleAnalytics.insights"> <p class="mb-2" v-if="titleAnalytics.insights[0]" v-html="formatInsightText(titleAnalytics.insights[0])"></p> <p class="mb-2" v-if="titleAnalytics.insights[1]" v-html="formatInsightText(titleAnalytics.insights[1])"></p> <p v-if="titleAnalytics.insights[2]" v-html="formatInsightText(titleAnalytics.insights[2])"></p> </div> </div> <!-- 主要内容区域 - 使用网格布局 --> <div class="grid grid-cols-1 lg:grid-cols-5 gap-6"> <!-- 左侧:词云图 --> <div class="lg:col-span-2 bg-white/5 backdrop-blur-sm rounded-xl p-6"> <h3 class="text-xl font-semibold text-gray-600 mb-4">热门关键词</h3> <div ref="wordCloudRef" class="w-full h-[300px]"></div> </div> <!-- 右侧:完成率对比图表 - 占更多空间 --> <div class="lg:col-span-3 bg-white/5 backdrop-blur-sm rounded-xl p-6"> <h3 class="text-xl font-semibold text-gray-600 mb-4">关键词完成率对比</h3> <div ref="completionChartRef" class="w-full h-[300px]"></div> </div> </div> </div> </div> </template> <script setup> import { ref, onMounted, watch, computed, onUnmounted } from 'vue' import * as echarts from 'echarts/core' const props = defineProps({ titleAnalytics: { type: Object, required: true } }) const wordCloudRef = ref(null) const completionChartRef = ref(null) let wordCloudChart = null let completionChart = null // 处理完成率数据 const highCompletionRates = computed(() => { if (!props.titleAnalytics?.keyword_analysis?.completion_rates) return {} const rates = Object.entries(props.titleAnalytics.keyword_analysis.completion_rates) .sort(([, a], [, b]) => b.average_completion_rate - a.average_completion_rate) .slice(0, 5) return Object.fromEntries(rates) }) const lowCompletionRates = computed(() => { if (!props.titleAnalytics?.keyword_analysis?.completion_rates) return {} const rates = Object.entries(props.titleAnalytics.keyword_analysis.completion_rates) .sort(([, a], [, b]) => a.average_completion_rate - b.average_completion_rate) .slice(0, 5) return Object.fromEntries(rates) }) // 初始化词云图 const initWordCloud = () => { if (!wordCloudRef.value || !props.titleAnalytics?.keyword_analysis?.top_keywords) return wordCloudChart = echarts.init(wordCloudRef.value) const wordCloudData = props.titleAnalytics.keyword_analysis.top_keywords.map(item => ({ name: item.word, value: item.count, textStyle: { color: `rgb(${Math.random() * 70 + 185}, ${Math.random() * 70 + 185}, ${Math.random() * 70 + 185})` } })) const option = { tooltip: { show: true, formatter: function(params) { return `${params.name}: ${params.value}次` }, backgroundColor: 'rgba(0, 0, 0, 0.7)', borderColor: 'rgba(251, 114, 153, 0.7)', borderWidth: 1, padding: [5, 10], textStyle: { color: '#e1e1e1', fontSize: 12 } }, series: [{ type: 'wordCloud', shape: 'circle', left: 'center', top: 'center', width: '90%', height: '90%', right: null, bottom: null, sizeRange: [12, 60], rotationRange: [-45, 45], rotationStep: 45, gridSize: 8, drawOutOfBound: false, layoutAnimation: true, textStyle: { fontFamily: 'sans-serif', fontWeight: 'bold' }, emphasis: { focus: 'self', textStyle: { shadowBlur: 10, shadowColor: '#333' } }, data: wordCloudData }] } wordCloudChart.setOption(option) } // 初始化完成率对比图表 const initCompletionChart = () => { if (!completionChartRef.value || !props.titleAnalytics?.keyword_analysis?.completion_rates) return completionChart = echarts.init(completionChartRef.value) // 合并所有数据并按完成率排序 const allData = Object.entries(props.titleAnalytics.keyword_analysis.completion_rates) .map(([word, data]) => ({ word, rate: (data.average_completion_rate * 100).toFixed(1) })) .sort((a, b) => Number(b.rate) - Number(a.rate)) .slice(0, 10) const option = { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: function(params) { return `${params[0].name}: ${params[0].value}%` } }, grid: { top: '10%', left: '10%', right: '8%', bottom: '15%' }, xAxis: { type: 'value', max: function(value) { // 动态设置最大值,确保有足够空间显示完整数值 return Math.ceil(value.max * 1.1) }, axisLabel: { color: '#4B5563', formatter: '{value}%' }, splitLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.1)' } } }, yAxis: { type: 'category', data: allData.map(item => item.word).reverse(), axisLabel: { color: '#4B5563' } }, series: [ { name: '完成率', type: 'bar', data: allData.map(item => item.rate).reverse(), itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [ { offset: 0, color: '#fb7299' }, { offset: 1, color: '#fc9b7a' } ]) }, label: { show: true, position: 'right', color: '#4B5563', formatter: '{c}%' } } ] } completionChart.setOption(option) } // 监听窗口大小变化 const handleResize = () => { if (wordCloudChart) { wordCloudChart.resize() } if (completionChart) { completionChart.resize() } } onMounted(() => { initWordCloud() initCompletionChart() window.addEventListener('resize', handleResize) }) onUnmounted(() => { window.removeEventListener('resize', handleResize) if (wordCloudChart) { wordCloudChart.dispose() } if (completionChart) { completionChart.dispose() } }) // 监听数据变化 watch(() => props.titleAnalytics, () => { if (wordCloudChart) { initWordCloud() } if (completionChart) { initCompletionChart() } }, { deep: true }) // 格式化洞察文字,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } </script>
298582245/wqwl_qinglong
10,822
wqwl_且悠.js
/** * 脚本:wqwl_且悠.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序且悠 * 环境变量:wqwl_qieyou,多个换行或新建多个变量 * 环境变量描述:抓包请求参数下的access_token,请求头中Extra-Data中的sid,uuid格式例如:access_token#sid#uuid#备注1 * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 3 * * * 一天一次 */ const axios = require('axios'); const fs = require('fs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || false; //并发数,默认4 let bfs = process.env["wqwl_bfs"] || 4; // 是否通知 let isNotify = true; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_qieyou'; //脚本名称 const name = '微信小程序且悠' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } // let fileData = wqwlkj.readFile('qieyou') class Task { constructor(ck) { this.index = index++; this.ck = ck this.baseUrl = 'https://h5.youzan.com' this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) } async init() { const ckData = this.ck.split('#') if (ckData.length < 3) { return this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 3) { this.remark = ckData[0].slice(0, 8); } else { this.remark = ckData[3]; } this.token = ckData[0]; this.sid = ckData[1]; this.uuid = ckData[2]; this.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090922) XWEB/8555', 'Content-Type': 'application/json', 'Extra-Data': JSON.stringify({ is_weapp: 1, sid: this.sid, version: "3.165.8.101", client: "weapp", bizEnv: "retail", uuid: this.uuid, ftime: Date.now() }), 'xweb_xhr': '1', 'Referer': 'https://servicewechat.com/wxe344bbbf9be876c9/90/page-frame.html' } this.params = { app_id: 'wxe344bbbf9be876c9', kdt_id: 150539347, access_token: this.token } if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } return true } async checkInfo() { try { let headers = this.headers headers['ftime'] = Date.now() const options = { url: `${this.baseUrl}/wscump/checkin/check-in-info.json`, method: 'GET', headers: headers, params: this.params, proxy: this.proxy } const res = await this.request(options, this.proxy) if (res.code === 0) { const checkInId = res.data.checkInId this.sendMessage(`✅获取签到id成功,id为:${checkInId}`) return checkInId } else { this.sendMessage(`❌获取签到ID信息失败,${res.message}`) return false } } catch (e) { throw new Error(`❌获取签到ID信息请求失败,${e.message}`) } } async checkIn(checkinId) { try { let headers = this.headers headers['ftime'] = Date.now() let params = { checkinId: checkinId, ...this.params } const options = { url: `${this.baseUrl}/wscump/checkin/checkinV2.json`, method: 'GET', headers: headers, params: params, proxy: this.proxy } const res = await this.request(options, this.proxy) // console.log(res) if (res.code === 0) { //const checkInId = res.data.checkInId this.sendMessage(`✅签到成功`) return true } else { this.sendMessage(`❌签到失败,${res.msg}`) return false } } catch (e) { throw new Error(`❌签到请求失败,${e.message}`) } } async info() { try { let headers = this.headers headers['ftime'] = Date.now() const options = { url: `${this.baseUrl}/wscuser/membercenter/init-data.json`, method: 'GET', headers: headers, params: this.params, proxy: this.proxy } const res = await this.request(options, this.proxy) if (res.code === 0) { //const checkInId = res.data.checkInId this.sendMessage(`✅当前积分:${res?.data?.member?.stats?.points}`, true) return true } else { this.sendMessage(`❌获取信息失败,${res.message}`) return false } } catch (e) { throw new Error(`❌获取信息请求失败,${e.message}`) } } async main() { await this.init() const checkInId = await this.checkInfo() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) if (checkInId) { await this.checkIn(checkInId) } await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.info() } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); return data; } catch (error) { this.sendMessage(`🔐检测到请求发生错误,正在重试...`) let newProxy; if (isProxy) { newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); } else { this.sendMessage(`⚠️未使用代理`); newProxy = true } if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } // wqwlkj.saveFile(fileData, 'qieyou') console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
298582245/wqwl_qinglong
12,242
wqwl_旧衣小二.js
/** * 脚本:wqwl_旧衣小二.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序旧衣小二 * 环境变量:wqwl_jyxe,多个换行或新建多个变量 * 环境变量描述:抓包https://jiuyixiaoer.fzjingzhou.com/api/请求体token=xxx,格式:xxx#备注 * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 3 * * * 一天一次 */ const axios = require('axios'); const fs = require('fs'); const qs = require('qs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || false; //并发数,默认4 let bfs = process.env["wqwl_bfs"] || 4; // 是否通知 let isNotify = true; //开启则打印每一次请求的返回结果 let isDebug = false; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_jyxe'; //脚本名称 const name = '微信小程序旧衣小二' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); if (typeof wqwlkj.findTypes == "function") { let type = await wqwlkj.findTypes(name); console.log(`============================ 🚀 当前脚本:${name} 🚀 📂 所属分类:${type} 📂 ============================\n`) } let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } let fileData = wqwlkj.readFile('jyxe') || {} class Task { constructor(ck) { this.index = index++; this.ck = ck this.baseUrl = 'https://jiuyixiaoer.fzjingzhou.com/api' this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) } async init() { const ckData = this.ck.split('#') if (ckData.length < 1) { return this.sendMessage(`${this.index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 1) { this.remark = `${ckData[0].slice(0, 8)}-${this.index}`; } else { this.remark = ckData[1]; } this.token = ckData[0]; let ua if (!fileData[this.remark]) fileData[this.remark] = {} if (!fileData[this.remark]['ua']) { ua = wqwlkj.generateRandomUA(); fileData[this.remark]['ua'] = ua } else ua = fileData[this.remark]['ua']; this.sendMessage(`🎲使用ua:${ua}`); // this.sendMessage(`🎲使用随机ua:${ua}`); this.headers = { 'Host': 'jiuyixiaoer.fzjingzhou.com', 'Connection': 'keep-alive', 'xweb_xhr': '1', 'platform': 'MP-WEIXIN', 'User-Agent': ua, 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*/*', 'Sec-Fetch-Site': 'cross-site', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty', 'Referer': 'https://servicewechat.com/wx426d52c8130b8559/5/page-frame.html', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate' } if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } return true } async sign() { try { const options = { method: 'POST', url: `${this.baseUrl}/Person/sign`, headers: this.headers, data: qs.stringify({ token: this.token }) } const res = await this.request(options) // console.log(res) if (res.code === 1000) this.sendMessage(`✅签到成功,获得:${res.data}环保币`, true) else this.sendMessage(`❌签到失败,${res.msg}`, true) return true } catch (e) { this.sendMessage(`❌签到请求失败,${e.message}`, true) return false } } async info() { try { const options = { method: 'POST', url: `${this.baseUrl}/Person/index`, headers: this.headers, data: qs.stringify({ token: this.token }) } const res = await this.request(options) // console.log(res) if (res.code === 1000) { if (res.data.score >= 20) { await this.scoreWithdraw(res.data.score, res.data.exchange) } else { this.sendMessage(`🪙【${res.data.nickname}】环保币:${res.data.score}≈${res.data.exchange}元`, true) this.sendMessage(`⚠️不足以提现,跳过提现操作`) } } else this.sendMessage(`❌信息获取失败,${res.msg}`, true) return true } catch (e) { this.sendMessage(`❌信息获取请求失败,${e.message}`, true) return false } } async scoreWithdraw(score, money) { try { const options = { method: 'POST', url: `${this.baseUrl}/cash/scoreWithdraw`, headers: this.headers, data: qs.stringify({ type: 'wx_account', score: score, token: this.token }) } this.sendMessage(`尝试提现${score}环保币(≈${money}元)...`) const res = await this.request(options) // console.log(res) if (res.code === 1000) { this.sendMessage(`🎉提现成功!提现 ${score} 环保币(≈${money}元)`, true) //重新获取环保币数量 await this.info() } else this.sendMessage(`❌提现失败,${res.msg}`, true) return true } catch (e) { this.sendMessage(`❌提现请求失败,${e.message}`, true) return false } } async main() { const isFinish = await this.init() if (!isFinish) return await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) const bool = await this.sign() if (!bool) return await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.info() } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); if (isDebug) { if (isDebug === 2) console.log(JSON.stringify(options)) const formatData = (data) => { if (data === null) return 'null'; if (data === undefined) return 'undefined'; if (typeof data === 'string') return data; if (typeof data === 'object') { try { return JSON.stringify(data, null, 2); // 美化输出 } catch (error) { return `[对象序列化失败: ${error.message}]`; } } return String(data); }; this.sendMessage(`[调试输出] ${options?.method}请求${options?.url}返回:${formatData(data)}`); } return data; } catch (error) { this.sendMessage(`🔐检测到请求发生错误,正在重试...`) let newProxy; if (isProxy) { newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); } else { this.sendMessage(`⚠️未使用代理`); newProxy = true } if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } wqwlkj.saveFile(fileData, 'jyxe') console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
2977094657/BiliHistoryFrontend
7,398
src/components/tailwind/analytics/pages/AuthorPopularAssociationPage.vue
<template> <div class="space-y-4"> <h3 class="text-xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> UP主热门关联分析 </h3> <!-- 加载状态 --> <div v-if="loading" class="flex justify-center items-center py-12"> <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-[#fb7299]"></div> </div> <!-- 错误状态 --> <div v-else-if="error" class="text-center py-12"> <div class="text-red-500 text-lg">{{ error }}</div> </div> <!-- 主要内容 --> <div v-else-if="associationData" class="space-y-4"> <!-- 洞察文本 --> <div class="text-center text-gray-600 dark:text-gray-300"> <div class="text-sm leading-relaxed" v-html="formatInsightText(insights.join(','))"></div> </div> <!-- 可视化图表 --> <div class="grid grid-cols-1 lg:grid-cols-3 gap-4"> <!-- UP主热门能力分布图 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-base font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-2 text-center"> 热门制造机分布 </h4> <div ref="chartRef" class="h-[460px]"></div> </div> <!-- 热门UP主列表 --> <div v-if="popularAuthors && popularAuthors.length > 0" class="lg:col-span-2 bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-base font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-2"> 热门制造机UP主 (前10个,按热门视频数排序) </h4> <div class="grid grid-cols-1 md:grid-cols-2 gap-2 h-[460px] overflow-y-auto"> <div v-for="(author, index) in popularAuthors" :key="index" class="flex items-center p-2 bg-gray-50/50 dark:bg-gray-800/50 rounded-lg hover:bg-gray-100/50 dark:hover:bg-gray-700/50 transition-colors"> <div class="flex-1 min-w-0"> <div class="font-medium text-gray-900 dark:text-gray-100 truncate text-xs">{{ author.author_name }}</div> <div class="text-xs text-gray-500 dark:text-gray-400 mt-1"> <span class="text-red-500">{{ author.popular_videos_watched }}个热门</span> <span class="ml-2">观看{{ author.total_videos_watched }}个</span> </div> <div class="text-xs text-gray-400 mt-1"> <span>热门率: {{ author.popular_rate }}%</span> <span class="ml-2">总热门: {{ author.total_popular_videos }}个</span> </div> </div> </div> </div> </div> </div> </div> </div> </template> <script setup> import { ref, onMounted, watch, computed } from 'vue' import * as echarts from 'echarts' import { getAuthorPopularAssociation } from '../../../../api/api.js' const props = defineProps({ selectedYear: { type: Number, default: () => new Date().getFullYear() }, data: { type: Object, default: null } }) const loading = ref(true) const error = ref(null) const associationData = ref(null) const chartRef = ref(null) let chart = null // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299] font-semibold">$1</span>') } // 计算属性 const insights = computed(() => { if (!associationData.value) return [] return associationData.value.insights || [] }) const popularAuthors = computed(() => { if (!associationData.value) return [] return (associationData.value.popular_authors || []).slice(0, 10) }) // 获取UP主热门关联数据 const fetchAssociationData = async (year) => { if (!year) return // 如果父组件已经传递了数据,直接使用 if (props.data) { associationData.value = props.data loading.value = false await initCharts() return } loading.value = true error.value = null try { const response = await getAuthorPopularAssociation(year) if (response.data.status === 'success') { associationData.value = response.data.data.association_analysis await initCharts() } else { error.value = response.data.message || '获取数据失败' } } catch (err) { console.error('获取UP主热门关联数据出错:', err) error.value = '获取数据时发生错误' } finally { loading.value = false } } // 初始化图表 const initCharts = async () => { await new Promise(resolve => setTimeout(resolve, 100)) // 等待DOM更新 initChart() } // 初始化图表 const initChart = () => { if (!chartRef.value || !associationData.value) return if (chart) { chart.dispose() } chart = echarts.init(chartRef.value) const totalAuthors = associationData.value.total_authors const popularAuthorCount = associationData.value.popular_author_count const normalAuthorCount = totalAuthors - popularAuthorCount const option = { tooltip: { trigger: 'item', formatter: function(params) { const percentage = params.percent return `${params.name}: ${params.value} 个 (${percentage}%)` } }, legend: { bottom: '8%', left: 'center', textStyle: { color: '#666', fontSize: 12 } }, series: [ { name: 'UP主分布', type: 'pie', radius: '70%', center: ['50%', '45%'], label: { show: true, position: 'outside', formatter: function(params) { return `${params.name}\n${params.value}个\n${params.percent}%` }, fontSize: 11, color: '#333' }, emphasis: { label: { show: true, fontSize: '13', fontWeight: 'bold' }, itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }, labelLine: { show: true, length: 15, length2: 10 }, data: [ { value: popularAuthorCount, name: '热门制造机', itemStyle: { color: { type: 'linear', x: 0, y: 0, x2: 1, y2: 1, colorStops: [ { offset: 0, color: '#fb7299' }, { offset: 1, color: '#fc9b7a' } ] } } }, { value: normalAuthorCount, name: '普通UP主', itemStyle: { color: { type: 'linear', x: 0, y: 0, x2: 1, y2: 1, colorStops: [ { offset: 0, color: '#e0e0e0' }, { offset: 1, color: '#c0c0c0' } ] } } } ] } ] } chart.setOption(option) } // 监听年份变化 watch(() => props.selectedYear, (newYear) => { fetchAssociationData(newYear) }, { immediate: true }) // 监听父组件传递的数据变化 watch(() => props.data, (newData) => { if (newData) { associationData.value = newData loading.value = false initCharts() } }, { immediate: true }) // 组件挂载时获取数据 onMounted(() => { fetchAssociationData(props.selectedYear) }) </script> <style scoped> .line-clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } </style>
281677160/openwrt-package
2,674
luci-app-passwall2/luasrc/view/passwall2/global/faq.htm
<% local api = require "luci.passwall2.api" -%> <style> .dns-con { padding: 1rem; } .faq-title { color: var(--primary); font-weight: bolder; margin-bottom: 0.5rem; display: inline-block; } .reset-title { color: var(--primary); font-weight: bolder; margin-bottom: 0.3rem; display: inline-block; margin-top: 1.2rem; text-decoration: underline; } .dns-item { margin-bottom: 0.8rem; line-height:1.2rem; } .dns-list { text-indent:1rem; line-height: 1.2rem; } </style> <div class="dns-con"> <div id="faq_dns"> <ul> <b class="faq-title"><%:DNS related issues:%></b> <li class="dns-item">1. <span><%:Certain browsers such as Chrome have built-in DNS service, which may affect DNS resolution settings. You can go to 'Settings -> Privacy and security -> Use secure DNS' menu to turn it off.%></span></li> <li class="dns-item">2. <span><%:If you are unable to access the internet after reboot, please try clearing the cache of your terminal devices (make sure to close all open browser application windows first, this step is especially important):%></span> <ul><li class="dns-list"> ◦ <span><%:For Windows systems, open Command Prompt and run the command 'ipconfig /flushdns'.%></span></li> <li class="dns-list"> ◦ <span><%:For Mac systems, open Terminal and run the command 'sudo killall -HUP mDNSResponder'.%></span></li> <li class="dns-list"> ◦ <span><%:For mobile devices, you can clear it by reconnecting to the network, such as toggling Airplane Mode and reconnecting to WiFi.%></span></li> </ul> </li> <li class="dns-item">3. <span><%:Please make sure your device's network settings point both the DNS server and default gateway to this router, to ensure DNS queries are properly routed.%></span></li> </ul> </div> <div id="faq_reset"></div> </div> <script> var origin = window.location.origin; var hide_url = origin + "<%=api.url("hide")%>"; var show_url = origin + "<%=api.url("show")%>"; function hide(url) { if (confirm('<%:Are you sure to hide?%>') == true) { window.location.href = hide_url; } } var dom = document.getElementById("faq_reset"); if (dom) { var li = ""; li += "<a href='#' class='reset-title' onclick='hide()'>" + "<%: Hide in main menu:%>"+ "</a>" + "<br />" + "<%: Browser access: %>" + "<a href='#' onclick='hide()'>" + hide_url + "</a>" + "<br />"; li += "<a href='#' class='reset-title'>" + "<%: Show in main menu:%>"+ "</a>" + "<br />" +"<%: Browser access: %>" + "<a href='#'>" + show_url + "</a>" + "<br />"; dom.innerHTML = li; } </script>
294coder/Efficient-MIF
5,394
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/ndwt2_working.m
function varargout = ndwt2_working(X,level,varargin) %NDWT2 Nondecimated 2-D wavelet transform. % NDWT2 will be removed in a future release of MATLAB. Use the % following function instead: % <a href="matlab:help swt2">swt2</a> % Error in R2015a % error(message('Wavelet:warnobsolete:ErrorReplaceNDWT2')); nbIn = length(varargin); if nbIn < 1 error(message('MATLAB:narginchk:notEnoughInputs')); elseif nbIn > 5 error(message('MATLAB:narginchk:tooManyInputs')); end LoD = cell(1,2); HiD = cell(1,2); LoR = cell(1,2); HiR = cell(1,2); if ischar(varargin{1}) [LD,HD,LR,HR] = wfilters(varargin{1}); for k = 1:2 LoD{k} = LD; HiD{k} = HD; LoR{k} = LR; HiR{k} = HR; end elseif isstruct(varargin{1}) if isfield(varargin{1},'w1') && isfield(varargin{1},'w2') for k = 1:2 [LoD{k},HiD{k},LoR{k},HiR{k}] = ... wfilters(varargin{1}.(['w' int2str(k)])); end elseif isfield(varargin{1},'LoD') && isfield(varargin{1},'HiD') && ... isfield(varargin{1},'LoR') && isfield(varargin{1},'HiR') for k = 1:2 LoD{k} = varargin{1}.LoD{k}; HiD{k} = varargin{1}.HiD{k}; LoR{k} = varargin{1}.LoR{k}; HiR{k} = varargin{1}.HiR{k}; end else error(message('Wavelet:FunctionArgVal:Invalid_ArgVal')); end elseif iscell(varargin{1}) if ischar(varargin{1}{1}) for k = 1:2 [LoD{k},HiD{k},LoR{k},HiR{k}] = wfilters(varargin{1}{k}); end else LoD(1:end) = varargin{1}(1); HiD(1:end) = varargin{1}(2); LoR(1:end) = varargin{1}(3); HiR(1:end) = varargin{1}(4); end else end nextArg = 2; dwtEXTM = 'sym'; while nbIn>=nextArg argName = varargin{nextArg}; argVal = varargin{nextArg+1}; nextArg = nextArg + 2; switch argName case 'mode' , dwtEXTM = argVal; end end % Initialization. if isempty(X) , varargout{1} = []; return; end sX = size(X); X = double(X); sizes = zeros(level+1,length(sX)); sizes(level+1,:) = sX; for k=1:level dec = decFUNC(X,LoD,HiD,dwtEXTM); X = dec{1,1,1}; sizes(level+1-k,:) = size(X); dec = reshape(dec,4,1,1); if k>1 cfs(1) = []; cfs = cat(1,dec,cfs); else cfs = dec; end end WT.sizeINI = sX; WT.level = level; WT.filters.LoD = LoD; WT.filters.HiD = HiD; WT.filters.LoR = LoR; WT.filters.HiR = HiR; WT.mode = dwtEXTM; WT.dec = cfs; WT.sizes = sizes; varargout{1} = WT; %-------------------------------------------------------------------------% function dec = decFUNC(X,LoD,HiD,dwtEXTM) dec = cell(2,2); permVect = []; [a_Lo,d_Hi] = wdec1D(X,LoD{1},HiD{1},permVect,dwtEXTM); permVect = [2,1,3]; [dec{1,1},dec{1,2}] = wdec1D(a_Lo,LoD{2},HiD{2},permVect,dwtEXTM); [dec{2,1},dec{2,2}] = wdec1D(d_Hi,LoD{2},HiD{2},permVect,dwtEXTM); %-------------------------------------------------------------------------% function [L,H] = wdec1D(X,Lo,Hi,perm,dwtEXTM) if ~isempty(perm) , X = permute(X,perm); end sX = size(X); if length(sX)<3 , sX(3) = 1; end lf = length(Lo); lx = sX(2); lc = lx+lf-1; switch dwtEXTM case 'zpd' % Zero extension. case {'sym','symh'} % Symmetric extension (half-point). X = [X(:,lf-1:-1:1,:) , X , X(:,end:-1:end-lf+1,:)]; case 'sp0' % Smooth extension of order 0. X = [X(:,ones(1,lf-1),:) , X , X(:,lx*ones(1,lf-1),:)]; case {'sp1','spd'} % Smooth extension of order 1. Z = zeros(sX(1),sX(2)+ 2*lf-2,sX(3)); Z(:,lf:lf+lx-1,:) = X; last = sX(2)+lf-1; for k = 1:lf-1 Z(:,last+k,:) = 2*Z(:,last+k-1,:)- Z(:,last+k-2,:); Z(:,lf-k,:) = 2*Z(:,lf-k+1,:)- Z(:,lf-k+2,:); end X = Z; clear Z; case 'symw' % Symmetric extension (whole-point). X = [X(:,lf:-1:2,:) , X , X(:,end-1:-1:end-lf,:)]; case {'asym','asymh'} % Antisymmetric extension (half-point). X = [-X(:,lf-1:-1:1,:) , X , -X(:,end:-1:end-lf+1,:)]; case 'asymw' % Antisymmetric extension (whole-point). X = [-X(:,lf:-1:2,:) , X , -X(:,end-1:-1:end-lf,:)]; case 'rndu' % Uniformly randomized extension. X = [randn(sX(1),lf-1,sX(3)) , X , randn(sX(1),lf-1,sX(3))]; case 'rndn' % Normally randomized extension. X = [randn(sX(1),lf-1,sX(3)) , X , randn(sX(1),lf-1,sX(3))]; case 'ppd' % Periodized extension (1). X = [X(:,end-lf+2:end,:) , X , X(:,1:lf-1,:)]; case 'per' % Periodized extension (2). if rem(lx,2) , X = [X , X(:,end,:)]; end X = [X(:,end-lf+2:end,:) , X , X(:,1:lf-1,:)]; end L = convn(X,Lo); H = convn(X,Hi); clear X switch dwtEXTM case 'zpd' otherwise lenL = size(L,2); first = lf; last = lenL-lf+1; L = L(:,first:last,:); H = H(:,first:last,:); lenL = size(L,2); first = 1+floor((lenL-lc)/2); last = first+lc-1; L = L(:,first:last,:); H = H(:,first:last,:); end if isequal(dwtEXTM,'per') first = 1; last = lx; L = L(:,first:last,:); H = H(:,first:last,:); end if ~isempty(perm) L = permute(L,perm); H = permute(H,perm); end %-------------------------------------------------------------------------%
294coder/Efficient-MIF
2,103
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/LPfilterGauss.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % LPfilterGauss filters the panchromatic (PAN) image using a Gaussin filter with gain at Nyquist frequency 0.3. % % Interface: % I_PAN_LR = LPfilterGauss(I_PAN,ratio) % % Inputs: % I_PAN: PAN image; % ratio: Scale ratio between MS and PAN. % % Outputs: % I_PAN_LR: Output filtered MS image. % % References: % [Aiazzi02] B. Aiazzi, L. Alparone, S. Baronti, and A. Garzelli, Context-driven fusion of high spatial and spectral resolution images based on % oversampled multiresolution analysis, IEEE Transactions on Geoscience and Remote Sensing, vol. 40, no. 10, pp. 23002312, October % 2002. % [Aiazzi06] B. Aiazzi, L. Alparone, S. Baronti, A. Garzelli, and M. Selva, MTF-tailored multiscale fusion of high-resolution MS and Pan imagery, % Photogrammetric Engineering and Remote Sensing, vol. 72, no. 5, pp. 591596, May 2006. % [Vivone14a] G. Vivone, R. Restaino, M. Dalla Mura, G. Licciardi, and J. Chanussot, Contrast and error-based fusion schemes for multispectral % image pansharpening, IEEE Geoscience and Remote Sensing Letters, vol. 11, no. 5, pp. 930934, May 2014. % [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms, % IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_PAN_LR = LPfilterGauss(I_PAN,ratio) GNyq = 0.3; N = 41; fcut = 1/ratio; alpha = sqrt((N*(fcut/2))^2/(-2*log(GNyq))); H = fspecial('gaussian', N, alpha); Hd = H./max(H(:)); h = fwind1(Hd,kaiser(N)); I_PAN_LR = imfilter(I_PAN,real(h),'replicate'); end
294coder/Efficient-MIF
1,855
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/showImage8_zoomin.asv
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Visualize and print an eight-band multispectral image. % % Interface: % showImage8(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L) % % Inputs: % I_MS: Eight band multispectral image; % print: Flag. If print == 1, print EPS image; % id: Identifier (name) of the printed EPS image; % flag_cut_bounds: Cut the boundaries of the viewed Panchromatic image; % dim_cut: Define the dimension of the boundary cut; % th_values: Flag. If th_values == 1, apply an hard threshold to the dynamic range; % L: Radiomatric resolution of the input image. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showImage8_zoomin(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L, location1, location2) if flag_cut_bounds I_MS = I_MS(dim_cut:end-dim_cut,dim_cut:end-dim_cut,:); end if th_values I_MS(I_MS > 2^L) = 2^L; I_MS(I_MS < 0) = 0; end if id == 1 IMN = viewimage(I_MS(:,:,[1,3,5])); IMN = IMN(:,:,3:-1:1); else IMN = viewimage(I_MS(:,:,[1,3,5]),[0.01 0.995]); IMN = IMN(:,:,3:-1:1); end if isempty(location2) ent=rectangleonimage(IMN,location1,1, 3, 3, 3, 1); % put close-up to up-right corner figure,imshow(ent,[]) else % type =1 (put to down-left); type =2 (put to down-right); % type =3 (put to up-right); type =4 (put to up-left); ent=rectangleonimage(IMN,location1,1, 3, 3, 3, 1); % put close-up to up-right corner ent=rectangleonimage(ent,location2,1, 3, 2, 3, 2); % put close-up to down-right corner figure,imshow(ent,[]) end if print printImage(IMN,sprintf('Outputs/%d.eps',id)); end end
294coder/Efficient-MIF
2,352
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/interp23tap.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % interp23tap interpolates the image I_Interpolated using a polynomial with 23 coefficients interpolator. % % Interface: % I_Interpolated = interp23tap(I_Interpolated,ratio) % % Inputs: % I_Interpolated: Image to interpolate; % ratio: Scale ratio between MS and PAN. Pre-condition: Resize factors power of 2. % % Outputs: % I_Interpolated: Interpolated image. % % References: % [Aiazzi02] B. Aiazzi, L. Alparone, S. Baronti, and A. Garzelli, Context-driven fusion of high spatial and spectral resolution images based on % oversampled multiresolution analysis,? IEEE Transactions on Geoscience and Remote Sensing, vol. 40, no. 10, pp. 2300?2312, October % 2002. % [Aiazzi13] B. Aiazzi, S. Baronti, M. Selva, and L. Alparone, Bi-cubic interpolation for shift-free pan-sharpening,? ISPRS Journal of Photogrammetry % and Remote Sensing, vol. 86, no. 6, pp. 65?76, December 2013. % [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms?, % IEEE Transaction on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 2565?2586, May 2015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_Interpolated = interp23tap(I_Interpolated,ratio) if (2^round(log2(double(ratio))) ~= ratio) disp('Error: Only resize factors power of 2'); return; end [r,c,b] = size(I_Interpolated); CDF23 = 2.*[0.5 0.305334091185 0 -0.072698593239 0 0.021809577942 0 -0.005192756653 0 0.000807762146 0 -0.000060081482]; CDF23 = [fliplr(CDF23(2:end)) CDF23]; BaseCoeff = CDF23; first = 1; for z = 1 : ratio/2 I1LRU = zeros((2^z) * r, (2^z) * c, b); if first I1LRU(2:2:end,2:2:end,:) = I_Interpolated; first = 0; else I1LRU(1:2:end,1:2:end,:) = I_Interpolated; end for ii = 1 : b t = I1LRU(:,:,ii); t = imfilter(t',BaseCoeff,'circular'); I1LRU(:,:,ii) = imfilter(t',BaseCoeff,'circular'); end I_Interpolated = I1LRU; end end
294coder/Efficient-MIF
1,903
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/indexes_evaluation.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Reduced resolution quality indexes. % % Interface: % [Q_index, SAM_index, ERGAS_index, sCC, Q2n_index] = indexes_evaluation(I_F,I_GT,ratio,L,Q_blocks_size,flag_cut_bounds,dim_cut,th_values) % % Inputs: % I_F: Fused Image; % I_GT: Ground-Truth image; % ratio: Scale ratio between MS and PAN. Pre-condition: Integer value; % L: Image radiometric resolution; % Q_blocks_size: Block size of the Q-index locally applied; % flag_cut_bounds: Cut the boundaries of the viewed Panchromatic image; % dim_cut: Define the dimension of the boundary cut; % th_values: Flag. If th_values == 1, apply an hard threshold to the dynamic range. % % Outputs: % Q_index: Q index; % SAM_index: Spectral Angle Mapper (SAM) index; % ERGAS_index: Erreur Relative Globale Adimensionnelle de Synthse (ERGAS) index; % sCC: spatial Correlation Coefficient between fused and ground-truth images; % Q2n_index: Q2n index. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Q_index, SAM_index, ERGAS_index, sCC, Q2n_index] = indexes_evaluation(I_F,I_GT,ratio,L,Q_blocks_size,flag_cut_bounds,dim_cut,th_values) if flag_cut_bounds I_GT = I_GT(dim_cut:end-dim_cut,dim_cut:end-dim_cut,:); I_F = I_F(dim_cut:end-dim_cut,dim_cut:end-dim_cut,:); end if th_values I_F(I_F > 2^L) = 2^L; I_F(I_F < 0) = 0; end cd Quality_Indices Q2n_index = q2n(I_GT,I_F,Q_blocks_size,Q_blocks_size); Q_index = Q(I_GT,I_F,2^L); SAM_index = SAM(I_GT,I_F); ERGAS_index = ERGAS(I_GT,I_F,ratio); sCC = SCC(I_F,I_GT); cd .. end
2977094657/BiliHistoryFrontend
2,655
src/components/tailwind/analytics/pages/StreakPage.vue
<!-- 连续观看记录页组件 --> <template> <div class="space-y-6"> <h3 class="text-4xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 连续观看记录 </h3> <div v-if="viewingData?.insights?.continuity" class="text-lg text-center text-gray-600 dark:text-gray-300 mb-8" v-html="formatInsightText(viewingData.insights.continuity)" > </div> <div v-if="viewingData?.viewing_continuity" class="grid grid-cols-2 gap-8"> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-6 border border-gray-300/50 dark:border-gray-500/50"> <div class="text-4xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent streak-number">{{ viewingData.viewing_continuity.max_streak || 0 }}天</div> <div class="text-lg text-gray-600 dark:text-gray-400 mt-2">最长连续观看</div> <div v-if="viewingData.viewing_continuity.longest_streak_period" class="mt-4 text-sm text-gray-500"> {{ viewingData.viewing_continuity.longest_streak_period.start }} 至 {{ viewingData.viewing_continuity.longest_streak_period.end }} </div> </div> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-6 border border-gray-300/50 dark:border-gray-500/50"> <div class="text-4xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent streak-number">{{ viewingData.viewing_continuity.current_streak || 0 }}天</div> <div class="text-lg text-gray-600 dark:text-gray-400 mt-2">当前连续观看</div> <div v-if="viewingData.viewing_continuity.current_streak_start" class="mt-4 text-sm text-gray-500"> 开始于 {{ viewingData.viewing_continuity.current_streak_start }} </div> </div> </div> <!-- 数据加载中或无数据时的提示 --> <div v-else class="text-center text-gray-500 dark:text-gray-400"> 正在加载连续观看数据... </div> </div> </template> <script setup> import { onMounted } from 'vue' import gsap from 'gsap' const props = defineProps({ viewingData: { type: Object, required: true } }) onMounted(() => { // 数字动画效果 const streakNumbers = document.querySelectorAll('.streak-number') streakNumbers.forEach(el => { const finalValue = parseInt(el.textContent) gsap.fromTo(el, { textContent: 0 }, { duration: 2, textContent: finalValue, snap: { textContent: 1 }, ease: 'power1.out' } ) }) }) // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } </script>
298582245/wqwl_qinglong
25,396
wqwl_毛铺草本荟.js
/** * 脚本:wqwl_毛铺草本荟.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序毛铺草本荟 * 环境变量:wqwl_mpcbh,多个换行或新建多个变量 * 环境变量描述:抓包Headers下的authorization,格式例如:authorization#备注1(authorization去掉Bearer ) * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 0 * * * 一天一次即可 */ const axios = require('axios'); const fs = require('fs'); const city = process.env["wq_mp_diqu"] || "上海市";//不知道影不影响中奖,觉得影响自己改成自己的就行 //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || true; //并发数,默认3 let bfs = process.env["wqwl_bfs"] || 3; // 是否通知 let isNotify = true; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_mpcbh'; //脚本名称 const name = '微信小程序毛铺草本荟' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } class Task { constructor(ck) { this.index = index++; this.baseURL = 'https://mpb.jingjiu.com/proxy-he/api' this.ck = ck this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) //活动列表 this.activityConfig = { lab: { startUrl: '/BlzLonglActivity/caobenshiyanshiUserDrawGet', endUrl: '/BlzLonglActivity/caobenshiyanshiUserDraws', mainUrl: '/BlzLonglActivity/caobenshiyanshiUserMains', name: '实验室' }, herb: { startUrl: '/BlzLonglActivity/shicaoxunyuanUserDrawGet', endUrl: '/BlzLonglActivity/shicaoxunyuanUserDraws', mainUrl: '/BlzLonglActivity/shicaoxunyuanUserMains', name: '分药材' } // 添加新活动只需在这里新增配置即可 }; } async init(ck) { const ckData = ck.split('#') if (ckData.length < 1) { return this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 1) { this.remark = ckData[0].slice(0, 8); } else { this.remark = ckData[1]; } this.auth = ckData[0]; if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠不使用代理`) } } // 签到 async sign() { try { if (!(this.auth)) return '授权过期' const data = { date: this.getToday() } const headers = this.getAppSign(data, ['date']) const options = { url: `${this.baseURL}/FlanSignInDaily/adds`, headers: headers, method: 'POST', data: data } //console.log(options) const result = await this.request(options, 0) // console.log(JSON.stringify(result)) if (result.code !== 0) return this.sendMessage(result.message) if (result.data.point_today && result.data.point_tomorrow) return this.sendMessage(`✅签到成功,获得${result.data.point_today}积分,明天将获得${result.data.point_tomorrow}积分`, true) } catch (e) { throw new Error(`❌签到接口请求失败,${e.message}`) } } //谁是5冕之王 async wumianStart() { try { if (!(this.auth)) return; const data = { "activity_code": "", "city": city };//地区自己改吧 const headers = this.getAppSign(data, ['activity_code', 'city']); const options = { url: `${this.baseURL}/BlzLongcaobenActivity/wumianUserMains`, headers: headers, method: 'POST', data: data }; const result = await this.request(options, 0); // console.log(JSON.stringify(result)) if (result?.code !== 0) return this.sendMessage(`谁是5冕之王获取次数失败,原因:${result.message}`); if (result?.data?.today_play_num_can) { this.sendMessage(`谁是5冕之王剩余次数:${result?.data?.today_play_num_can}`); } if (result?.data?.today_play_num_can > 0 && result?.data?.activity?.activity_id) { this.sendMessage(`开始谁是5冕之王...`) const data2 = { "activity_id": result?.data?.activity?.activity_id }; const headers2 = this.getAppSign(data, ['activity_id']); const options2 = { url: `${this.baseURL}/BlzLongcaobenActivity/wumianUserMains`, headers: headers2, method: 'POST', data: data2 }; const result2 = await this.request(options2, 0); if (result2?.code !== 0) return this.sendMessage(`谁是5冕之王获取信息失败,原因:${result2.message}`); const data3 = { "activity_id": result?.data?.activity?.activity_id, 'play_time_start': Math.floor(Date.now() / 1000) }; const headers3 = this.getAppSign(data, ['activity_id', 'play_time_start']); const options3 = { url: `${this.baseURL}/BlzLongcaobenActivity/wumianUserDrawGet`, headers: headers3, method: 'POST', data: data3 }; const result3 = await this.request(options3, 0); if (result3?.code !== 0) return this.sendMessage(`谁是5冕之王开始失败,原因:${result3.message}`); await wqwlkj.sleep(wqwlkj.getRandom(30, 40)) if (result3?.data?.user_record_id) { this.sendMessage(`获取到游戏记录id:${result3?.data?.user_record_id}`) const data4 = { "user_record_id": result3?.data?.user_record_id, 'play_time_finish': Math.floor(Date.now() / 1000) }; const headers4 = this.getAppSign(data, ['user_record_id', 'play_time_finish']); const options4 = { url: `${this.baseURL}/BlzLongcaobenActivity/wumianUserDraws`, headers: headers4, method: 'POST', data: data4 }; const result4 = await this.request(options4, 0); if (result4?.code !== 0) return this.sendMessage(`谁是5冕之王结束失败,原因:${result4.message}`); this.sendMessage(`✅谁是5冕之王成功,获得${result4?.data?.award?.AwardName || result4?.data?.awardLocal?.title || '未识别'}`, true); } else { this.sendMessage(`❌谁是5冕之王user_record_id获取失败`) } } else { this.sendMessage(`❌谁是5冕之王activity_code获取失败`) } } catch (e) { throw new Error(`❌谁是5冕之王请求接口失败,${e.message}`); } } //周五专属 async memberdayStart() { if (!this.isAfterFriday8AM()) return this.sendMessage(`⚠️非周五8:00-22:00时间段,不执行`) try { if (!(this.auth)) return; const data = {}; const headers = this.getAppSign(data, []); const options = { url: `${this.baseURL}/BlzWeekActivity/memberdayUserMains`, headers: headers, method: 'POST', data: data }; const result = await this.request(options, 0); if (result.code !== 0) return this.sendMessage(result.message); if (result.data.is_draw) { this.sendMessage(`周五俱乐部剩余次数:${result.data.is_draw}`); } if (result.data.draw_ticket && result.data.is_draw > 0) { this.sendMessage(`开始周五俱乐部...`) await wqwlkj.sleep(wqwlkj.getRandom(10, 20)) const data = { draw_ticket: result.data.draw_ticket } const headers = this.getAppSign(data, ['draw_ticket']); const options = { url: `${this.baseURL}/BlzWeekActivity/memberdayUserDraws`, headers: headers, method: 'POST', data: data }; const result2 = await this.request(options, 0); if (result.code !== 0) return this.sendMessage(result.message) this.sendMessage(`✅周五俱乐部成功,获得${result2?.data?.AwardName || result2?.data?.awardLocal?.title || '未识别'}`, true); } else { this.sendMessage(`周五俱乐部获取ticket失败`) } } catch (e) { throw new Error(`❌周五俱乐部请求接口失败,${e.message}`); } } isAfterFriday8AM(date = new Date()) { if (date.getDay() !== 5) { return false; } const hours = date.getHours(); const minutes = date.getMinutes(); const totalMinutes = hours * 60 + minutes; // 8:00 = 480分钟, 22:00 = 1320分钟 return totalMinutes >= 480 && totalMinutes <= 1320; } // 通用次数查询函数 async commonUserMains(activityType) { try { if (!(this.auth)) return; if (!this.activityConfig[activityType]) { throw new Error(`未知的活动类型: ${activityType}`); } const data = {}; const headers = this.getAppSign(data, []); const options = { url: `${this.baseURL}${this.activityConfig[activityType].mainUrl}`, headers: headers, method: 'POST', data: data }; const result = await this.request(options, 0); if (result.code !== 0) return this.sendMessage(result.message); if (result.data.today_play_num_can) { this.sendMessage(`${this.activityConfig[activityType].name}剩余次数:${result.data.today_play_num_can}`); } return result.data.today_play_num_can; } catch (e) { throw new Error(`❌${this.activityConfig[activityType]?.name || activityType}次数请求接口失败,${e.message}`); } } // 通用开始函数 async commonDrawGet(activityType) { try { if (!(this.auth)) return; if (!this.activityConfig[activityType]) { throw new Error(`未知的活动类型: ${activityType}`); } const data = { "play_time_start": Math.round(Date.now() / 1000), "use_type": "free" }; const headers = this.getAppSign(data, ['play_time_start', 'use_type']); const options = { url: `${this.baseURL}${this.activityConfig[activityType].startUrl}`, headers: headers, method: 'POST', data: data }; const result = await this.request(options, 0); if (result.code !== 0) return this.sendMessage(result.message); if (result.data.user_record_id) return result.data.user_record_id; } catch (e) { throw new Error(`❌${this.activityConfig[activityType]?.name || activityType}请求接口失败,${e.message}`); } } // 通用结束函数 async commonDraws(activityType, userRecordId) { try { if (!(this.auth)) return; if (!this.activityConfig[activityType]) { throw new Error(`未知的活动类型: ${activityType}`); } const data = { "play_time_finish": Math.round(Date.now() / 1000), "user_record_id": userRecordId }; const headers = this.getAppSign(data, ['play_time_finish', 'user_record_id']); const options = { url: `${this.baseURL}${this.activityConfig[activityType].endUrl}`, headers: headers, method: 'POST', data: data }; const result = await this.request(options, 0); if (result.code !== 0) return this.sendMessage(result.message); this.sendMessage(`✅${this.activityConfig[activityType].name}成功,获得${result.data.title || result.data.awardLocal.title || '识别失败了'}`, true); } catch (e) { throw new Error(`❌请求${this.activityConfig[activityType]?.name || activityType}结束接口失败,${e.message}`); } } //观看视频 async taskViewVideoView() { try { if (!(this.auth)) return const data = { "video_id": "video-117" } const headers = this.getAppSign(data, []) const options = { url: `${this.baseURL}/BlzAppletIndex/taskViewVideoView`, headers: headers, method: 'POST', data: data } const result = await this.request(options, 0) //console.log(JSON.stringify(result)) if (result.code !== 0) return this.sendMessage(result.message) if (result.data.point === 0) return this.sendMessage('❌今日已观看过视频了') this.sendMessage(`✅观看视频成功,${result.data.task.description || '识别失败了'}`, true) //console.log(JSON.stringify(result)) } catch (e) { throw new Error(`❌请求观看视频接口失败,${e.message}`) } } //订阅消息 async taskSubscribeMessage() { try { if (!(this.auth)) return const data = { "tag": "subscribe_message_202410" } const headers = this.getAppSign(data, []) const options = { url: `${this.baseURL}/BlzAppletIndex/taskSubscribeMessage`, headers: headers, method: 'POST', data: data } const result = await this.request(options, 0) if (result.code !== 0) return this.sendMessage(result.message) if (result.data.point === 0) return this.sendMessage('❌今日已订阅过消息了') this.sendMessage(`✅订阅消息成功,${result.data.task.description || '识别失败了'}`, true) // } catch (e) { throw new Error(`❌请求订阅消息接口失败,${e.message}`) } } // 获取信息 async userInfo() { try { if (!(this.auth)) return const data = { } const headers = this.getAppSign(data, ['play_time_finish', 'user_record_id']) const options = { url: `${this.baseURL}/user?is_jifen_clear_data=1`, headers: headers, method: 'GET', } const result = await this.request(options, 0) if (result.code !== 0) return this.sendMessage(result.message) this.sendMessage(`用户【${result.data.name}】积分:${result.data.point}`, true) } catch (e) { throw new Error(`❌获取信息接口失败,${e.message}`) } } getAppSign(o, e) { if (!this.ua) this.ua = wqwlkj.generateRandomUA() var a = Math.round(Date.now() / 1000); var i = "DYSHJS^M&.YXZRGS"; var s = this.auth var c = ""; e.forEach(key => { if (o.hasOwnProperty(key)) { c += key + o[key].toString(); } }); c = a + c + i + s; //console.log(c) var r = { 'User-Agent': this.ua, "accept": "*/*", "accept-language": "zh-CN,zh;q=0.9", apptime: a, appsign: wqwlkj.md5(c, true).substr(-10), Authorization: s, "content-type": "application/json", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "x-version": "0.0.1", "xweb_xhr": "1", "Referer": "https://servicewechat.com/wxefd0fe341e06b815/508/page-frame.html", "Referrer-Policy": "unsafe-url" }; return r; } getToday() { const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零 const day = String(now.getDate()).padStart(2, '0'); // 日期补零 return `${year}-${month}-${day}`; } async main() { await this.init(this.ck) await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) this.sendMessage(`开始签到...`) const result = await this.sign() if (result == '' || result == null || result == undefined || result === '授权过期') return this.sendMessage('❌授权已过期或ck无效,请重新获取', true) await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.wumianStart() // 遍历所有配置的活动 for (const [activityType, config] of Object.entries(this.activityConfig)) { this.sendMessage(`开始${config.name}游戏...`); // 查询剩余次数 const times = await this.commonUserMains(activityType); if (times > 0) { // 开始活动 const recordId = await this.commonDrawGet(activityType); if (recordId) { // 随机等待时间 const delay = wqwlkj.getRandom(30, 40); await wqwlkj.sleep(delay); // 结束活动 await this.commonDraws(activityType, recordId); } } // 活动间间隔 await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } this.sendMessage(`开始观看视频`) await this.taskViewVideoView() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) this.sendMessage(`开始订阅消息..`) await this.taskSubscribeMessage() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.memberdayStart() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) this.sendMessage(`开始获取个人信息...`) await this.userInfo() } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); return data; } catch (error) { this.sendMessage(`🔐检测到请求发生错误,正在重试...`) let newProxy; if (isProxy) { newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); } else { this.sendMessage(`⚠️未使用代理`); newProxy = true } if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
298582245/wqwl_qinglong
11,821
wqwl_赚转鱼.js
/** * 脚本:wqwl_赚转鱼.js * 作者:wqwlkj 裙:960690899 * 描述:微信小程序赚转鱼 * 环境变量:wqwl_zzy,多个换行或新建多个变量 * 环境变量描述:抓包Headers下的user-token,格式例如:user-token#备注1 * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 0 2 * * * 一天一次 */ /** * ck好短,一个小时不到,不如手动,写了就发 */ const axios = require('axios'); const fs = require('fs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || true; //并发数,默认4 let bfs = process.env["wqwl_bfs"] || 4; // 是否通知 let isNotify = true; //账号索引 let index = 0; //ck环境变量名 const ckName = 'wqwl_zzy'; //脚本名称 const name = '微信小程序赚转鱼' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } // let fileData = wqwlkj.readFile('zzy') class Task { constructor(ck) { this.index = index++; this.ck = ck this.baseUrl = 'https://app.duoyukeji.net/api' this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) } async init() { const ckData = this.ck.split('#') if (ckData.length < 1) { return this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); } else if (ckData.length === 1) { this.remark = ckData[0].slice(0, 8); } else { this.remark = ckData[1]; } this.token = ckData[0]; this.headers = { "accept": "*/*", "accept-language": "zh-CN,zh;q=0.9", "appid": "wx9ab1b6f621909585", "channel": "weixin", "content-type": "application/json", "interface-version": "1.0", "provider": "retrieve", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "user-token": this.token, "xweb_xhr": "1", "Referer": "https://servicewechat.com/wx9ab1b6f621909585/198/page-frame.html", "Referrer-Policy": "unsafe-url" } if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } return true } async signIn() { try { const options = { url: `${this.baseUrl}/mine/gold/signIn`, headers: this.headers, method: 'GET' } const res = await this.request(options, this.proxy) if (res.msg === '签到成功') this.sendMessage(`✅签到成功`) else this.sendMessage(`❌签到失败,原因:${res.msg}`) } catch (e) { throw new Error(`❌签到请求失败,${e.message}`) } } async signIn() { try { const options = { url: `${this.baseUrl}/mine/gold/signIn`, headers: this.headers, method: 'GET' } const res = await this.request(options, this.proxy) if (res.msg === '签到成功') this.sendMessage(`✅签到成功`) else this.sendMessage(`❌签到失败,原因:${res.msg}`) } catch (e) { throw new Error(`❌签到请求失败,${e.message}`) } } async getTimes() { try { const options = { url: `${this.baseUrl}/mine/gold/mining/progress`, headers: this.headers, method: 'GET' } const res = await this.request(options, this.proxy) if (res.data.residueNumber === null) { this.sendMessage(`❌请手动领取旷工再运行`) return false } this.sendMessage(`✅已获取${res.data.residueNumber}次挖矿机会`) for (let i = 0; i < res.data.residueNumber; i++) { await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.residue() } } catch (e) { throw new Error(`❌获取次数请求失败,${e.message}`) } } async residue() { try { const options = { url: `${this.baseUrl}/open/activity/participation/activity?activityRuleId=3`, headers: this.headers, method: 'GET' } const res = await this.request(options, this.proxy) if (res.msg === '成功') { this.sendMessage(`✅挖矿成功,获得【${res.data.prizeName}】,准备兑换...`) await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.updatePrize(res.data.activityLogId) } else this.sendMessage(`❌挖矿失败,原因:${res.msg}`) } catch (e) { throw new Error(`❌挖矿请求失败,${e.message}`) } } async updatePrize(activityLogId) { try { const options = { url: `${this.baseUrl}/open/activity/updatePrize`, headers: this.headers, method: 'POST', data: JSON.stringify({ activityRuleId: 3, id: activityLogId }) } const res = await this.request(options, this.proxy) if (res.msg === '兑换成功') { this.sendMessage(`✅兑换成功,获得【${res.data}】元`) await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) } else this.sendMessage(`❌挖矿失败,原因:${res.msg}`) } catch (e) { throw new Error(`❌挖矿请求失败,${e.message}`) } } async userMessage() { try { const options = { url: `${this.baseUrl}/open/popularize/userMessage`, headers: this.headers, method: 'POST', data: JSON.stringify({ }) } const res = await this.request(options, this.proxy) if (res.data.id) { this.sendMessage(`✅用户【${res.data.name}】余额:${res.data.account}元`, true) } else this.sendMessage(`❌查询用户信息失败,原因:${res.msg}`) } catch (e) { throw new Error(`❌查询用户信息请求失败,${e.message}`) } } // async main() { const isFinish = await this.init() if (!isFinish) return await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.signIn() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.getTimes() await wqwlkj.sleep(wqwlkj.getRandom(3, 5)) await this.userMessage() } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); return data; } catch (error) { this.sendMessage(`🔐检测到请求发生错误,正在重试...`) // 刷新代理 const newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } // wqwlkj.saveFile(fileData, 'zzy') console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
2881099/FreeSql.AdminLTE
10,064
Examples/net80_blazor/Infrastructure/Swagger/ApiUIOptions.cs
using System; using System.IO; using System.Reflection; using System.Collections.Generic; using System.Linq; using System.Text.Json.Serialization; namespace FreeWeb.Infrastructure.Swagger { public class ApiUIOptions { /// <summary> /// Gets or sets a route prefix for accessing the swagger-ui /// </summary> public string RoutePrefix { get; set; } = "swagger"; /// <summary> /// Gets or sets a Stream function for retrieving the swagger-ui page /// </summary> public Func<Stream> IndexStream { get; set; } = () => typeof(ApiUIOptions).GetTypeInfo().Assembly .GetManifestResourceStream("ZhonTai.ApiUI.src.dist.index.html"); /// <summary> /// Gets or sets a title for the swagger-ui page /// </summary> public string DocumentTitle { get; set; } = "Api UI"; /// <summary> /// Gets or sets additional content to place in the head of the swagger-ui page /// </summary> public string HeadContent { get; set; } = ""; /// <summary> /// Gets the JavaScript config object, represented as JSON, that will be passed to the SwaggerUI /// </summary> public ConfigObject ConfigObject { get; set; } = new ConfigObject(); /// <summary> /// Gets the JavaScript config object, represented as JSON, that will be passed to the initOAuth method /// </summary> public OAuthConfigObject OAuthConfigObject { get; set; } = new OAuthConfigObject(); /// <summary> /// Gets the interceptor functions that define client-side request/response interceptors /// </summary> public InterceptorFunctions Interceptors { get; set; } = new InterceptorFunctions(); } public class ConfigObject { /// <summary> /// One or more Swagger JSON endpoints (url and name) to power the UI /// </summary> public IEnumerable<UrlDescriptor> Urls { get; set; } = null; /// <summary> /// If set to true, enables deep linking for tags and operations /// </summary> public bool DeepLinking { get; set; } = false; /// <summary> /// If set to true, it persists authorization data and it would not be lost on browser close/refresh /// </summary> public bool PersistAuthorization { get; set; } = false; /// <summary> /// Controls the display of operationId in operations list /// </summary> public bool DisplayOperationId { get; set; } = false; /// <summary> /// The default expansion depth for models (set to -1 completely hide the models) /// </summary> public int DefaultModelsExpandDepth { get; set; } = 1; /// <summary> /// The default expansion depth for the model on the model-example section /// </summary> public int DefaultModelExpandDepth { get; set; } = 1; /// <summary> /// Controls how the model is shown when the API is first rendered. /// (The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links) /// </summary> public ModelRendering DefaultModelRendering { get; set; } = ModelRendering.Example; /// <summary> /// Controls the display of the request duration (in milliseconds) for Try-It-Out requests /// </summary> public bool DisplayRequestDuration { get; set; } = false; /// <summary> /// Controls the default expansion setting for the operations and tags. /// It can be 'list' (expands only the tags), 'full' (expands the tags and operations) or 'none' (expands nothing) /// </summary> public DocExpansion DocExpansion { get; set; } = DocExpansion.List; /// <summary> /// If set, enables filtering. The top bar will show an edit box that you can use to filter the tagged operations /// that are shown. Can be an empty string or specific value, in which case filtering will be enabled using that /// value as the filter expression. Filtering is case sensitive matching the filter expression anywhere inside the tag /// </summary> public string Filter { get; set; } = null; /// <summary> /// If set, limits the number of tagged operations displayed to at most this many. The default is to show all operations /// </summary> public int? MaxDisplayedTags { get; set; } = null; /// <summary> /// Controls the display of vendor extension (x-) fields and values for Operations, Parameters, and Schema /// </summary> public bool ShowExtensions { get; set; } = false; /// <summary> /// Controls the display of extensions (pattern, maxLength, minLength, maximum, minimum) fields and values for Parameters /// </summary> public bool ShowCommonExtensions { get; set; } = false; /// <summary> /// OAuth redirect URL /// </summary> [JsonPropertyName("oauth2RedirectUrl")] public string OAuth2RedirectUrl { get; set; } = null; /// <summary> /// List of HTTP methods that have the Try it out feature enabled. /// An empty array disables Try it out for all operations. This does not filter the operations from the display /// </summary> public IEnumerable<SubmitMethod> SupportedSubmitMethods { get; set; } = Enum.GetValues(typeof(SubmitMethod)).Cast<SubmitMethod>(); /// <summary> /// Controls whether the "Try it out" section should be enabled by default. /// </summary> [JsonPropertyName("tryItOutEnabled")] public bool TryItOutEnabled { get; set; } /// <summary> /// By default, Swagger-UI attempts to validate specs against swagger.io's online validator. /// You can use this parameter to set a different validator URL, for example for locally deployed validators (Validator Badge). /// Setting it to null will disable validation /// </summary> public string ValidatorUrl { get; set; } = null; [JsonExtensionData] public Dictionary<string, object> AdditionalItems { get; set; } = new Dictionary<string, object>(); } public class UrlDescriptor { public string Url { get; set; } public string Name { get; set; } } public enum ModelRendering { Example, Model } public enum DocExpansion { List, Full, None } public enum SubmitMethod { Get, Put, Post, Delete, Options, Head, Patch, Trace } public class OAuthConfigObject { /// <summary> /// Default username for OAuth2 password flow. /// </summary> public string Username { get; set; } = null; /// <summary> /// Default clientId /// </summary> public string ClientId { get; set; } = null; /// <summary> /// Default clientSecret /// </summary> /// <remarks>Setting this exposes the client secrets in inline javascript in the swagger-ui generated html.</remarks> public string ClientSecret { get; set; } = null; /// <summary> /// Realm query parameter (for oauth1) added to authorizationUrl and tokenUrl /// </summary> public string Realm { get; set; } = null; /// <summary> /// Application name, displayed in authorization popup /// </summary> public string AppName { get; set; } = null; /// <summary> /// Scope separator for passing scopes, encoded before calling, default value is a space (encoded value %20) /// </summary> public string ScopeSeparator { get; set; } = " "; /// <summary> /// String array of initially selected oauth scopes, default is empty array /// </summary> public IEnumerable<string> Scopes { get; set; } = new string[] { }; /// <summary> /// Additional query parameters added to authorizationUrl and tokenUrl /// </summary> public Dictionary<string, string> AdditionalQueryStringParams { get; set; } = null; /// <summary> /// Only activated for the accessCode flow. During the authorization_code request to the tokenUrl, /// pass the Client Password using the HTTP Basic Authentication scheme /// (Authorization header with Basic base64encode(client_id + client_secret)) /// </summary> public bool UseBasicAuthenticationWithAccessCodeGrant { get; set; } = false; /// <summary> /// Only applies to authorizatonCode flows. Proof Key for Code Exchange brings enhanced security for OAuth public clients. /// The default is false /// </summary> public bool UsePkceWithAuthorizationCodeGrant { get; set; } = false; } public class InterceptorFunctions { /// <summary> /// MUST be a valid Javascript function. /// Function to intercept remote definition, "Try it out", and OAuth 2.0 requests. /// Accepts one argument requestInterceptor(request) and must return the modified request, or a Promise that resolves to the modified request. /// Ex: "function (req) { req.headers['MyCustomHeader'] = 'CustomValue'; return req; }" /// </summary> public string RequestInterceptorFunction { get; set; } /// <summary> /// MUST be a valid Javascript function. /// Function to intercept remote definition, "Try it out", and OAuth 2.0 responses. /// Accepts one argument responseInterceptor(response) and must return the modified response, or a Promise that resolves to the modified response. /// Ex: "function (res) { console.log(res); return res; }" /// </summary> public string ResponseInterceptorFunction { get; set; } } }
298582245/wqwl_qinglong
14,587
wqwl_银鱼(通用版).js
/** * 脚本:wqwl_银鱼(通用版).js * 作者:wqwlkj 裙:960690899 * 描述:小程序:银鱼质亨,不一定,搜索 银愉 关键字,橙色图标应该就是了 * 环境变量:wqwl_yinyu,多个换行或新建多个变量 * 环境变量描述:抓包headers下的Authori-zation和Form-type,格式auth1#type1#备注1 * 代理变量:wqwl_daili(获取代理链接,需要返回txt格式的http/https) * cron: 一天一次 */ //本代码是基于网上的代码使用AI进行修改 //外面的脚本提现失败就是他的Form-type跟你的不同,换成自己的就好了 const axios = require('axios'); const fs = require('fs'); //代理链接 let proxy = process.env["wqwl_daili"] || ''; //是否用代理,默认使用(填了代理链接) let isProxy = process.env["wqwl_useProxy"] || false; //并发数,默认4 let bfs = process.env["wqwl_bfs"] || 4; // 是否通知 let isNotify = true; //账号索引 let index = 0; //开启则打印每一次请求的返回结果 let isDebug = false; //ck环境变量名 const ckName = 'wqwl_yinyu'; //脚本名称 const name = '微信小程序银鱼质亨' !(async function () { let wqwlkj; const filePath = 'wqwl_require.js'; const url = 'https://raw.githubusercontent.com/298582245/wqwl_qinglong/refs/heads/main/wqwl_require.js'; if (fs.existsSync(filePath)) { console.log('✅wqwl_require.js已存在,无需重新下载,如有报错请重新下载覆盖\n'); wqwlkj = require('./wqwl_require'); } else { console.log('正在下载wqwl_require.js,请稍等...\n'); console.log(`如果下载过慢,可以手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本`) console.log('地址:' + url); try { const res = await axios.get(url); fs.writeFileSync(filePath, res.data); console.log('✅下载完成,准备开始运行脚本\n'); wqwlkj = require('./wqwl_require'); } catch (e) { console.log('❌下载失败,请手动下载wqwl_require.js,并保存为wqwl_require.js,并重新运行脚本\n'); console.log('地址:' + url); return; // 下载失败,不再继续执行 } } // 确保 require 成功后才继续执行 try { wqwlkj.disclaimer(); if (typeof wqwlkj.findTypes == "function") { let type = await wqwlkj.findTypes(name); console.log(`============================ 🚀 当前脚本:${name} 🚀 📂 所属分类:${type} 📂 ============================\n`) } let notify; if (isNotify) { try { notify = require('./sendNotify'); console.log('✅加载发送通知模块成功'); } catch (e) { console.log('❌加载发送通知模块失败'); notify = null } } //let fileData = wqwlkj.readFile('yinyu') class Task { constructor(ck) { this.index = index++; this.ck = ck this.baseUrl = 'https://n03.sentezhenxuan.com/api' this.maxRetries = 3; // 最大重试次数 this.retryDelay = 3; // 重试延迟(秒) } async init() { const ckData = this.ck.split('#') if (ckData.length < 2) { this.sendMessage(`${index + 1} 环境变量有误,请检查环境变量是否正确`, true); return false; } else if (ckData.length === 2) { this.remark = `${ckData[0].slice(0, 8)}-${this.index}`; } else { this.remark = ckData[2]; } this.auth = ckData[0]; this.type = ckData[1]; if (!/^[A-Za-z-]+$/.test(this.type)) { this.sendMessage(`⚠️没传正确的Form-type,使用默认值:routine-tuangou(提现失败请手动替换)`) this.type = 'routine-tuangou'; } if (!this.auth.includes('Bearer')) this.auth = `Bearer ${this.auth}` const jwtData = this.parseJWT(this.auth) // console.log(jwtData) if (jwtData?.payload?.iss) this.baseUrl = `https://${jwtData?.payload?.iss}/api` else if (jwtData?.payload?.aud) thies.baseUrl = `https://${jwtData?.payload?.aud}/api` else this.sendMessage(`⚠️使用ck获取host,使用默认host:n03.sentezhenxuan.com`) //console.log(this.baseUrl) //'https://n03.sentezhenxuan.com/api' this.headers = { "Accept": "application/json", "Accept-Encoding": "gzip, deflate, br", "Content-Type": "application/json", "Connection": "keep-alive", "Referer": "https://servicewechat.com/wx5b82dfe3747e533f/5/page-frame.html", "Host": "n03.sentezhenxuan.com", "Authori-zation": this.auth, "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.50 NetType/WIFI Language/zh_CN", "Cb-lang": "zh-CN", "Form-type": this.type, "xweb_xhr": "1" }; if (proxy && isProxy) { this.proxy = await wqwlkj.getProxy(this.index, proxy) //console.log(`使用代理:${this.proxy}`) this.sendMessage(`✅使用代理:${this.proxy}`) } else { this.proxy = '' this.sendMessage(`⚠️不使用代理`) } return true } async getVideoIds() { try { const options = { url: `${this.baseUrl}/video/list?page=1&limit=10&status=1&source=0&isXn=1`, headers: this.headers, method: 'GET', } let res = await this.request(options); // console.log(res) //console.log(typeof res) // res = this.JSONpare(res) if (!res || !res.status == 200 || !Array.isArray(res.data)) { this.sendMessage(`❌获取视频列表失败:, ${res?.msg || '未知错误'} `, true); this.videoIds = []; return false; } else { this.videoIds = res.data.map(item => item.id).filter(id => typeof id === 'number'); } return true; } catch (e) { this.sendMessage(`❌获取视频id请求失败,${e.message}`) this.videoIds = []; return false; } } async watchVideos() { if (this.videoIds.length <= 0) return this.sendMessage(`⚠️ 无视频可刷,跳过此步骤`) try { const total = this.videoIds.length; // console.log(this.videoIds) let i = 0 for (; i < total; i++) { const options = { url: `${this.baseUrl}/video/videoJob`, headers: this.headers, method: 'POST', data: JSON.stringify( { vid: this.videoIds[i], startTime: Date.now() - 80000, endTime: Date.now(), baseVersion: "3.8.9", playMode: 0, } ) } let res = await this.request(options); //res = this.JSONpare(res) if (res || res.status == 200) { this.sendMessage(`🎥视频 ${i + 1}/${total} 刷完 (ID: ${this.videoIds[i]})`); } else { this.sendMessage(`⚠️视频 ${i + 1}/${total} 异常:`, data?.msg || '无数据') } await wqwlkj.sleep(wqwlkj.getRandom(1, 3)) } return true; } catch (e) { this.sendMessage(`❌视频观看失败:,${e.message || e}`) return false; } } async doWithdraw() { try { const header = JSON.parse(JSON.stringify(this.headers)) header['Accept-Language'] = "zh-CN,zh;q=0.9"; header['User-Agent'] = "Mozilla/5.0 (iPhone; CPU iPhone OS 15_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.50(0x1800323d) NetType/WIFI Language/zh_CN" const options = { url: `${this.baseUrl}/userTx`, headers: header, method: 'GET', } let res = await this.request(options); //res = this.JSONpare(res) if (res.code === 200 || res.status === 200) { this.sendMessage(`💰 提现成功:, ${res.msg || '成功'} `, true); } else { this.sendMessage(`❌提现失败,${res.msg}`, true) } } catch (e) { this.sendMessage(`❌提现请求失败:,${e.message || e}`) return false; } } async main() { const init = await this.init() if (!init) return; this.sendMessage(`🔍 正在获取视频列表...`) const getId = await this.getVideoIds() if (!getId) return; this.sendMessage(`📽️ 获取到 ${this.videoIds.length} 个视频ID,准备刷视频...`) const watchVideo = await this.watchVideos() if (!watchVideo) return; this.sendMessage(`💳 正在尝试提现...`) await this.doWithdraw() } // 手动解析 JWT(Base64 解码) parseJWT(token) { try { const cleanToken = token.replace('Bearer ', ''); // JWT 由三部分组成:header.payload.signature const parts = cleanToken.split('.'); if (parts.length !== 3) { throw new Error('无效的 JWT 格式'); } // Base64Url 解码 const header = JSON.parse(Buffer.from(parts[0], 'base64').toString()); const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString()); return { header, payload, signature: parts[2] }; } catch (error) { console.error('JWT 解析失败:', error.message); return null; } } // 带重试机制的请求方法 async request(options, retryCount = 0) { try { const data = await wqwlkj.request(options, this.proxy); if (isDebug) { if (isDebug === 2) console.log(JSON.stringify(options)) const formatData = (data) => { if (data === null) return 'null'; if (data === undefined) return 'undefined'; if (typeof data === 'string') return data; if (typeof data === 'object') { try { return JSON.stringify(data, null, 2); // 美化输出 } catch (error) { return `[对象序列化失败: ${error.message}]`; } } return String(data); }; this.sendMessage(`[调试输出] ${options?.method}请求${options?.url}返回:${formatData(data)}`); } return data; } catch (error) { this.sendMessage(`🔐检测到请求发生错误,正在重试...`) let newProxy; if (isProxy) { newProxy = await wqwlkj.getProxy(this.index, proxy); this.proxy = newProxy this.sendMessage(`✅代理更新成功:${this.proxy}`); } else { this.sendMessage(`⚠️未使用代理`); newProxy = true } if (retryCount < this.maxRetries && newProxy) { this.sendMessage(`🕒${this.retryDelay * (retryCount + 1)}s秒后重试...`); await wqwlkj.sleep(this.retryDelay * (retryCount + 1)); return await this.request(options, retryCount + 1); } throw new Error(`❌请求最终失败: ${error.message}`); } } sendMessage(message, isPush = false) { message = `账号[${this.index + 1}](${this.remark}): ${message}` if (isNotify && isPush) { return wqwlkj.sendMessage(message + "\n") } console.log(message) return message } } console.log(`${name}开始执行...`); const tokens = wqwlkj.checkEnv(process.env[ckName]); //console.log(`共${tokens.length}个账号`); const totalBatches = Math.ceil(tokens.length / bfs); for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { const start = batchIndex * bfs; const end = start + bfs; const batch = tokens.slice(start, end); console.log(`开始执行第 ${batchIndex + 1} 批任务 (${start + 1}-${Math.min(end, tokens.length)})`); const taskInstances = batch.map(token => new Task(token)); const tasks = taskInstances.map(instance => instance.main()); const results = await Promise.allSettled(tasks); results.forEach((result, index) => { const task = taskInstances[index]; if (result.status === 'rejected') { task.sendMessage(result.reason); } }); await wqwlkj.sleep(wqwlkj.getRandom(3, 5)); } // wqwlkj.saveFile(fileData, 'yinyu') console.log(`${name}全部任务已完成!`); const message = wqwlkj.getMessage() if (message !== '' && isNotify === true) { await notify.sendNotify(`${name} `, `${message} `); } } catch (e) { console.error('❌ 执行过程中发生异常:', e.message); } })();
281677160/openwrt-package
6,555
luci-app-passwall2/luasrc/view/passwall2/global/backup.htm
<% local api = require "luci.passwall2.api" -%> <div class="cbi-section"> <h3><%:Backup and Restore%></h3> <div class="cbi-section-descr"> <%:Backup or Restore Client and Server Configurations.%> <br> <font color="red"><%:Note: Restoring configurations across different versions may cause compatibility issues.%></font> </div> </div> <div class="cbi-value" id="_backup_div"> <label class="cbi-value-title"><%:Create Backup File%></label> <div class="cbi-value-field"> <input class="btn cbi-button cbi-button-save" type="button" onclick="dl_backup()" value="<%:DL Backup%>" /> </div> </div> <div class="cbi-value" id="_upload_div"> <label class="cbi-value-title"><%:Restore Backup File%></label> <div class="cbi-value-field"> <input class="btn cbi-button cbi-button-apply" type="button" onclick="show_upload_win()" value="<%:RST Backup%>" /> </div> </div> <div class="cbi-value" id="_reset_div"> <label class="cbi-value-title"><%:Restore to default configuration%></label> <div class="cbi-value-field"> <input class="btn cbi-button cbi-button-reset" type="button" onclick="do_reset()" value="<%:Do Reset%>" /> </div> </div> <div class="cbi-value"></div> <div id="upload-modal" class="up-modal" style="display:none;"> <div class="up-modal-content"> <h3><%:Restore Backup File%></h3> <div class="up-cbi-value-field"> <input class="cbi-input-file" type="file" id="ulfile" accept=".tar.gz" /> </div> <div class="up-button-container"> <input class="btn cbi-button cbi-button-apply" type="button" id="upload-btn" onclick="do_upload()" value="<%:UL Restore%>" /> <input class="btn cbi-button cbi-button-remove" type="button" onclick="close_upload_win()" value="<%:CLOSE WIN%>" /> </div> </div> </div> <style> .up-modal { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 2px solid #ccc; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.5); z-index: 1000; width: 90%; max-width: 400px; } .up-modal-content { width: 100%; max-width: 400px; text-align: center; display: flex; flex-direction: column; justify-content: center; align-items: center; } .up-button-container { display: flex; justify-content: space-between; width: 100%; max-width: 250px; } .up-cbi-value-field { display: flex; flex-direction: column; align-items: center; width: 100%; margin-top: 15px; margin-bottom: 30px; } </style> <script> function show_upload_win(btn) { document.getElementById("upload-modal").style.display = "block"; } function close_upload_win(btn) { document.getElementById("ulfile").value = ""; document.getElementById("upload-modal").style.display = "none"; } function dl_backup(btn) { fetch('<%= api.url("create_backup") %>', { method: 'POST' }) .then(response => { if (!response.ok) { throw new Error("备份失败!"); } const filename = response.headers.get("X-Backup-Filename"); if (!filename) { return; } return response.blob().then(blob => ({ blob, filename })); }) .then(result => { if (!result) return; const { blob, filename } = result; const url = window.URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); window.URL.revokeObjectURL(url); }) .catch(error => alert(error.message)); } function do_reset(btn) { if (confirm("<%: Do you want to restore the client to default settings?%>")) { setTimeout(function () { if (confirm("<%: Are you sure you want to restore the client to default settings?%>")) { var xhr1 = new XMLHttpRequest(); xhr1.open("GET",'<%= api.url("clear_log") %>', true); xhr1.send(); var xhr2 = new XMLHttpRequest(); xhr2.open("GET",'<%= api.url("reset_config") %>', true); xhr2.send(); window.location.href = '<%= api.url("log") %>' } }, 1000); } } function do_upload(btn) { const fileInput = document.getElementById("ulfile"); const file = fileInput.files[0]; if (!file) { alert("<%:Please select a file first.%>"); return; } if (!file.name.endsWith(".tar.gz")) { alert("<%:Invalid file type. Please upload a .tar.gz file.%>"); fileInput.value = ""; return; } const maxSize = 10 * 1024 * 1024; // 10MB if (file.size > maxSize) { alert("<%:File size exceeds 10MB limit.%>"); fileInput.value = ""; return; } const reader = new FileReader(); reader.onload = function (e) { const binaryString = e.target.result; // ArrayBuffer const binary = new Uint8Array(binaryString); let binaryText = ""; for (let i = 0; i < binary.length; i++) { binaryText += String.fromCharCode(binary[i]); } const base64Data = btoa(binaryText); const targetByteSize = 64 * 1024; // 分片大小 64KB let chunkSize = Math.floor(targetByteSize * 4 / 3); chunkSize = chunkSize + (4 - (chunkSize % 4)) % 4; const totalChunks = Math.ceil(base64Data.length / chunkSize); let currentChunk = 0; function sendNextChunk() { if (currentChunk < totalChunks) { const chunk = base64Data.substring(currentChunk * chunkSize, (currentChunk + 1) * chunkSize); const xhr = new XMLHttpRequest(); xhr.open("POST", '<%= api.url("restore_backup") %>', true); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { const resp = JSON.parse(xhr.responseText); if (resp.status === "success") { currentChunk++; document.getElementById("upload-btn").value = "Uploading... " + Math.floor((currentChunk / totalChunks) * 100) + "%"; sendNextChunk(); } else { alert("Upload error: " + resp.message); document.getElementById("upload-btn").value = "<%:UL Restore%>"; } } else { alert("Upload failed with status " + xhr.status); document.getElementById("upload-btn").value = "<%:UL Restore%>"; } } }; const formData = new FormData(); formData.append("filename", file.name); formData.append("chunk", chunk); formData.append("chunk_index", currentChunk); formData.append("total_chunks", totalChunks); xhr.send(formData); } else { //alert("Upload completed."); document.getElementById("upload-btn").value = "<%:UL Restore%>"; window.location.href = '<%= api.url("log") %>' } } sendNextChunk(); }; reader.readAsArrayBuffer(file); } </script>
294coder/Efficient-MIF
1,345
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/showImage8.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Visualize and print an eight-band multispectral image. % % Interface: % showImage8(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L) % % Inputs: % I_MS: Eight band multispectral image; % print: Flag. If print == 1, print EPS image; % id: Identifier (name) of the printed EPS image; % flag_cut_bounds: Cut the boundaries of the viewed Panchromatic image; % dim_cut: Define the dimension of the boundary cut; % th_values: Flag. If th_values == 1, apply an hard threshold to the dynamic range; % L: Radiomatric resolution of the input image. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showImage8(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L) if flag_cut_bounds I_MS = I_MS(dim_cut:end-dim_cut,dim_cut:end-dim_cut,:); end if th_values I_MS(I_MS > 2^L) = 2^L; I_MS(I_MS < 0) = 0; end if id == 1 IMN = viewimage(I_MS(:,:,[1,3,5])); IMN = IMN(:,:,3:-1:1); else IMN = viewimage(I_MS(:,:,[1,3,5]),[0.01 0.995]); IMN = IMN(:,:,3:-1:1); end if print printImage(IMN,sprintf('Outputs/%d.eps',id)); end end
294coder/Efficient-MIF
1,625
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/LPfilterPlusDec.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % LPfilterPlusDec filters and decimates the image I_PAN using a Starck and Murtagh (S&M) filter. % % Interface: % I_PAN_LR = LPfilterPlusDec(I_PAN,ratio) % % Inputs: % I_PAN: Image to be filtered and decimated; % ratio: Scale ratio between MS and PAN. Pre-condition: Resize factors power of 2. % % Outputs: % I_PAN_LR: Filtered and decimated image. % % References: % [Starck07] J.-L. Starck, J. Fadili, and F. Murtagh, The undecimated wavelet decomposition and its reconstruction, IEEE Transactions on Image % Processing, vol. 16, no. 2, pp. 297309, February 2007. % [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms, % IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_PAN_LR = LPfilterPlusDec(I_PAN,ratio) h=[1 4 6 4 1 ]/16; g=[0 0 1 0 0 ]-h; htilde=[ 1 4 6 4 1]/16; gtilde=[ 0 0 1 0 0 ]+htilde; h=sqrt(2)*h; g=sqrt(2)*g; htilde=sqrt(2)*htilde; gtilde=sqrt(2)*gtilde; WF={h,g,htilde,gtilde}; Levels = ceil(log2(ratio)); WT = ndwt2_working(I_PAN,Levels,WF); for ii = 2 : numel(WT.dec), WT.dec{ii} = zeros(size(WT.dec{ii})); end I_PAN_LR = indwt2_working(WT,'c'); I_PAN_LR = imresize(I_PAN_LR,1/ratio,'nearest'); end
294coder/Efficient-MIF
1,746
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/showImage4_zoomin.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Visualize and print a four-band multispectral image. % % Interface: % showImage4(I_F,print,id,flag_cut_bounds,dim_cut,thvalues,L) % % Inputs: % I_MS: Four band multispectral image; % print: Flag. If print == 1, print EPS image; % id: Identifier (name) of the printed EPS image; % flag_cut_bounds: Cut the boundaries of the viewed Panchromatic image; % dim_cut: Define the dimension of the boundary cut; % th_values: Flag. If th_values == 1, apply an hard threshold to the dynamic range; % L: Radiomatric resolution of the input image. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showImage4_zoomin(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L,ratio, location1, location2) if flag_cut_bounds I_MS = I_MS(dim_cut:end-dim_cut,dim_cut:end-dim_cut,:); end if th_values I_MS(I_MS > 2^L) = 2^L; I_MS(I_MS < 0) = 0; end IMN = viewimage(I_MS(:,:,1:3)); IMN = IMN(:,:,3:-1:1); if isempty(location2) ent=rectangleonimage(IMN,location1,1, 3, 3, 3, 1); % put close-up to up-right corner figure,imshow(ent,[]) else % type =1 (put to down-left); type =2 (put to down-right); % type =3 (put to up-right); type =4 (put to up-left); ent=rectangleonimage(IMN,location1,1, 3, 3, 3, 1); % put close-up to up-right corner ent=rectangleonimage(ent,location2,1, 3, 2, 3, 2); % put close-up to down-right corner figure,imshow(ent,[]) end if print printImage(IMN,sprintf('Outputs/%d.eps',id)); end end
2977094657/BiliHistoryFrontend
7,398
src/components/tailwind/analytics/pages/RewatchPage.vue
<!-- 最爱重温页组件 --> <template> <div class="absolute inset-0"> <div class="h-full flex items-center justify-center"> <div class="max-w-7xl w-full mx-auto px-2 py-6 overflow-y-auto"> <div class="space-y-4"> <h3 class="text-3xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 最爱重温的视频 </h3> <div v-if="viewingData?.insights?.most_watched_videos" class="text-sm text-center text-gray-600 dark:text-gray-300 mb-2 px-4" v-html="formatInsightText(viewingData.insights.most_watched_videos)" > </div> <!-- 没有重复观看数据的提示 --> <div v-if="!viewingData?.watch_counts?.most_watched_videos?.length" class="mt-8 text-center py-10 bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-lg border border-gray-300/50 dark:border-gray-500/50"> <svg class="w-16 h-16 mx-auto text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1115 0z" /> </svg> <p class="mt-4 text-lg font-medium text-gray-700 dark:text-gray-300">暂无重复观看记录</p> <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">你在这一年中很少重复观看相同的视频</p> <p class="mt-1 text-sm text-gray-500">每次都在探索新内容的你,真是充满好奇心呢!</p> </div> <!-- 第一名 --> <div v-else-if="viewingData.watch_counts.most_watched_videos[0]" class="bg-gradient-to-br from-white/50 via-[#fb7299]/10 to-[#fc9b7a]/20 dark:from-white/5 dark:via-[#fb7299]/20 dark:to-[#fc9b7a]/30 backdrop-blur-sm rounded-lg p-3 transform hover:scale-[1.01] transition-transform cursor-pointer video-item relative overflow-hidden border border-gray-300/50 dark:border-gray-500/50" @click="handleVideoClick(viewingData.watch_counts.most_watched_videos[0].bvid)" > <div class="flex items-start space-x-4"> <div class="flex-1 min-w-0"> <div class="text-sm font-medium text-gray-800 dark:text-white hover:text-[#fb7299] transition-colors line-clamp-2"> {{ viewingData.watch_counts.most_watched_videos[0].title }} </div> <div class="mt-1.5 text-xs text-gray-600 dark:text-gray-400 flex items-center space-x-4"> <span>UP主:{{ viewingData.watch_counts.most_watched_videos[0].author_name }}</span> <span>观看 {{ viewingData.watch_counts.most_watched_videos[0].watch_count }} 次</span> <span>{{ viewingData.watch_counts.most_watched_videos[0].tag_name }}</span> </div> </div> <div class="flex flex-col items-center justify-center bg-white/30 dark:bg-white/10 backdrop-blur-sm rounded-lg px-2 py-1.5 border border-gray-300/50 dark:border-gray-500/50"> <div class="text-lg font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent rewatch-interval whitespace-nowrap"> {{ Math.round(viewingData.watch_counts.most_watched_videos[0].avg_interval / 3600 / 24) }} </div> <div class="text-[10px] text-gray-500 whitespace-nowrap">天/次</div> </div> </div> </div> <!-- 其余视频 --> <div v-if="viewingData.watch_counts.most_watched_videos?.length > 1" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3"> <div v-for="(video, index) in viewingData.watch_counts.most_watched_videos.slice(1)" :key="video.bvid" class="backdrop-blur-sm rounded-lg p-2.5 transform hover:scale-[1.02] transition-transform cursor-pointer video-item relative overflow-hidden border border-gray-300/50 dark:border-gray-500/50" :class="{ 'bg-gradient-to-br from-white/50 via-[#fc9b7a]/10 to-[#fcd07a]/20 dark:from-white/5 dark:via-[#fc9b7a]/20 dark:to-[#fcd07a]/30': index === 0, 'bg-gradient-to-br from-white/50 via-[#fcd07a]/10 to-[#fce07a]/20 dark:from-white/5 dark:via-[#fcd07a]/20 dark:to-[#fce07a]/30': index === 1, 'bg-white/50 dark:bg-white/5': index > 1 }" @click="handleVideoClick(video.bvid)" > <div class="flex items-start space-x-3"> <div class="flex-1 min-w-0"> <div class="text-xs font-medium text-gray-800 dark:text-white hover:text-[#fb7299] transition-colors line-clamp-2"> {{ video.title }} </div> <div class="mt-1 text-[10px] text-gray-600 dark:text-gray-400 flex items-center justify-between"> <span>UP主:{{ video.author_name }}</span> <span>{{ video.watch_count }}次</span> </div> <div class="text-[10px] text-gray-500">{{ video.tag_name }}</div> </div> <div class="flex flex-col items-center justify-center bg-white/30 dark:bg-white/10 backdrop-blur-sm rounded-lg px-2 py-1 ml-1 border border-gray-300/50 dark:border-gray-500/50"> <div class="text-sm font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent rewatch-interval whitespace-nowrap"> {{ Math.round(video.avg_interval / 3600 / 24) }} </div> <div class="text-[10px] text-gray-500 whitespace-nowrap">天/次</div> </div> </div> </div> </div> </div> </div> </div> </div> </template> <script setup> import { onMounted, nextTick, watch, ref } from 'vue' import gsap from 'gsap' import { openInBrowser } from '@/utils/openUrl.js' const props = defineProps({ viewingData: { type: Object, required: true } }) // 用于存储当前视频列表的引用 const videoList = ref([]) const handleVideoClick = async (bvid) => { await openInBrowser(`https://www.bilibili.com/video/${bvid}`) } // 初始化动画 const initAnimation = () => { nextTick(() => { if (props.viewingData?.watch_counts?.most_watched_videos?.length > 0) { const videoItems = document.querySelectorAll('.video-item') if (videoItems.length > 0) { gsap.from(videoItems, { opacity: 0, y: 20, duration: 0.5, stagger: 0.1, ease: 'power2.out', delay: 0.2 }) } } }) } // 监听数据变化 watch(() => props.viewingData?.watch_counts?.most_watched_videos, (newVal) => { // 先清空现有数据 videoList.value = [] // 在下一个 tick 中更新数据 nextTick(() => { if (newVal) { videoList.value = newVal initAnimation() } }) }, { deep: true }) onMounted(() => { videoList.value = props.viewingData?.watch_counts?.most_watched_videos || [] initAnimation() }) // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } </script> <style scoped> .line-clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } </style>
281677160/openwrt-package
5,038
luci-app-passwall2/luasrc/view/passwall2/global/footer.htm
<% local api = require "luci.passwall2.api" -%> <script type="text/javascript"> //<![CDATA[ function go() { var _status = document.getElementsByClassName('_status'); for (var i = 0; i < _status.length; i++) { var id = _status[i].getAttribute("socks_id"); XHR.get('<%=api.url("socks_status")%>', { index: i, id: id }, function(x, result) { var index = result.index; var div = ''; var div1 = '<font style="font-weight:bold;" color="green">✓</font>&nbsp'; var div2 = '<font style="font-weight:bold;" color="red">X</font>&nbsp'; if (result.socks_status) { div += div1; } else { div += div2; } if (result.use_http) { if (result.http_status) { div += div1; } else { div += div2; } } _status[index].innerHTML = div; } ); } var global_id = null; var global = document.getElementById("cbi-passwall2-global"); if (global) { var node = global.getElementsByClassName("cbi-section-node")[0]; var node_id = node.getAttribute("id"); global_id = node_id; var reg1 = new RegExp("(?<=" + node_id + "-).*?(?=(node))") for (var i = 0; i < node.childNodes.length; i++) { if (node.childNodes[i].childNodes && node.childNodes[i].childNodes.length > 0) { for (var k = 0; k < node.childNodes[i].childNodes.length; k++) { try { var dom = node.childNodes[i].childNodes[k]; if (dom.id) { var s = dom.id.match(reg1); if (s) { var cbi_id = global_id + "-" var dom_id = dom.id.split(cbi_id).join(cbi_id.split("-").join(".")).split("cbi.").join("cbid.") var node_select = document.getElementsByName(dom_id)[0]; var node_select_value = node_select.value; if (node_select_value && node_select_value != "" && node_select_value.indexOf("_default") != 0 && node_select_value.indexOf("_direct") != 0 && node_select_value.indexOf("_blackhole") != 0) { if (node_select.tagName == "INPUT") { node_select = document.getElementById("cbi.combobox." + dom_id); } if (true) { var to_url = "<%=api.url("node_config")%>/" + node_select_value; if (node_select_value.indexOf("Socks_") == 0) { to_url = "<%=api.url("socks_config")%>/" + node_select_value.substring("Socks_".length); } var new_a = document.createElement("a"); new_a.innerHTML = "<%:Edit%>"; new_a.href = "#"; new_a.setAttribute("onclick", "location.href='" + to_url + "'"); var new_html = new_a.outerHTML; } if (s[0] == "") { var log_a = document.createElement("a"); log_a.innerHTML = "<%:Log%>"; log_a.href = "#"; log_a.setAttribute("onclick", "window.open('" + '<%=api.url("get_redir_log")%>' + "?id=default&name=global" + "', '_blank')"); new_html += "&nbsp&nbsp" + log_a.outerHTML; } node_select.insertAdjacentHTML("afterend", "&nbsp&nbsp" + new_html); } } } } catch(err) { } } } } } var socks = document.getElementById("cbi-passwall2-socks"); if (socks) { var socks_enabled_dom = document.getElementById(global_id + "-socks_enabled"); socks_enabled_dom.parentNode.removeChild(socks_enabled_dom); var descr = socks.getElementsByClassName("cbi-section-descr")[0]; descr.outerHTML = socks_enabled_dom.outerHTML; rows = socks.getElementsByClassName("cbi-section-table-row"); for (var i = 0; i < rows.length; i++) { try { var row = rows[i]; var id = row.id; if (!id) continue; var dom_id = id + "-node"; var node = document.getElementById(dom_id); var dom_id = dom_id.replace("cbi-", "cbid-").replace(new RegExp("-", 'g'), "."); var node_select = document.getElementsByName(dom_id)[0]; var node_select_value = node_select.value; if (node_select_value && node_select_value != "") { var v = document.getElementById(dom_id + "-" + node_select_value); if (v) { node_select.title = v.text; } else { node_select.title = node_select.options[node_select.options.selectedIndex].text; } var new_html = "" var new_a = document.createElement("a"); new_a.innerHTML = "<%:Edit%>"; new_a.href = "#"; new_a.setAttribute("onclick","location.href='" + '<%=api.url("node_config")%>' + "/" + node_select_value + "'"); new_html = new_a.outerHTML; var log_a = document.createElement("a"); log_a.innerHTML = "<%:Log%>"; log_a.href = "#"; log_a.setAttribute("onclick", "window.open('" + '<%=api.url("get_socks_log")%>' + "?name=" + id.replace("cbi-passwall2-", "") + "', '_blank')"); new_html += "&nbsp" + log_a.outerHTML; node_select.insertAdjacentHTML("afterend", "&nbsp&nbsp" + new_html); } } catch(err) { } } } } setTimeout("go()", 1000); //]]> </script>
2881099/FreeSql.AdminLTE
13,980
Examples/net80_blazor/Infrastructure/Swagger/ApiUIOptionsExtensions.cs
using System; using System.Text; using System.Linq; using System.Collections.Generic; namespace FreeWeb.Infrastructure.Swagger { public static class ApiUIOptionsExtensions { /// <summary> /// Injects additional CSS stylesheets into the index.html page /// </summary> /// <param name="options"></param> /// <param name="path">A path to the stylesheet - i.e. the link "href" attribute</param> /// <param name="media">The target media - i.e. the link "media" attribute</param> public static void InjectStylesheet(this ApiUIOptions options, string path, string media = "screen") { var builder = new StringBuilder(options.HeadContent); builder.AppendLine($"<link href='{path}' rel='stylesheet' media='{media}' type='text/css' />"); options.HeadContent = builder.ToString(); } /// <summary> /// Injects additional Javascript files into the index.html page /// </summary> /// <param name="options"></param> /// <param name="path">A path to the javascript - i.e. the script "src" attribute</param> /// <param name="type">The script type - i.e. the script "type" attribute</param> public static void InjectJavascript(this ApiUIOptions options, string path, string type = "text/javascript") { var builder = new StringBuilder(options.HeadContent); builder.AppendLine($"<script src='{path}' type='{type}'></script>"); options.HeadContent = builder.ToString(); } /// <summary> /// Adds Swagger JSON endpoints. Can be fully-qualified or relative to the UI page /// </summary> /// <param name="options"></param> /// <param name="url">Can be fully qualified or relative to the current host</param> /// <param name="name">The description that appears in the document selector drop-down</param> public static void SwaggerEndpoint(this ApiUIOptions options, string url, string name) { var urls = new List<UrlDescriptor>(options.ConfigObject.Urls ?? Enumerable.Empty<UrlDescriptor>()); urls.Add(new UrlDescriptor { Url = url, Name = name }); options.ConfigObject.Urls = urls; } /// <summary> /// Enables deep linking for tags and operations /// </summary> /// <param name="options"></param> public static void EnableDeepLinking(this ApiUIOptions options) { options.ConfigObject.DeepLinking = true; } /// <summary> /// Enables persist authorization data /// </summary> /// <param name="options"></param> public static void EnablePersistAuthorization(this ApiUIOptions options) { options.ConfigObject.PersistAuthorization = true; } /// <summary> /// Controls the display of operationId in operations list /// </summary> /// <param name="options"></param> public static void DisplayOperationId(this ApiUIOptions options) { options.ConfigObject.DisplayOperationId = true; } /// <summary> /// The default expansion depth for models (set to -1 completely hide the models) /// </summary> /// <param name="options"></param> /// <param name="depth"></param> public static void DefaultModelsExpandDepth(this ApiUIOptions options, int depth) { options.ConfigObject.DefaultModelsExpandDepth = depth; } /// <summary> /// The default expansion depth for the model on the model-example section /// </summary> /// <param name="options"></param> /// <param name="depth"></param> public static void DefaultModelExpandDepth(this ApiUIOptions options, int depth) { options.ConfigObject.DefaultModelExpandDepth = depth; } /// <summary> /// Controls how the model is shown when the API is first rendered. /// (The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links.) /// </summary> /// <param name="options"></param> /// <param name="modelRendering"></param> public static void DefaultModelRendering(this ApiUIOptions options, ModelRendering modelRendering) { options.ConfigObject.DefaultModelRendering = modelRendering; } /// <summary> /// Controls the display of the request duration (in milliseconds) for Try-It-Out requests /// </summary> /// <param name="options"></param> public static void DisplayRequestDuration(this ApiUIOptions options) { options.ConfigObject.DisplayRequestDuration = true; } /// <summary> /// Controls the default expansion setting for the operations and tags. /// It can be 'List' (expands only the tags), 'Full' (expands the tags and operations) or 'None' (expands nothing) /// </summary> /// <param name="options"></param> /// <param name="docExpansion"></param> public static void DocExpansion(this ApiUIOptions options, DocExpansion docExpansion) { options.ConfigObject.DocExpansion = docExpansion; } /// <summary> /// Enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown. /// If an expression is provided it will be used and applied initially. /// Filtering is case sensitive matching the filter expression anywhere inside the tag /// </summary> /// <param name="options"></param> /// <param name="expression"></param> public static void EnableFilter(this ApiUIOptions options, string expression = null) { options.ConfigObject.Filter = expression ?? ""; } /// <summary> /// Enables the "Try it out" section by default. /// </summary> /// <param name="options"></param> public static void EnableTryItOutByDefault(this ApiUIOptions options) { options.ConfigObject.TryItOutEnabled = true; } /// <summary> /// Limits the number of tagged operations displayed to at most this many. The default is to show all operations /// </summary> /// <param name="options"></param> /// <param name="count"></param> public static void MaxDisplayedTags(this ApiUIOptions options, int count) { options.ConfigObject.MaxDisplayedTags = count; } /// <summary> /// Controls the display of vendor extension (x-) fields and values for Operations, Parameters, and Schema /// </summary> /// <param name="options"></param> public static void ShowExtensions(this ApiUIOptions options) { options.ConfigObject.ShowExtensions = true; } /// <summary> /// Controls the display of extensions (pattern, maxLength, minLength, maximum, minimum) fields and values for Parameters /// </summary> /// <param name="options"></param> public static void ShowCommonExtensions(this ApiUIOptions options) { options.ConfigObject.ShowCommonExtensions = true; } /// <summary> /// List of HTTP methods that have the Try it out feature enabled. An empty array disables Try it out for all operations. /// This does not filter the operations from the display /// </summary> /// <param name="options"></param> /// <param name="submitMethods"></param> public static void SupportedSubmitMethods(this ApiUIOptions options, params SubmitMethod[] submitMethods) { options.ConfigObject.SupportedSubmitMethods = submitMethods; } /// <summary> /// OAuth redirect URL /// </summary> /// <param name="options"></param> /// <param name="url"></param> public static void OAuth2RedirectUrl(this ApiUIOptions options, string url) { options.ConfigObject.OAuth2RedirectUrl = url; } [Obsolete("The validator is disabled by default. Use EnableValidator to enable it")] public static void ValidatorUrl(this ApiUIOptions options, string url) { options.ConfigObject.ValidatorUrl = url; } /// <summary> /// You can use this parameter to enable the swagger-ui's built-in validator (badge) functionality /// Setting it to null will disable validation /// </summary> /// <param name="options"></param> /// <param name="url"></param> public static void EnableValidator(this ApiUIOptions options, string url = "https://online.swagger.io/validator") { options.ConfigObject.ValidatorUrl = url; } /// <summary> /// Default clientId /// </summary> /// <param name="options"></param> /// <param name="value"></param> public static void OAuthClientId(this ApiUIOptions options, string value) { options.OAuthConfigObject.ClientId = value; } /// <summary> /// Default userName /// </summary> /// <param name="options"></param> /// <param name="value"></param> public static void OAuthUsername(this ApiUIOptions options, string value) { options.OAuthConfigObject.Username = value; } /// <summary> /// Default clientSecret /// </summary> /// <param name="options"></param> /// <param name="value"></param> /// <remarks>Setting this exposes the client secrets in inline javascript in the swagger-ui generated html.</remarks> public static void OAuthClientSecret(this ApiUIOptions options, string value) { options.OAuthConfigObject.ClientSecret = value; } /// <summary> /// realm query parameter (for oauth1) added to authorizationUrl and tokenUrl /// </summary> /// <param name="options"></param> /// <param name="value"></param> public static void OAuthRealm(this ApiUIOptions options, string value) { options.OAuthConfigObject.Realm = value; } /// <summary> /// Application name, displayed in authorization popup /// </summary> /// <param name="options"></param> /// <param name="value"></param> public static void OAuthAppName(this ApiUIOptions options, string value) { options.OAuthConfigObject.AppName = value; } /// <summary> /// Scope separator for passing scopes, encoded before calling, default value is a space (encoded value %20) /// </summary> /// <param name="options"></param> /// <param name="value"></param> public static void OAuthScopeSeparator(this ApiUIOptions options, string value) { options.OAuthConfigObject.ScopeSeparator = value; } /// <summary> /// String array of initially selected oauth scopes, default is empty array /// </summary> public static void OAuthScopes(this ApiUIOptions options, params string[] scopes) { options.OAuthConfigObject.Scopes = scopes; } /// <summary> /// Additional query parameters added to authorizationUrl and tokenUrl /// </summary> /// <param name="options"></param> /// <param name="value"></param> public static void OAuthAdditionalQueryStringParams( this ApiUIOptions options, Dictionary<string, string> value) { options.OAuthConfigObject.AdditionalQueryStringParams = value; } /// <summary> /// Only activated for the accessCode flow. During the authorization_code request to the tokenUrl, /// pass the Client Password using the HTTP Basic Authentication scheme (Authorization header with /// Basic base64encoded[client_id:client_secret]). The default is false /// </summary> /// <param name="options"></param> public static void OAuthUseBasicAuthenticationWithAccessCodeGrant(this ApiUIOptions options) { options.OAuthConfigObject.UseBasicAuthenticationWithAccessCodeGrant = true; } /// <summary> /// Only applies to authorizatonCode flows. Proof Key for Code Exchange brings enhanced security for OAuth public clients. /// The default is false /// </summary> /// <param name="options"></param> public static void OAuthUsePkce(this ApiUIOptions options) { options.OAuthConfigObject.UsePkceWithAuthorizationCodeGrant = true; } /// <summary> /// Function to intercept remote definition, "Try it out", and OAuth 2.0 requests. /// </summary> /// <param name="options"></param> /// <param name="value">MUST be a valid Javascript function: (request: SwaggerRequest) => SwaggerRequest</param> public static void UseRequestInterceptor(this ApiUIOptions options, string value) { options.Interceptors.RequestInterceptorFunction = value; } /// <summary> /// Function to intercept remote definition, "Try it out", and OAuth 2.0 responses. /// </summary> /// <param name="options"></param> /// <param name="value">MUST be a valid Javascript function: (response: SwaggerResponse ) => SwaggerResponse </param> public static void UseResponseInterceptor(this ApiUIOptions options, string value) { options.Interceptors.ResponseInterceptorFunction = value; } } }
294coder/Efficient-MIF
1,548
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/indexes_evaluation_FS.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Full resolution quality indexes. % % Interface: % [D_lambda,D_S,QNR_index,SAM_index,sCC] = indexes_evaluation_FS(I_F,I_MS_LR,I_PAN,L,th_values,I_MS,sensor,tag,ratio) % % Inputs: % I_F: Fused image; % I_MS_LR: MS image; % I_PAN: Panchromatic image; % L: Image radiometric resolution; % th_values: Flag. If th_values == 1, apply an hard threshold to the dynamic range; % I_MS: MS image upsampled to the PAN size; % sensor: String for type of sensor (e.g. 'WV2','IKONOS'); % ratio: Scale ratio between MS and PAN. Pre-condition: Integer value; % flagQNR: if flagQNR == 1, the software uses the QNR otherwise the HQNR is used. % % Outputs: % D_lambda: D_lambda index; % D_S: D_S index; % QNR_index: QNR index; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [D_lambda,D_S,QNR_index] = indexes_evaluation_FS(I_F,I_MS_LR,I_PAN,L,th_values,I_MS,sensor,ratio,flagQNR) if th_values I_F(I_F > 2^L) = 2^L; I_F(I_F < 0) = 0; end cd Quality_Indices if flagQNR == 1 [QNR_index,D_lambda,D_S]= QNR(I_F,I_MS,I_MS_LR,I_PAN,ratio); else [QNR_index,D_lambda,D_S] = HQNR(I_F,I_MS_LR,I_MS,I_PAN,32,sensor,ratio); end cd .. end
294coder/Efficient-MIF
2,459
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/MTF_PAN.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % MTF filters the panchromatic (PAN) image using a Gaussin filter matched with the Modulation Transfer Function (MTF) of the PAN sensor. % % Interface: % I_Filtered = MTF_PAN(I_PAN,sensor,ratio) % % Inputs: % I_PAN: PAN image; % sensor: String for type of sensor (e.g. 'WV2', 'IKONOS'); % ratio: Scale ratio between MS and PAN. % % Outputs: % I_Filtered: Output filtered PAN image. % % References: % [Aiazzi02] B. Aiazzi, L. Alparone, S. Baronti, and A. Garzelli, Context-driven fusion of high spatial and spectral resolution images based on % oversampled multiresolution analysis, IEEE Transactions on Geoscience and Remote Sensing, vol. 40, no. 10, pp. 23002312, October % 2002. % [Aiazzi06] B. Aiazzi, L. Alparone, S. Baronti, A. Garzelli, and M. Selva, MTF-tailored multiscale fusion of high-resolution MS and Pan imagery, % Photogrammetric Engineering and Remote Sensing, vol. 72, no. 5, pp. 591596, May 2006. % [Vivone14a] G. Vivone, R. Restaino, M. Dalla Mura, G. Licciardi, and J. Chanussot, Contrast and error-based fusion schemes for multispectral % image pansharpening, IEEE Geoscience and Remote Sensing Letters, vol. 11, no. 5, pp. 930934, May 2014. % [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms, % IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function I_Filtered = MTF_PAN(I_PAN,sensor,ratio) switch sensor case 'QB' GNyq = 0.15; case 'IKONOS' GNyq = 0.17; case {'GeoEye1','WV4'} GNyq = 0.16; case 'WV2' GNyq = 0.11; case 'WV3' GNyq = 0.14; case 'none' GNyq = 0.15; end N = 41; fcut = 1/ratio; alpha = sqrt(((N-1)*(fcut/2))^2/(-2*log(GNyq))); H = fspecial('gaussian', N, alpha); Hd = H./max(H(:)); h = fwind1(Hd,kaiser(N)); I_PAN_LP = imfilter(I_PAN,real(h),'replicate'); I_Filtered= double(I_PAN_LP); end
2977094657/BiliHistoryFrontend
10,103
src/components/tailwind/analytics/pages/AuthorCompletionPage.vue
<!-- UP主完成率分析页组件 --> <template> <div class="absolute inset-0"> <div class="h-full flex items-center justify-center"> <div class="max-w-7xl w-full mx-auto px-2 py-4 overflow-y-auto"> <div class="space-y-4"> <h3 class="text-3xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> UP主完成率分析 </h3> <div class="text-sm text-center text-gray-800 dark:text-gray-200 mb-2 space-y-1 px-4"> <div v-if="viewingData?.insights?.most_valuable_author" v-html="formatInsightText(viewingData.insights.most_valuable_author)"> </div> <div v-if="viewingData?.insights?.highest_completion_author" v-html="formatInsightText(viewingData.insights.highest_completion_author)"> </div> <div v-if="viewingData?.insights?.potential_discovery" v-html="formatInsightText(viewingData.insights.potential_discovery)"> </div> <div v-if="viewingData?.insights?.viewing_behavior_summary" v-html="formatInsightText(viewingData.insights.viewing_behavior_summary)"> </div> </div> <!-- 图表容器 --> <div class="grid grid-cols-1 lg:grid-cols-2 gap-3"> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-3 border border-gray-300/50 dark:border-gray-500/50 h-[420px]"> <h4 class="text-base font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-3"> 最喜欢的UP主 </h4> <v-chart ref="favoriteChartRef" class="h-[360px] w-full" :option="favoriteOption" autoresize @click="handleFavoriteClick" /> </div> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-3 border border-gray-300/50 dark:border-gray-500/50 h-[420px]"> <h4 class="text-base font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-3"> 观看最多的UP主 </h4> <v-chart ref="mostWatchedChartRef" class="h-[360px] w-full" :option="mostWatchedOption" autoresize @click="handleMostWatchedClick" /> </div> </div> </div> </div> </div> </div> </template> <script setup> import { ref, computed, onMounted } from 'vue' import VChart from 'vue-echarts' import * as echarts from 'echarts/core' import { CanvasRenderer } from 'echarts/renderers' import { BarChart, LineChart, RadarChart } from 'echarts/charts' import { GridComponent, TooltipComponent, LegendComponent, TitleComponent, DataZoomComponent, RadarComponent } from 'echarts/components' import { use } from 'echarts/core' // 注册必要的组件 use([ CanvasRenderer, BarChart, LineChart, RadarChart, GridComponent, TooltipComponent, LegendComponent, TitleComponent, DataZoomComponent, RadarComponent ]) const props = defineProps({ viewingData: { type: Object, required: true } }) const favoriteChartRef = ref(null) const mostWatchedChartRef = ref(null) // 获取最喜欢的UP主数据(使用most_valuable_authors) const sortedFavoriteAuthors = computed(() => { if (!props.viewingData?.completion_rates?.most_valuable_authors) return [] return Object.entries(props.viewingData.completion_rates.most_valuable_authors) .sort((a, b) => b[1].comprehensive_score - a[1].comprehensive_score) .slice(0, 10) // 显示10个UP主 }) // 获取观看最多的UP主数据 const sortedMostWatchedAuthors = computed(() => { if (!props.viewingData?.completion_rates?.most_watched_authors) return [] return Object.entries(props.viewingData.completion_rates.most_watched_authors) .sort((a, b) => b[1].video_count - a[1].video_count) .slice(0, 10) }) // 最喜欢的UP主雷达图配置 const favoriteOption = computed(() => { const data = sortedFavoriteAuthors.value.map(([author, stats]) => ({ name: author, value: [ stats.comprehensive_score, stats.loyalty_score, stats.quality_score, stats.average_completion_rate, stats.fully_watched_rate, stats.video_count / 10 // 缩放视频数量以适应雷达图 ], authorMid: stats.author_mid })) return { tooltip: { trigger: 'item', formatter: (params) => { const stats = sortedFavoriteAuthors.value.find(([author]) => author === params.name)?.[1] if (!stats) return '' return `${params.name}<br/> 综合评分:${stats.comprehensive_score.toFixed(1)}<br/> 喜爱度评分:${stats.loyalty_score.toFixed(1)}<br/> 质量评分:${stats.quality_score.toFixed(1)}<br/> 平均完成率:${stats.average_completion_rate.toFixed(1)}%<br/> 完整观看率:${stats.fully_watched_rate.toFixed(1)}%<br/> 视频数量:${stats.video_count}个` } }, legend: { data: data.map(item => item.name), textStyle: { color: '#666', fontSize: 10 }, left: 'left', orient: 'vertical', top: 'middle', type: 'scroll', width: 70 }, radar: { center: ['65%', '50%'], radius: '65%', indicator: [ { name: '综合评分', max: 100 }, { name: '喜爱度', max: 100 }, { name: '质量评分', max: 100 }, { name: '完成率', max: 100 }, { name: '完整观看率', max: 100 }, { name: '视频数量', max: 20 } ], name: { textStyle: { color: '#999', fontSize: 12, fontWeight: 'bold' } }, axisLabel: { color: '#666' }, axisLine: { lineStyle: { color: '#ddd' } }, splitLine: { lineStyle: { color: '#ddd' } } }, series: [{ type: 'radar', data: data.map((item, index) => { const colors = [ '#fb7299', // 粉色 '#40a9ff', // 蓝色 '#66d980', // 绿色 '#fc9b7a', // 橙色 '#9254de', // 紫色 '#ffc53d', // 黄色 '#ff6b6b', // 红色 '#4ecdc4', // 青色 '#45b7d1', // 天蓝色 '#f39c12' // 深橙色 ] const color = colors[index % colors.length] return { ...item, itemStyle: { color: color }, lineStyle: { color: color, width: 2 }, // 默认不显示背景区域 emphasis: { itemStyle: { color: color }, lineStyle: { color: color, width: 4 }, areaStyle: { color: color, opacity: 0.4 } } } }) }] } }) // 观看最多的UP主散点图配置 const mostWatchedOption = computed(() => { const data = sortedMostWatchedAuthors.value.map(([author, stats]) => ([ stats.video_count, stats.average_completion_rate, stats.fully_watched, author, stats.author_mid ])) return { tooltip: { trigger: 'item', formatter: (params) => { return `${params.data[3]}<br/> 观看视频数:${params.data[0]}个<br/> 平均完成率:${params.data[1].toFixed(1)}%<br/> 完整观看数:${params.data[2]}个` } }, grid: { top: '10%', left: '12%', right: '8%', bottom: '15%' }, xAxis: { type: 'value', name: '观看视频数', nameLocation: 'middle', nameGap: 25, axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' }, splitLine: { lineStyle: { color: 'rgba(0, 0, 0, 0.1)' } } }, yAxis: { type: 'value', name: '平均完成率(%)', nameLocation: 'middle', nameGap: 35, axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' }, splitLine: { lineStyle: { color: 'rgba(0, 0, 0, 0.1)' } } }, series: [{ type: 'scatter', symbolSize: (data) => Math.sqrt(data[2]) * 3, // 根据完整观看数调整点的大小 data: data, itemStyle: { color: (params) => { const colors = ['#fb7299', '#40a9ff', '#66d980', '#fc9b7a', '#9254de', '#ffc53d'] return colors[params.dataIndex % colors.length] }, opacity: 0.8 }, emphasis: { focus: 'item', itemStyle: { opacity: 1, borderColor: '#333', borderWidth: 2 } } }] } }) // 点击事件处理函数 const handleFavoriteClick = (params) => { if (params.componentType === 'series') { const authorData = sortedFavoriteAuthors.value.find(([author]) => author === params.name) if (authorData?.[1]?.author_mid) { handleAuthorClick(authorData[1].author_mid) } } } const handleMostWatchedClick = (params) => { if (params.componentType === 'series') { const authorData = sortedMostWatchedAuthors.value.find(([author]) => author === params.data[3]) if (authorData?.[1]?.author_mid) { handleAuthorClick(authorData[1].author_mid) } } } const handleAuthorClick = (mid) => { window.open(`https://space.bilibili.com/${mid}`, '_blank') } // 添加事件监听 onMounted(() => { const favoriteChart = favoriteChartRef.value const mostWatchedChart = mostWatchedChartRef.value // 雷达图点击事件(通过ECharts内置事件处理) if (favoriteChart) { favoriteChart.chart.on('click', (params) => { if (params.componentType === 'series') { const authorData = sortedFavoriteAuthors.value.find(([author]) => author === params.name) if (authorData?.[1]?.author_mid) { handleAuthorClick(authorData[1].author_mid) } } }) } // 散点图点击事件(通过ECharts内置事件处理) if (mostWatchedChart) { mostWatchedChart.chart.on('click', (params) => { if (params.componentType === 'series') { const authorData = sortedMostWatchedAuthors.value.find(([author]) => author === params.data[3]) if (authorData?.[1]?.author_mid) { handleAuthorClick(authorData[1].author_mid) } } }) } }) // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } </script> <style scoped> .echarts :deep(.yAxis) { cursor: pointer; } </style>
2881099/FreeSql.AdminLTE
5,611
Examples/net80_blazor/Infrastructure/Swagger/ApiUIMiddleware.cs
using System.Reflection; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Text; using System.Collections.Generic; using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.FileProviders; using Microsoft.AspNetCore.StaticFiles; using Microsoft.AspNetCore.Http.Extensions; using System.Linq; #if NETSTANDARD2_0 using IWebHostEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment; #endif namespace FreeWeb.Infrastructure.Swagger { public class ApiUIMiddleware { private const string EmbeddedFileNamespace = "ZhonTai.ApiUI.src.dist"; private readonly ApiUIOptions _options; private readonly StaticFileMiddleware _staticFileMiddleware; private readonly JsonSerializerOptions _jsonSerializerOptions; public ApiUIMiddleware( RequestDelegate next, IWebHostEnvironment hostingEnv, ILoggerFactory loggerFactory, ApiUIOptions options) { _options = options ?? new ApiUIOptions(); _staticFileMiddleware = CreateStaticFileMiddleware(next, hostingEnv, loggerFactory, options); _jsonSerializerOptions = new JsonSerializerOptions(); #if NET6_0_OR_GREATER _jsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; #else _jsonSerializerOptions.IgnoreNullValues = true; #endif _jsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; _jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase, false)); } public async Task Invoke(HttpContext httpContext) { var httpMethod = httpContext.Request.Method; var path = httpContext.Request.Path.Value; // If the RoutePrefix is requested (with or without trailing slash), redirect to index URL if (httpMethod == "GET" && Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase)) { // Use relative redirect to support proxy environments var relativeIndexUrl = string.IsNullOrEmpty(path) || path.EndsWith("/") ? "index.html" : $"{path.Split('/').Last()}/index.html"; RespondWithRedirect(httpContext.Response, relativeIndexUrl); return; } if (httpMethod == "GET" && Regex.IsMatch(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?index.html$", RegexOptions.IgnoreCase)) { await RespondWithIndexHtml(httpContext.Response); return; } if (httpMethod == "GET" && Regex.IsMatch(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?swagger-resources$", RegexOptions.IgnoreCase)) { await RespondWithConfig(httpContext.Response); return; } await _staticFileMiddleware.Invoke(httpContext); } private async Task RespondWithConfig(HttpResponse response) { await response.WriteAsync(JsonSerializer.Serialize(_options.ConfigObject.Urls, _jsonSerializerOptions)); } private StaticFileMiddleware CreateStaticFileMiddleware( RequestDelegate next, IWebHostEnvironment hostingEnv, ILoggerFactory loggerFactory, ApiUIOptions options) { var staticFileOptions = new StaticFileOptions { RequestPath = string.IsNullOrEmpty(options.RoutePrefix) ? string.Empty : $"/{options.RoutePrefix}", FileProvider = new EmbeddedFileProvider(typeof(ApiUIMiddleware).GetTypeInfo().Assembly, EmbeddedFileNamespace), }; return new StaticFileMiddleware(next, hostingEnv, Options.Create(staticFileOptions), loggerFactory); } private void RespondWithRedirect(HttpResponse response, string location) { response.StatusCode = 301; response.Headers["Location"] = location; } private async Task RespondWithIndexHtml(HttpResponse response) { response.StatusCode = 200; response.ContentType = "text/html;charset=utf-8"; using (var stream = _options.IndexStream()) { // Inject arguments before writing to response var htmlBuilder = new StringBuilder(new StreamReader(stream).ReadToEnd()); foreach (var entry in GetIndexArguments()) { htmlBuilder.Replace(entry.Key, entry.Value); } await response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8); } } private IDictionary<string, string> GetIndexArguments() { return new Dictionary<string, string>() { { "%(DocumentTitle)", _options.DocumentTitle }, { "%(HeadContent)", _options.HeadContent }, { "%(ConfigObject)", JsonSerializer.Serialize(_options.ConfigObject, _jsonSerializerOptions) }, { "%(OAuthConfigObject)", JsonSerializer.Serialize(_options.OAuthConfigObject, _jsonSerializerOptions) }, { "%(Interceptors)", JsonSerializer.Serialize(_options.Interceptors) }, }; } } }
2977094657/BiliHistoryFrontend
3,292
src/components/tailwind/analytics/pages/MonthlyPage.vue
<!-- 月度趋势页组件 --> <template> <div class="space-y-6"> <h3 class="text-4xl font-bold text-center bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent"> 月度观看趋势 </h3> <div v-if="viewingData?.insights?.monthly_pattern" class="text-lg text-center text-gray-600 dark:text-gray-300 mb-8" v-html="formatInsightText(viewingData.insights.monthly_pattern)" > </div> <!-- 月度趋势图表 --> <div class="bg-white/50 dark:bg-white/5 backdrop-blur-sm rounded-xl p-6 border border-gray-300/50 dark:border-gray-500/50"> <h4 class="text-xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent mb-4">月度趋势</h4> <div class="h-[220px]"> <v-chart ref="chartRef" class="h-full w-full" :option="monthlyOption" autoresize /> </div> </div> </div> </template> <script setup> import { ref, computed, onMounted } from 'vue' import gsap from 'gsap' import VChart from 'vue-echarts' import * as echarts from 'echarts/core' const props = defineProps({ viewingData: { type: Object, required: true } }) const chartRef = ref(null) const monthlyOption = computed(() => { if (!props.viewingData?.monthly_stats) return {} const data = Object.entries(props.viewingData.monthly_stats) .sort(([a], [b]) => a.localeCompare(b)) return { tooltip: { trigger: 'axis', backgroundColor: 'rgba(28, 28, 28, 0.9)', borderColor: '#fb7299', textStyle: { color: '#fff' } }, grid: { top: '15%', left: '8%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'category', data: data.map(([month]) => month), axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' } }, yAxis: { type: 'value', name: '观看次数', axisLine: { lineStyle: { color: '#666' } }, axisLabel: { color: '#999' }, splitLine: { lineStyle: { color: 'rgba(0, 0, 0, 0.1)' } } }, series: [{ data: data.map(([, count]) => count), type: 'line', smooth: true, lineStyle: { width: 2.5, color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [ { offset: 0, color: 'rgba(251, 114, 153, 0.9)' }, { offset: 1, color: 'rgba(252, 155, 122, 0.9)' } ]) }, areaStyle: { opacity: 0.15, color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [ { offset: 0, color: 'rgba(251, 114, 153, 0.4)' }, { offset: 1, color: 'rgba(252, 155, 122, 0)' } ]) }, symbolSize: 6, symbol: 'circle', itemStyle: { borderWidth: 2, borderColor: '#fff', color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [ { offset: 0, color: 'rgba(251, 114, 153, 0.9)' }, { offset: 1, color: 'rgba(252, 155, 122, 0.9)' } ]) } }] } }) onMounted(() => { if (chartRef.value) { gsap.from(chartRef.value.$el, { opacity: 0, y: 20, duration: 0.5, ease: 'power2.out', delay: 0.2 }) } }) // 格式化洞察文本,为数字添加颜色 const formatInsightText = (text) => { if (!text) return ''; return text.replace(/(\d+(\.\d+)?)/g, '<span class="text-[#fb7299]">$1</span>') } </script>
2881099/FreeSql.AdminLTE
1,760
Examples/net80_blazor/Infrastructure/Swagger/ApiUIBuilderExtensions.cs
using System; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.AspNetCore.Hosting; #if NETSTANDARD2_0 using IWebHostEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment; #endif namespace FreeWeb.Infrastructure.Swagger { public static class ApiUIBuilderExtensions { /// <summary> /// Register the SwaggerUI middleware with provided options /// </summary> public static IApplicationBuilder UseSwaggerUI(this IApplicationBuilder app, ApiUIOptions options) { return app.UseMiddleware<ApiUIMiddleware>(options); } /// <summary> /// Register the SwaggerUI middleware with optional setup action for DI-injected options /// </summary> public static IApplicationBuilder UseApiUI( this IApplicationBuilder app, Action<ApiUIOptions> setupAction = null) { ApiUIOptions options; using (var scope = app.ApplicationServices.CreateScope()) { options = scope.ServiceProvider.GetRequiredService<IOptionsSnapshot<ApiUIOptions>>().Value; setupAction?.Invoke(options); } // To simplify the common case, use a default that will work with the SwaggerMiddleware defaults if (options.ConfigObject.Urls == null) { var hostingEnv = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>(); options.ConfigObject.Urls = new[] { new UrlDescriptor { Name = $"{hostingEnv.ApplicationName} v1", Url = "v1/swagger.json" } }; } return app.UseSwaggerUI(options); } } }
294coder/Efficient-MIF
1,467
Pansharpening_Hyper_SR_Matlab_Test_Package/Tools/showImage8LR.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Description: % Visualize and print an eight-band multispectral image. % % Interface: % showImage8LR(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L,ratio) % % Inputs: % I_MS: Eight band multispectral image; % print: Flag. If print == 1, print EPS image; % id: Identifier (name) of the printed EPS image; % flag_cut_bounds: Cut the boundaries of the viewed Panchromatic image; % dim_cut: Define the dimension of the boundary cut; % th_values: Flag. If th_values == 1, apply an hard threshold to the dynamic range; % L: Radiomatric resolution of the input image; % ratio: Resize factor. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showImage8LR(I_MS,print,id,flag_cut_bounds,dim_cut,th_values,L,ratio) if flag_cut_bounds I_MS = I_MS(round(dim_cut/ratio):end-round(dim_cut/ratio),round(dim_cut/ratio):end-round(dim_cut/ratio),:); end if th_values I_MS(I_MS > 2^L) = 2^L; I_MS(I_MS < 0) = 0; end if id == 1 IMN = viewimage(I_MS(:,:,[1,3,5])); IMN = IMN(:,:,3:-1:1); else IMN = viewimage(I_MS(:,:,[1,3,5]),[0.01 0.995]); IMN = IMN(:,:,3:-1:1); end if print printImage(IMN,sprintf('Outputs/%d.eps',id)); end end