| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518 |
- // EasyFlow 编译器 - 工作流任务解析和执行器
- // 配置参数
- const DEFAULT_STEP_INTERVAL = 1000; // 默认步骤间隔1秒
- const DEFAULT_SCROLL_DISTANCE = 100; // 默认每次滚动距离(像素)
- // 变量上下文(用于存储变量值)
- let variableContext = {};
- // 变量上下文是否已初始化(防止循环中重置变量)
- let variableContextInitialized = false;
- // 全局步骤计数器(用于连续的步骤编号)
- let globalStepCounter = 0;
- // 当前工作流文件夹路径(用于日志记录)
- let currentWorkflowFolderPath = null;
- /**
- * 记录日志(同时输出到 console 和文件)
- * @param {string} message - 日志消息
- * @param {string} folderPath - 工作流文件夹路径(可选,如果不提供则使用 currentWorkflowFolderPath)
- */
- async function logMessage(message, folderPath = null) {
- // 尝试写入日志文件(异步,不阻塞主流程)
- // 注意:不输出到 console,只写入日志文件
- try {
- const targetFolderPath = folderPath || currentWorkflowFolderPath;
- if (targetFolderPath && electronAPI.appendLog) {
- electronAPI.appendLog(targetFolderPath, message).catch(err => {
- // 静默失败,不影响主流程
- });
- }
- } catch (error) {
- // 静默失败,不影响主流程
- }
- }
- // 打印所有 outVars 的值
- async function logOutVars(action, variableContext, folderPath = null) {
- if (!action.outVars || !Array.isArray(action.outVars) || action.outVars.length === 0) {
- return;
- }
-
- const outVarsInfo = action.outVars.map((varName, index) => {
- const varNameClean = extractVarName(varName);
- const value = variableContext[varNameClean];
- // 如果值太长,截断显示(超过100字符)
- let displayValue = value;
- if (typeof value === 'string' && value.length > 100) {
- displayValue = value.substring(0, 100) + '...';
- }
- return `${varNameClean}: ${JSON.stringify(displayValue)}`;
- });
-
- // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
- // const logMsg = `输出变量: ${outVarsInfo.join(', ')}`;
- // await logMessage(logMsg, folderPath);
- }
- const path = require('path')
- const fs = require('fs')
- const { spawnSync } = require('child_process')
- const funcDir = path.join(__dirname, 'Func')
- const projectRoot = path.resolve(__dirname, '..', '..')
- const adbInteractPath = path.join(projectRoot, 'nodejs', 'adb', 'adb-interact.js')
- const { generateHistorySummary, getHistorySummary } = require(path.join(funcDir, 'chat', 'chat-history.js'))
- const { executeOcrChat } = require(path.join(funcDir, 'chat', 'ocr-chat.js'))
- const { executeImgBoundingBoxLocation } = require(path.join(funcDir, 'img-bounding-box-location.js'))
- const { executeImgCenterPointLocation, matchImageAndGetCoordinate } = require(path.join(funcDir, 'img-center-point-location.js'))
- const { executeImgCropping } = require(path.join(funcDir, 'img-cropping.js'))
- const { executeReadLastMessage } = require(path.join(funcDir, 'chat', 'read-last-message.js'))
- const { executeReadTxt, readTextFile } = require(path.join(funcDir, 'read-txt.js'))
- const { executeSaveTxt, writeTextFile } = require(path.join(funcDir, 'save-txt.js'))
- const { executeSmartChatAppend } = require(path.join(funcDir, 'chat', 'smart-chat-append.js'))
- function runAdb(action, args = [], deviceId = '') {
- const r = spawnSync('node', [adbInteractPath, action, ...args, deviceId], { encoding: 'utf-8', timeout: 10000 })
- return { success: r.status === 0, error: r.stderr }
- }
- const sendTap = (device, x, y) => runAdb('tap', [String(x), String(y)], device)
- const sendSwipe = (device, x1, y1, x2, y2, duration) => runAdb('swipe-coords', [String(x1), String(y1), String(x2), String(y2), String(duration || 300)], device)
- const sendKeyEvent = (device, keyCode) => runAdb('keyevent', [String(keyCode)], device)
- const sendText = (device, text) => runAdb('text', [String(text)], device)
- function appendLog(folderPath, message) {
- fs.appendFileSync(path.join(folderPath, 'log.txt'), message + '\n')
- return Promise.resolve()
- }
- const _stub = (name) => ({ success: false, error: `${name} 需在主进程实现` })
- const electronAPI = {
- sendTap, sendSwipe, sendKeyEvent, sendText,
- matchImageAndGetCoordinate,
- findTextAndGetCoordinate: () => _stub('findTextAndGetCoordinate'),
- appendLog, readTextFile, writeTextFile,
- saveChatHistory: () => _stub('saveChatHistory'),
- readChatHistory: () => _stub('readChatHistory'),
- readAllChatHistory: () => _stub('readAllChatHistory'),
- saveChatHistorySummary: () => _stub('saveChatHistorySummary'),
- getChatHistorySummary: () => _stub('getChatHistorySummary'),
- saveChatHistoryTxt: () => _stub('saveChatHistoryTxt'),
- extractChatHistory: () => _stub('extractChatHistory'),
- readLastMessage: () => _stub('readLastMessage'),
- ocrLastMessage: () => _stub('ocrLastMessage'),
- getCachedScreenshot: () => _stub('getCachedScreenshot'),
- captureScreenshot: () => _stub('captureScreenshot'),
- sendScroll: () => _stub('sendScroll'),
- sendSystemKey: () => _stub('sendSystemKey'),
- matchImageRegionLocation: () => _stub('matchImageRegionLocation'),
- }
- /**
- * 解析时间字符串(格式:2026/1/13 02:09)
- * @param {string} timeStr - 时间字符串
- * @returns {Date|null} 解析后的日期对象,失败返回null
- */
- function parseTimeString(timeStr) {
- if (!timeStr || timeStr.trim() === '') {
- return null;
- }
-
- try {
- // 支持格式:2026/1/13 02:09 或 2026/01/13 02:09
- const parts = timeStr.trim().split(' ');
- if (parts.length !== 2) {
- return null;
- }
-
- const datePart = parts[0].split('/');
- const timePart = parts[1].split(':');
-
- if (datePart.length !== 3 || timePart.length !== 2) {
- return null;
- }
-
- const year = parseInt(datePart[0], 10);
- const month = parseInt(datePart[1], 10) - 1; // 月份从0开始
- const day = parseInt(datePart[2], 10);
- const hour = parseInt(timePart[0], 10);
- const minute = parseInt(timePart[1], 10);
-
- const date = new Date(year, month, day, hour, minute, 0, 0);
-
- // 验证日期是否有效
- if (isNaN(date.getTime())) {
- return null;
- }
-
- return date;
- } catch (error) {
- return null;
- }
- }
- /**
- * 解析延迟字符串(格式:10s, 5m, 2h)
- * @param {string} delayStr - 延迟字符串
- * @returns {number|null} 延迟的毫秒数,失败返回null
- */
- function parseDelayString(delayStr) {
- if (!delayStr || delayStr.trim() === '') {
- return 0; // 空字符串表示不延迟
- }
-
- try {
- const trimmed = delayStr.trim();
- const unit = trimmed.slice(-1).toLowerCase();
- const value = parseInt(trimmed.slice(0, -1), 10);
-
- if (isNaN(value) || value < 0) {
- return null;
- }
-
- switch (unit) {
- case 's':
- return value * 1000; // 秒转毫秒
- case 'm':
- return value * 60 * 1000; // 分钟转毫秒
- case 'h':
- return value * 60 * 60 * 1000; // 小时转毫秒
- default:
- return null;
- }
- } catch (error) {
- return null;
- }
- }
- /**
- * 计算需要等待的时间(毫秒)
- * @param {string} data - 执行时间字符串(格式:2026/1/13 02:09)
- * @param {string} delay - 延迟字符串(格式:10s, 5m, 2h)
- * @returns {number} 需要等待的毫秒数
- */
- function calculateWaitTime(data, delay) {
- // 始终返回 0,不等待,立即执行
- return 0;
- }
- /**
- * 从变量名中提取变量名(去除 {variable} 格式的包裹)
- * @param {string} varName - 变量名(可能包含 {})
- * @returns {string} 提取后的变量名
- */
- function extractVarName(varName) {
- if (typeof varName === 'string' && varName.startsWith('{') && varName.endsWith('}')) {
- return varName.slice(1, -1);
- }
- return varName;
- }
- /**
- * 替换字符串中的变量(只支持 {{variable}} 格式,用于字符串拼接)
- * @param {string} str - 原始字符串
- * @param {Object} context - 变量上下文
- * @returns {string} 替换后的字符串
- */
- function replaceVariablesInString(str, context = variableContext) {
- if (typeof str !== 'string') {
- return str;
- }
-
- let result = str;
-
- // 只替换 {{variable}} 格式的变量(双花括号,用于字符串拼接)
- // 支持变量名中包含连字符,如 {{chat-history}}
- const doubleBracePattern = /\{\{([\w-]+)\}\}/g;
- result = result.replace(doubleBracePattern, (match, varName) => {
- const varValue = context[varName];
- if (varValue === undefined || varValue === null) {
- return '';
- }
- // 如果值是空字符串,返回空字符串
- if (varValue === '') {
- return '';
- }
- // 如果值是字符串 "undefined" 或 "null",视为空
- if (varValue === 'undefined' || varValue === 'null') {
- return '';
- }
- // 如果是字符串,尝试判断是否是 JSON 数组字符串
- if (typeof varValue === 'string') {
- try {
- const parsed = JSON.parse(varValue);
- if (Array.isArray(parsed)) {
- // 如果是空数组,返回空字符串
- if (parsed.length === 0) {
- return '';
- }
- // 如果不是空数组,返回原始 JSON 字符串
- return varValue;
- }
- } catch (e) {
- // 不是 JSON,按普通字符串处理
- }
- }
- // 如果是数组或对象,转换为 JSON 字符串
- if (Array.isArray(varValue) || typeof varValue === 'object') {
- try {
- return JSON.stringify(varValue);
- } catch (e) {
- return String(varValue);
- }
- }
- return String(varValue);
- });
-
- return result;
- }
- /**
- * 解析变量值(支持 {variable} 格式)
- * @param {any} value - 原始值
- * @param {Object} context - 变量上下文
- * @returns {any} 解析后的值
- */
- function resolveValue(value, context = variableContext) {
- if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) {
- const varName = value.slice(1, -1);
- return context[varName] !== undefined ? context[varName] : value;
- }
- if (Array.isArray(value)) {
- return value.map(item => resolveValue(item, context));
- }
- if (typeof value === 'object' && value !== null) {
- const resolved = {};
- for (const key in value) {
- resolved[key] = resolveValue(value[key], context);
- }
- return resolved;
- }
- return value;
- }
- /**
- * 手动解析并计算算术表达式(不使用 eval 或 Function)
- * 支持 +, -, *, / 和括号
- * @param {string} expr - 表达式字符串,如 "1+2*3"
- * @returns {number} 计算结果
- */
- function parseArithmeticExpression(expr) {
- let index = 0;
-
- // 跳过空格
- const skipWhitespace = () => {
- while (index < expr.length && /\s/.test(expr[index])) {
- index++;
- }
- };
-
- // 解析数字
- const parseNumber = () => {
- skipWhitespace();
- let numStr = '';
- let hasDot = false;
-
- while (index < expr.length) {
- const char = expr[index];
- if (char >= '0' && char <= '9') {
- numStr += char;
- index++;
- } else if (char === '.' && !hasDot) {
- numStr += '.';
- hasDot = true;
- index++;
- } else {
- break;
- }
- }
-
- if (numStr === '') {
- throw new Error('期望数字');
- }
-
- const num = parseFloat(numStr);
- if (isNaN(num)) {
- throw new Error(`无效的数字: ${numStr}`);
- }
- return num;
- };
-
- // 解析因子(数字或括号表达式)
- const parseFactor = () => {
- skipWhitespace();
-
- if (index >= expr.length) {
- throw new Error('表达式不完整');
- }
-
- // 处理负号(一元运算符)
- let isNegative = false;
- if (expr[index] === '-') {
- isNegative = true;
- index++;
- skipWhitespace();
- } else if (expr[index] === '+') {
- // 正号可以忽略
- index++;
- skipWhitespace();
- }
-
- let result;
- if (expr[index] === '(') {
- index++; // 跳过 '('
- result = parseExpression();
- skipWhitespace();
- if (index >= expr.length || expr[index] !== ')') {
- throw new Error('缺少右括号');
- }
- index++; // 跳过 ')'
- } else {
- result = parseNumber();
- }
-
- return isNegative ? -result : result;
- };
-
- // 解析项(处理 * 和 /)
- const parseTerm = () => {
- let result = parseFactor();
-
- skipWhitespace();
- while (index < expr.length) {
- const op = expr[index];
- if (op === '*') {
- index++;
- result *= parseFactor();
- } else if (op === '/') {
- index++;
- const divisor = parseFactor();
- if (divisor === 0) {
- throw new Error('除以零');
- }
- result /= divisor;
- } else {
- break;
- }
- skipWhitespace();
- }
-
- return result;
- };
-
- // 解析表达式(处理 + 和 -)
- const parseExpression = () => {
- let result = parseTerm();
-
- skipWhitespace();
- while (index < expr.length) {
- const op = expr[index];
- if (op === '+') {
- index++;
- result += parseTerm();
- } else if (op === '-') {
- index++;
- result -= parseTerm();
- } else {
- break;
- }
- skipWhitespace();
- }
-
- return result;
- };
-
- try {
- const result = parseExpression();
- skipWhitespace();
- if (index < expr.length) {
- throw new Error(`表达式解析不完整,剩余: ${expr.substring(index)}`);
- }
- return result;
- } catch (error) {
- throw new Error(`表达式解析失败: ${error.message}`);
- }
- }
- /**
- * 评估算术表达式(支持 +, -, *, / 运算)
- * 只处理 {variable} 格式(单花括号),用于数字运算
- * @param {string} expression - 表达式字符串,如 "{turn} + 1"
- * @param {Object} context - 变量上下文
- * @returns {any} 计算结果
- */
- function evaluateExpression(expression, context = variableContext) {
- if (typeof expression !== 'string') {
- return expression;
- }
-
- try {
- // 替换变量(只处理 {variable} 格式,单花括号用于数字运算)
- let expr = expression.trim();
- // 只匹配 {variable} 格式,不匹配 {{variable}} 格式
- // 使用负向前瞻确保不会匹配双花括号的开始部分
- const varPattern = /\{(\w+)\}(?!\})/g;
- const originalExpr = expr;
- let hasVariables = false;
-
- expr = expr.replace(varPattern, (match, varName) => {
- hasVariables = true;
- const value = context[varName];
- if (value === undefined || value === null) {
- return '0';
- }
- // 数字类型直接转换
- if (typeof value === 'number') {
- return String(value);
- }
- // 布尔类型转换
- if (typeof value === 'boolean') {
- return value ? '1' : '0';
- }
- // 尝试将字符串转换为数字
- if (typeof value === 'string') {
- const numValue = Number(value);
- // 如果字符串可以转换为数字,且不是空字符串,使用数字
- if (!isNaN(numValue) && value.trim() !== '') {
- return String(numValue);
- }
- // 如果无法转换为数字,返回 0 避免错误
- return '0';
- }
- // 其他类型尝试转换为数字
- const numValue = Number(value);
- if (!isNaN(numValue)) {
- return String(numValue);
- }
- return '0';
- });
-
- // 如果没有变量且没有运算符,直接返回原值
- if (!hasVariables && !/[+\-*/]/.test(expr)) {
- const numValue = Number(expr);
- if (!isNaN(numValue) && expr.trim() !== '') {
- return numValue;
- }
- return expr;
- }
-
- // 检查是否包含算术运算符
- if (!/[+\-*/]/.test(expr)) {
- // 没有运算符,直接返回解析后的值
- const numValue = Number(expr);
- if (!isNaN(numValue) && expr.trim() !== '') {
- return numValue;
- }
- return expr;
- }
-
- // 手动解析简单的算术表达式(只支持 +, -, *, /)
- // 移除所有空格
- expr = expr.replace(/\s+/g, '');
-
- // 检查是否只包含数字、运算符、小数点和括号
- if (!/^[0-9+\-*/().]+$/.test(expr)) {
- // 包含不允许的字符,返回原值
- return resolveValue(originalExpr, context);
- }
-
- // 验证表达式格式(防止注入)
- // 确保表达式以数字或括号开头,以数字或括号结尾
- if (!/^[0-9(]/.test(expr) || !/[0-9)]$/.test(expr)) {
- return resolveValue(originalExpr, context);
- }
-
- // 手动解析并计算表达式(不使用 eval 或 Function)
- const result = parseArithmeticExpression(expr);
-
- // 如果结果是数字,返回数字类型
- if (typeof result === 'number' && !isNaN(result) && isFinite(result)) {
- return result;
- }
-
- // 如果结果不是有效数字,返回原值
- return resolveValue(originalExpr, context);
- } catch (error) {
- // 如果计算失败,尝试直接解析变量
- return resolveValue(expression, context);
- }
- }
- /**
- * 评估条件表达式(不使用eval,手动解析)
- * @param {string} condition - 条件表达式
- * @param {Object} context - 变量上下文
- * @returns {boolean} 条件结果
- */
- function evaluateCondition(condition, context = variableContext) {
- if (!condition) return true;
- try {
- // 替换变量
- // 支持变量名中包含连字符,如 {chat-history}
- // 使用 [\w-]+ 来匹配字母、数字、下划线和连字符
- let expr = condition;
- const varPattern = /\{([\w-]+)\}/g;
- expr = expr.replace(varPattern, (match, varName) => {
- const value = context[varName];
- // 如果变量不存在,视为空字符串(所有变量都是 string 或 int 类型)
- if (value === undefined || value === null) {
- return '""';
- }
- // 如果值是空字符串,也返回 '""'
- if (value === '') {
- return '""';
- }
- // 如果值是字符串 "undefined" 或 "null",也视为空字符串
- if (value === 'undefined' || value === 'null') {
- return '""';
- }
- // 确保字符串类型
- if (typeof value === 'string') {
- // 尝试判断是否是 JSON 字符串
- try {
- const parsed = JSON.parse(value);
- if (Array.isArray(parsed)) {
- // 如果是 JSON 数组字符串,转换为 JSON 字符串用于比较(保持原格式)
- const escaped = value.replace(/"/g, '\\"');
- return `"${escaped}"`;
- }
- } catch (e) {
- // 不是 JSON,按普通字符串处理
- }
- // 转义字符串中的引号
- const escaped = value.replace(/"/g, '\\"');
- return `"${escaped}"`;
- }
- if (Array.isArray(value)) {
- // 数组转换为 JSON 字符串(与 chat-history 和 currentMessage 格式一致)
- try {
- const jsonStr = JSON.stringify(value);
- const escaped = jsonStr.replace(/"/g, '\\"');
- return `"${escaped}"`;
- } catch (e) {
- return `"[]"`;
- }
- }
- if (typeof value === 'number') return value;
- if (typeof value === 'boolean') return value;
- // 其他类型转为字符串
- return `"${String(value)}"`;
- });
-
- // 手动解析简单的条件表达式(不使用eval)
- // 支持: ==, !=, >, <, >=, <=, &&, ||
- const result = parseConditionExpression(expr);
- return result;
- } catch (error) {
- return false;
- }
- }
- /**
- * 手动解析条件表达式(避免使用eval)
- * @param {string} expr - 表达式字符串
- * @returns {boolean} 结果
- */
- function parseConditionExpression(expr) {
- // 去除空格
- expr = expr.trim();
-
- // 处理逻辑运算符(从低优先级到高优先级)
- // 先处理 ||
- if (expr.includes('||')) {
- const parts = expr.split('||').map(p => p.trim());
- return parts.some(part => parseConditionExpression(part));
- }
-
- // 处理 &&
- if (expr.includes('&&')) {
- const parts = expr.split('&&').map(p => p.trim());
- return parts.every(part => parseConditionExpression(part));
- }
-
- // 处理比较运算符
- const operators = [
- { op: '!=', fn: (a, b) => a != b },
- { op: '==', fn: (a, b) => {
- // 确保类型一致:如果一边是字符串,另一边也转为字符串
- if (typeof a === 'string' && typeof b !== 'string') {
- b = String(b);
- } else if (typeof b === 'string' && typeof a !== 'string') {
- a = String(a);
- }
- // 特殊处理:空字符串比较
- // 如果两边都是空字符串,直接返回 true
- if (a === '' && b === '') {
- return true;
- }
- // 特殊处理:如果一边是空字符串,另一边是 JSON 数组字符串,判断数组是否为空
- if ((a === '' && typeof b === 'string') || (b === '' && typeof a === 'string')) {
- const jsonStr = a === '' ? b : a;
- try {
- const parsed = JSON.parse(jsonStr);
- if (Array.isArray(parsed)) {
- return parsed.length === 0; // 空数组 == 空字符串
- }
- } catch (e) {
- // 不是 JSON,按普通比较
- }
- }
- return a == b;
- }},
- { op: '>=', fn: (a, b) => Number(a) >= Number(b) },
- { op: '<=', fn: (a, b) => Number(a) <= Number(b) },
- { op: '>', fn: (a, b) => Number(a) > Number(b) },
- { op: '<', fn: (a, b) => Number(a) < Number(b) }
- ];
-
- for (const { op, fn } of operators) {
- if (expr.includes(op)) {
- const parts = expr.split(op).map(p => p.trim());
- if (parts.length === 2) {
- const left = parseValue(parts[0]);
- const right = parseValue(parts[1]);
- // 调试:如果是 relationBg 相关的条件,输出调试信息
- if (expr.includes('relationBg')) {
- // 只在开发时输出,不影响生产
- }
- return fn(left, right);
- }
- }
- }
-
- // 如果没有运算符,尝试解析为布尔值
- const value = parseValue(expr);
- if (typeof value === 'boolean') return value;
- if (typeof value === 'string') {
- // 空字符串为false
- if (value === '' || value === 'undefined') return false;
- // 尝试解析 JSON 字符串,如果是空数组 "[]",返回 false
- try {
- const parsed = JSON.parse(value);
- if (Array.isArray(parsed)) {
- return parsed.length > 0;
- }
- // 如果是空对象 "{}",返回 false
- if (typeof parsed === 'object' && Object.keys(parsed).length === 0) {
- return false;
- }
- } catch (e) {
- // 不是 JSON,按普通字符串处理
- }
- // 非空字符串为true
- return true;
- }
- // 数字:0为false,非0为true
- if (typeof value === 'number') return value !== 0;
-
- return Boolean(value);
- }
- /**
- * 解析值(字符串、数字、布尔值)
- * @param {string} str - 字符串
- * @returns {any} 解析后的值
- */
- function parseValue(str) {
- str = str.trim();
-
- // 布尔值
- if (str === 'true') return true;
- if (str === 'false') return false;
-
- // 字符串(带引号)
- if ((str.startsWith('"') && str.endsWith('"')) ||
- (str.startsWith("'") && str.endsWith("'"))) {
- return str.slice(1, -1).replace(/\\"/g, '"').replace(/\\'/g, "'");
- }
-
- // 数字
- if (/^-?\d+(\.\d+)?$/.test(str)) {
- return parseFloat(str);
- }
-
- // undefined
- if (str === 'undefined') return undefined;
-
- // 默认返回字符串
- return str;
- }
- /**
- * 解析工作流格式(支持 variables, execute)
- * @param {Object} workflow - 工作流配置对象
- * @returns {Object} 解析后的工作流
- */
- function parseWorkflow(workflow) {
- if (!workflow || typeof workflow !== 'object') {
- return null;
- }
- // 初始化变量上下文(仅在未初始化时初始化,避免循环中重置)
- if (!variableContextInitialized) {
- variableContext = workflow.variables ? {} : {};
- if (workflow.variables) {
- // 转换变量类型:只允许 number 或 string
- for (const key in workflow.variables) {
- const value = workflow.variables[key];
- if (value === null || value === undefined) {
- variableContext[key] = ''; // null/undefined 转换为空字符串
- } else if (typeof value === 'boolean') {
- variableContext[key] = value ? '1' : '0'; // boolean 转换为字符串 '1' 或 '0'
- } else if (typeof value === 'number') {
- variableContext[key] = value; // number 保持不变
- } else if (typeof value === 'string') {
- variableContext[key] = value; // string 保持不变
- } else {
- variableContext[key] = String(value); // 其他类型转换为字符串
- }
- }
- }
- variableContextInitialized = true;
- } else {
- // 如果已初始化,只更新新增的变量(保留已有变量值)
- if (workflow.variables) {
- for (const key in workflow.variables) {
- // 如果变量已存在且不为空,则保留原值;否则使用新值
- if (variableContext[key] === undefined || variableContext[key] === null || variableContext[key] === '') {
- const value = workflow.variables[key];
- // 转换变量类型:只允许 number 或 string
- if (value === null || value === undefined) {
- variableContext[key] = ''; // null/undefined 转换为空字符串
- } else if (typeof value === 'boolean') {
- variableContext[key] = value ? '1' : '0'; // boolean 转换为字符串 '1' 或 '0'
- } else if (typeof value === 'number') {
- variableContext[key] = value; // number 保持不变
- } else if (typeof value === 'string') {
- variableContext[key] = value; // string 保持不变
- } else {
- variableContext[key] = String(value); // 其他类型转换为字符串
- }
- }
- }
- }
- }
-
- // 解析 execute 字段
- let actions = [];
-
- if (workflow.execute && Array.isArray(workflow.execute)) {
- actions = parseActions(workflow.execute);
- } else {
- // 如果没有 execute 字段,返回空数组
- actions = [];
- }
- // 处理 schedule 字段
- let schedule = workflow.schedule || {};
-
- // 如果 schedule 是数组,转换为对象格式(取第一个元素)
- if (Array.isArray(schedule)) {
- schedule = schedule.length > 0 ? schedule[0] : {};
- }
-
- // 如果 schedule 是对象但包含嵌套的 schedule 字段,提取内部对象
- if (schedule && typeof schedule === 'object' && schedule.schedule) {
- schedule = schedule.schedule;
- }
- // 处理 repeat 字段:将 "forever" 转换为 -1
- if (schedule && typeof schedule === 'object') {
- if (schedule.repeat === 'forever' || schedule.repeat === 'Forever') {
- schedule.repeat = -1;
- }
- }
- return {
- schedule: schedule,
- variables: variableContext,
- actions: actions
- };
- }
- /**
- * 解析操作数组(支持新旧格式)
- * @param {Array} actions - 操作数组
- * @returns {Array} 解析后的操作列表
- */
- function parseActions(actions) {
- if (!Array.isArray(actions)) {
- return [];
- }
- const parsedActions = [];
-
- for (const action of actions) {
- if (typeof action !== 'object' || action === null) {
- continue;
- }
- // 新格式:使用 type 字段
- if (action.type) {
- parsedActions.push(parseNewFormatAction(action));
- }
- // 旧格式:向后兼容
- else {
- parsedActions.push(parseOldFormatAction(action));
- }
- }
- return parsedActions;
- }
- /**
- * 解析新格式操作
- * @param {Object} action - 操作对象
- * @returns {Object} 解析后的操作
- */
- function parseNewFormatAction(action) {
- const parsed = {
- type: action.type,
- method: action.method,
- // target和value保留原始值,在执行时再解析(因为变量可能在执行时才被赋值)
- target: action.target,
- value: action.value,
- variable: action.variable,
- condition: action.condition,
- delay: action.delay || '',
- timeout: action.timeout,
- retry: action.retry
- };
- // 根据类型添加特定字段
- switch (action.type) {
- case 'adb':
- // 统一 ADB 操作,通过 method 区分
- parsed.method = action.method;
- // 支持新的 inVars/outVars 格式(都可以为空)
- if (action.inVars && Array.isArray(action.inVars)) {
- parsed.inVars = action.inVars.map(v => extractVarName(v));
- } else {
- parsed.inVars = [];
- }
- if (action.outVars && Array.isArray(action.outVars)) {
- parsed.outVars = action.outVars.map(v => extractVarName(v));
- } else {
- parsed.outVars = [];
- }
- // 向后兼容:保留旧字段
- parsed.target = action.target;
- parsed.value = action.value;
- parsed.variable = action.variable;
- parsed.clear = action.clear || false;
- break;
- case 'locate':
- // locate 操作(向后兼容)
- break;
- case 'click':
- // click 操作(向后兼容)
- break;
- case 'input':
- parsed.clear = action.clear || false;
- break;
- case 'ocr':
- parsed.area = action.area;
- parsed.avatar = resolveValue(action.avatar);
- break;
- case 'extract-messages':
- case 'ocr-chat':
- case 'ocr-chat-history': // 向后兼容
- case 'extract-chat-history': // 向后兼容
- // 支持新的 inVars/outVars 格式(都可以为空)
- if (action.inVars && Array.isArray(action.inVars)) {
- parsed.inVars = action.inVars.map(v => extractVarName(v));
- if (action.inVars.length >= 2) {
- parsed.avatar1 = action.inVars[0];
- parsed.avatar2 = action.inVars[1];
- } else if (action.inVars.length === 1) {
- parsed.avatar1 = action.inVars[0];
- parsed.avatar2 = action.avatar2;
- }
- } else {
- parsed.inVars = [];
- parsed.avatar1 = action.avatar1;
- parsed.avatar2 = action.avatar2;
- }
- if (action.outVars && Array.isArray(action.outVars)) {
- parsed.outVars = action.outVars.map(v => extractVarName(v));
- if (action.outVars.length > 0) {
- parsed.variable = extractVarName(action.outVars[0]);
- }
- } else {
- parsed.outVars = [];
- if (action.variable) {
- parsed.variable = extractVarName(action.variable);
- }
- }
- // 向后兼容:支持旧的 friendAvatar 和 myAvatar
- if (action.friendAvatar && !parsed.avatar1) parsed.avatar1 = action.friendAvatar;
- if (action.myAvatar && !parsed.avatar2) parsed.avatar2 = action.myAvatar;
- break;
- case 'save-messages':
- // 保存消息记录到文件
- break;
- case 'generate-summary':
- parsed.summaryVariable = action.summaryVariable;
- break;
- case 'ai-generate':
- parsed.prompt = resolveValue(action.prompt);
- parsed.model = action.model;
- // 支持新的 inVars/outVars 格式(都可以为空)
- if (action.inVars && Array.isArray(action.inVars)) {
- parsed.inVars = action.inVars.map(v => extractVarName(v));
- } else {
- parsed.inVars = [];
- }
- if (action.outVars && Array.isArray(action.outVars)) {
- parsed.outVars = action.outVars.map(v => extractVarName(v));
- if (action.outVars.length > 0) {
- parsed.variable = extractVarName(action.outVars[0]);
- }
- } else {
- parsed.outVars = [];
- if (action.variable) {
- parsed.variable = extractVarName(action.variable);
- }
- }
- break;
- case 'schedule':
- // schedule 操作:condition 定义调度条件,interval 定义要执行的动作
- parsed.condition = action.condition || {};
- // 处理 repeat 字段:将 "forever" 转换为 -1
- if (parsed.condition && typeof parsed.condition === 'object') {
- if (parsed.condition.repeat === 'forever' || parsed.condition.repeat === 'Forever') {
- parsed.condition.repeat = -1;
- }
- }
- // interval 字段包含要执行的动作数组
- if (action.interval && Array.isArray(action.interval)) {
- parsed.interval = parseActions(action.interval);
- } else {
- parsed.interval = [];
- }
- break;
- case 'if':
- // 支持 ture 作为 then 的别名(可能是拼写错误,但为了兼容性支持)
- parsed.then = action.then || action.ture ? parseActions(action.then || action.ture) : [];
- parsed.else = action.else ? parseActions(action.else) : [];
- break;
- case 'for':
- parsed.variable = action.variable;
- parsed.items = resolveValue(action.items);
- parsed.body = action.body ? parseActions(action.body) : [];
- break;
- case 'while':
- // 支持 ture 作为 body 的别名(可能是拼写错误,但为了兼容性支持)
- parsed.body = action.body || action.ture ? parseActions(action.body || action.ture) : [];
- break;
- case 'delay':
- parsed.value = action.value || action.delay || '0s';
- break;
- case 'set':
- parsed.variable = action.variable;
- parsed.value = resolveValue(action.value);
- break;
- case 'random':
- // 支持新格式:inVars[min, max] 和 outVars[{variable}]
- if (action.inVars && Array.isArray(action.inVars) && action.inVars.length >= 2) {
- parsed.min = action.inVars[0];
- parsed.max = action.inVars[1];
- } else {
- // 向后兼容旧格式
- parsed.min = action.min;
- parsed.max = action.max;
- }
-
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- parsed.variable = action.outVars[0];
- } else {
- // 向后兼容旧格式
- parsed.variable = action.variable;
- }
-
- // integer 默认为 true(随机数总是整数)
- parsed.integer = action.integer !== undefined ? action.integer : true;
- break;
- case 'log':
- // log 操作:支持 inVars 或 value 字段
- if (action.inVars && Array.isArray(action.inVars)) {
- parsed.inVars = action.inVars.map(v => extractVarName(v));
- } else {
- parsed.inVars = [];
- }
- // 支持 value 字段作为直接输出内容
- if (action.value) {
- parsed.value = action.value;
- }
- break;
- case 'read-last-message':
- // 支持新的 inVars/outVars 格式,也支持 inputVars/outputVars(大小写不同,都可以为空)
- const inputVars = action.inVars || action.inputVars || [];
- const outputVars = action.outVars || action.outputVars || [];
-
- parsed.inVars = inputVars.map(v => extractVarName(v));
- parsed.outVars = outputVars.map(v => extractVarName(v));
-
- if (inputVars.length > 0) {
- parsed.inputVar = extractVarName(inputVars[0]);
- }
- if (outputVars.length > 0) {
- parsed.textVariable = extractVarName(outputVars[0]);
- }
- if (outputVars.length > 1) {
- parsed.senderVariable = extractVarName(outputVars[1]);
- }
-
- // 向后兼容:支持旧的 textVariable 和 senderVariable
- if (!parsed.textVariable) parsed.textVariable = action.textVariable;
- if (!parsed.senderVariable) parsed.senderVariable = action.senderVariable;
- break;
- case 'read-txt':
- case 'read-text': // 向后兼容别名
- // 支持新的 inVars/outVars 格式
- if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 0) {
- parsed.inVars = action.inVars.map(v => extractVarName(v));
- parsed.filePath = action.inVars[0];
- } else {
- parsed.inVars = [];
- parsed.filePath = action.filePath;
- }
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- parsed.variable = extractVarName(action.outVars[0]);
- } else if (action.variable) {
- parsed.variable = extractVarName(action.variable);
- }
- break;
- case 'save-txt':
- case 'save-text': // 向后兼容别名
- // 支持新的 inVars/outVars 格式
- // 入参顺序:第一个参数是内容,第二个参数是文件路径
- if (action.inVars && Array.isArray(action.inVars)) {
- parsed.inVars = action.inVars.map(v => extractVarName(v));
- if (action.inVars.length > 0) {
- parsed.content = action.inVars[0]; // 第一个参数是内容
- }
- if (action.inVars.length > 1) {
- parsed.filePath = action.inVars[1]; // 第二个参数是文件路径
- }
- } else {
- parsed.inVars = [];
- parsed.filePath = action.filePath;
- parsed.content = action.content;
- }
- // save-txt 通常不需要 outVars,但为了兼容性支持
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- parsed.variable = extractVarName(action.outVars[0]);
- }
- break;
- case 'img-bounding-box-location':
- // 支持新的 inVars/outVars 格式(都可以为空)
- if (action.inVars && Array.isArray(action.inVars)) {
- parsed.inVars = action.inVars.map(v => extractVarName(v));
- // 如果 inVars 有值,从变量中读取 screenshot 和 region
- if (action.inVars.length > 0) parsed.screenshot = action.inVars[0];
- if (action.inVars.length > 1) parsed.region = action.inVars[1];
- } else {
- parsed.inVars = [];
- parsed.screenshot = action.screenshot;
- parsed.region = action.region;
- }
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- parsed.variable = extractVarName(action.outVars[0]);
- } else if (action.variable) {
- parsed.variable = extractVarName(action.variable);
- }
- break;
- case 'img-center-point-location':
- // 支持新的 inVars/outVars 格式(都可以为空)
- if (action.inVars && Array.isArray(action.inVars)) {
- parsed.inVars = action.inVars.map(v => extractVarName(v));
- // 如果 inVars 有值,从变量中读取 template
- if (action.inVars.length > 0) parsed.template = action.inVars[0];
- } else {
- parsed.inVars = [];
- parsed.template = action.template;
- }
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- parsed.variable = extractVarName(action.outVars[0]);
- } else if (action.variable) {
- parsed.variable = extractVarName(action.variable);
- }
- break;
- case 'img-cropping':
- // 支持新的 inVars/outVars 格式
- if (action.inVars && Array.isArray(action.inVars)) {
- parsed.inVars = action.inVars.map(v => extractVarName(v));
- // 如果 inVars 有值,从变量中读取 area 和 savePath
- if (action.inVars.length > 0) parsed.area = action.inVars[0];
- if (action.inVars.length > 1) parsed.savePath = action.inVars[1];
- } else {
- parsed.inVars = [];
- parsed.area = action.area;
- parsed.savePath = action.savePath;
- }
- // img-cropping 通常不需要 outVars,但为了兼容性支持
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- parsed.variable = extractVarName(action.outVars[0]);
- }
- break;
- case 'scroll':
- case 'swipe':
- case 'press':
- case 'string-press':
- case 'keyevent':
- // 保持原有逻辑(向后兼容)
- break;
- }
- return parsed;
- }
- /**
- * 解析旧格式操作(向后兼容)
- * @param {Object} action - 操作对象
- * @returns {Object} 解析后的操作
- */
- function parseOldFormatAction(action) {
- const times = action.times && action.times > 0 ? parseInt(action.times, 10) : 1;
- const data = action.data || '';
- const delay = action.delay || '';
- // 检查 press 操作
- if (action.press) {
- return {
- type: 'press',
- value: action.press,
- times: times,
- data: data,
- delay: delay,
- };
- }
- // 检查 input 操作
- else if (action.input !== undefined) {
- return {
- type: 'input',
- value: action.input,
- times: times,
- data: data,
- delay: delay,
- };
- }
- // 检查 swipe 操作
- else if (action.swipe) {
- const swipeValue = action.swipe;
- const validSwipeDirections = ['up-down', 'down-up', 'left-right', 'right-left'];
-
- if (!validSwipeDirections.includes(swipeValue)) {
- return null;
- }
-
- return {
- type: 'swipe',
- value: swipeValue,
- times: times,
- data: data,
- delay: delay,
- };
- }
- // 检查 string-press 操作
- else if (action['string-press']) {
- return {
- type: 'string-press',
- value: action['string-press'],
- times: times,
- data: data,
- delay: delay,
- };
- }
- // 检查 scroll 操作
- else if (action.scroll) {
- const scrollValue = action.scroll;
- const validScrollDirections = ['up-down', 'down-up', 'left-right', 'right-left'];
-
- if (!validScrollDirections.includes(scrollValue)) {
- return null;
- }
-
- return {
- type: 'scroll',
- value: scrollValue,
- times: times,
- data: data,
- delay: delay,
- };
- }
- else {
- return null;
- }
- }
- /**
- * 获取操作名称(用于显示)
- * @param {Object} action - 操作对象
- * @returns {string} 操作名称
- */
- function getActionName(action) {
- const typeNames = {
- 'schedule': '定时执行',
- 'adb': 'ADB操作',
- 'press': '点击图片',
- 'input': '输入文本',
- 'swipe': '滑动',
- 'string-press': '点击文字',
- 'scroll': '滚动',
- 'locate': '定位',
- 'click': '点击',
- 'ocr': '文字识别',
- 'extract-messages': '提取消息记录',
- 'save-messages': '保存消息记录',
- 'generate-summary': '生成总结',
- 'ocr-chat': 'OCR识别对话',
- // 向后兼容
- 'ocr-chat-history': 'OCR提取消息记录',
- 'extract-chat-history': '提取消息记录', // 向后兼容
- 'generate-history-summary': '生成总结',
- 'img-bounding-box-location': '图像区域定位',
- 'img-center-point-location': '图像中心点定位',
- 'img-cropping': '裁剪图片区域',
- 'read-last-message': '读取最后一条消息',
- 'read-txt': '读取文本文件',
- 'read-text': '读取文本文件', // 向后兼容别名
- 'save-txt': '保存文本文件',
- 'save-text': '保存文本文件', // 向后兼容别名
- 'smart-chat-append': '智能合并聊天记录',
- 'ai-generate': 'AI生成',
- 'if': '条件判断',
- 'for': '循环',
- 'while': '循环',
- 'delay': '延迟',
- 'set': '设置变量',
- 'random': '生成随机数',
- 'echo': '打印信息',
- 'log': '打印信息' // 向后兼容
- };
-
- const typeName = typeNames[action.type] || action.type;
- const value = action.value || action.target || '';
- const displayValue = typeof value === 'string' ? value : JSON.stringify(value);
-
- if (action.type === 'schedule') {
- const condition = action.condition || {};
- const interval = condition.interval || '0s';
- const repeat = condition.repeat !== undefined ? condition.repeat : 1;
- const repeatText = repeat === -1 ? '无限循环' : `重复${repeat}次`;
- return `${typeName}: ${interval}, ${repeatText}`;
- } else if (action.type === 'input') {
- return `${typeName}: ${displayValue.length > 20 ? displayValue.substring(0, 20) + '...' : displayValue}`;
- } else if (action.type === 'string-press' || action.type === 'click') {
- return `${typeName}: ${displayValue.length > 20 ? displayValue.substring(0, 20) + '...' : displayValue}`;
- } else if (action.type === 'if') {
- return `${typeName}: ${action.condition || ''}`;
- } else if (action.type === 'for') {
- return `${typeName}: ${action.variable || ''}`;
- } else if (action.type === 'set') {
- return `${typeName}: ${action.variable || ''}`;
- } else {
- return `${typeName}: ${displayValue}`;
- }
- }
- /**
- * 计算滑动操作的坐标
- * @param {string} direction - 滑动方向: up-down, down-up, left-right, right-left
- * @param {number} width - 设备宽度
- * @param {number} height - 设备高度
- * @returns {Object} 包含起始和结束坐标的对象 {x1, y1, x2, y2}
- */
- function calculateSwipeCoordinates(direction, width, height) {
- // 滑动距离为屏幕的 70%,起始和结束位置各留 15% 的边距
- const margin = 0.15;
- const swipeDistance = 0.7;
- let x1, y1, x2, y2;
- switch (direction) {
- case 'up-down':
- // 从上往下滑动
- x1 = x2 = Math.round(width / 2);
- y1 = Math.round(height * margin);
- y2 = Math.round(height * (margin + swipeDistance));
- break;
-
- case 'down-up':
- // 从下往上滑动
- x1 = x2 = Math.round(width / 2);
- y1 = Math.round(height * (margin + swipeDistance));
- y2 = Math.round(height * margin);
- break;
-
- case 'left-right':
- // 从左往右滑动
- y1 = y2 = Math.round(height / 2);
- x1 = Math.round(width * margin);
- x2 = Math.round(width * (margin + swipeDistance));
- break;
-
- case 'right-left':
- // 从右往左滑动
- y1 = y2 = Math.round(height / 2);
- x1 = Math.round(width * (margin + swipeDistance));
- x2 = Math.round(width * margin);
- break;
-
- default:
- throw new Error(`未知的滑动方向: ${direction}`);
- }
- return { x1, y1, x2, y2 };
- }
- /**
- * 执行单个操作
- * @param {Object} action - 操作对象
- * @param {string} device - 设备 ID
- * @param {string} folderPath - 文件夹路径(用于 press 操作查找图片)
- * @param {Object} resolution - 设备分辨率 {width, height}
- * @returns {Promise<Object>} 执行结果 {success, error?, result?}
- */
- async function executeAction(action, device, folderPath, resolution) {
- try {
- // 检查条件
- if (action.condition && !evaluateCondition(action.condition)) {
- return { success: true, skipped: true };
- }
- switch (action.type) {
- case 'adb': {
- // 统一 ADB 操作
- const method = action.method;
- if (!method) {
- return { success: false, error: 'adb 操作缺少 method 参数' };
- }
- // 从 inVars 读取参数
- const inVars = action.inVars || [];
- const outVars = action.outVars || [];
- switch (method) {
- case 'input': {
- // 输入文本:inVars[0] 是输入文本
- let inputValue = null;
- if (inVars.length > 0) {
- const inputVar = extractVarName(inVars[0]);
- inputValue = variableContext[inputVar];
- } else if (action.value) {
- inputValue = resolveValue(action.value);
- }
- if (!inputValue) {
- return { success: false, error: 'input 操作缺少输入内容' };
- }
- // 如果设置了clear,先清空输入框
- if (action.clear) {
- for (let i = 0; i < 200; i++) {
- const clearResult = await electronAPI.sendKeyEvent(device, '67');
- if (!clearResult.success) break;
- await new Promise(resolve => setTimeout(resolve, 10));
- }
- await new Promise(resolve => setTimeout(resolve, 200));
- }
- if (!electronAPI || !electronAPI.sendText) {
- return { success: false, error: '输入 API 不可用' };
- }
- const textResult = await electronAPI.sendText(device, String(inputValue));
- if (!textResult.success) {
- return { success: false, error: `输入失败: ${textResult.error}` };
- }
- return { success: true };
- }
- case 'click': {
- // 点击操作:inVars[0] 是位置(坐标对象或变量名)
- let position = null;
- if (inVars.length > 0) {
- const posVar = extractVarName(inVars[0]);
- position = variableContext[posVar];
- } else if (action.target) {
- position = resolveValue(action.target);
- }
- if (!position) {
- return { success: false, error: 'click 操作缺少位置参数' };
- }
- // 如果 position 是字符串,尝试解析为坐标对象
- if (typeof position === 'string') {
- if (position === '') {
- return { success: false, error: 'click 操作缺少位置参数(位置变量为空)' };
- }
- try {
- // 尝试解析 JSON 字符串(例如:{"x":123,"y":456})
- position = JSON.parse(position);
- } catch (e) {
- // 如果不是 JSON,可能是 "x,y" 格式,尝试解析
- const parts = position.split(',');
- if (parts.length === 2) {
- const x = parseFloat(parts[0].trim());
- const y = parseFloat(parts[1].trim());
- if (!isNaN(x) && !isNaN(y)) {
- position = { x: Math.round(x), y: Math.round(y) };
- } else {
- return { success: false, error: `click 操作的位置格式错误,无法解析字符串: ${position}` };
- }
- } else {
- return { success: false, error: `click 操作的位置格式错误,无法解析字符串: ${position}` };
- }
- }
- }
- // 如果 position 是数组 [x, y],转换为对象
- if (Array.isArray(position) && position.length >= 2) {
- position = { x: position[0], y: position[1] };
- }
- // 如果 position 是 corners 对象(四个顶点),计算中心点
- if (position && typeof position === 'object' && position.topLeft && position.bottomRight) {
- const centerX = Math.round((position.topLeft.x + position.bottomRight.x) / 2);
- const centerY = Math.round((position.topLeft.y + position.bottomRight.y) / 2);
- position = { x: centerX, y: centerY };
- }
- if (!position || typeof position !== 'object' || position.x === undefined || position.y === undefined) {
- return { success: false, error: 'click 操作的位置格式错误,需要 {x, y} 对象' };
- }
- if (!electronAPI || !electronAPI.sendTap) {
- return { success: false, error: '点击 API 不可用' };
- }
- const tapResult = await electronAPI.sendTap(device, position.x, position.y);
- if (!tapResult.success) {
- return { success: false, error: `点击失败: ${tapResult.error}` };
- }
- return { success: true };
- }
- case 'locate': {
- // 定位操作:inVars[0] 是目标(图片路径或文字),outVars[0] 保存位置
- // 支持通过 action.method 或 action.targetMethod 指定定位方法
- const locateMethod = action.method || action.targetMethod || 'image'; // image, text, coordinate
- let position = null;
- if (locateMethod === 'image') {
- let imagePath = null;
- if (inVars.length > 0) {
- const imageVar = extractVarName(inVars[0]);
- imagePath = variableContext[imageVar] || imageVar;
- } else if (action.target) {
- imagePath = action.target;
- }
- if (!imagePath) {
- return { success: false, error: 'locate 操作(image)缺少图片路径' };
- }
- // resources 作为根目录
- const fullPath = imagePath.startsWith('/') || imagePath.includes(':')
- ? imagePath
- : `${folderPath}/resources/${imagePath}`;
- if (!electronAPI || !electronAPI.matchImageAndGetCoordinate) {
- return { success: false, error: '图像匹配 API 不可用' };
- }
- const matchResult = await electronAPI.matchImageAndGetCoordinate(device, fullPath);
- if (!matchResult.success) {
- return { success: false, error: `图像匹配失败: ${matchResult.error}` };
- }
- position = matchResult.clickPosition;
- } else if (locateMethod === 'text') {
- let targetText = null;
- if (inVars.length > 0) {
- const textVar = extractVarName(inVars[0]);
- targetText = variableContext[textVar] || textVar;
- } else if (action.target) {
- targetText = action.target;
- }
- if (!targetText) {
- return { success: false, error: 'locate 操作(text)缺少文字内容' };
- }
- if (!electronAPI || !electronAPI.findTextAndGetCoordinate) {
- return { success: false, error: '文字识别 API 不可用' };
- }
- const matchResult = await electronAPI.findTextAndGetCoordinate(device, targetText);
- if (!matchResult.success) {
- return { success: false, error: `文字识别失败: ${matchResult.error}` };
- }
- position = matchResult.clickPosition;
- } else if (locateMethod === 'coordinate') {
- let coord = null;
- if (inVars.length > 0) {
- const coordVar = extractVarName(inVars[0]);
- coord = variableContext[coordVar];
- } else if (action.target) {
- coord = resolveValue(action.target);
- }
- if (!coord) {
- return { success: false, error: 'locate 操作(coordinate)缺少坐标' };
- }
- position = Array.isArray(coord) ? { x: coord[0], y: coord[1] } : coord;
- }
- // 保存到变量
- if (outVars.length > 0) {
- const outputVar = extractVarName(outVars[0]);
- variableContext[outputVar] = position;
- await logOutVars(action, variableContext, folderPath);
- } else if (action.variable) {
- variableContext[action.variable] = position;
- }
- return { success: true, result: position };
- }
- case 'swipe': {
- // 滑动操作:inVars[0] 是方向,inVars[1] 和 inVars[2] 可选(起始和结束位置)
- let direction = null;
- if (inVars.length > 0) {
- const dirVar = extractVarName(inVars[0]);
- direction = variableContext[dirVar] || dirVar;
- } else if (action.value) {
- direction = resolveValue(action.value);
- }
- if (!direction) {
- return { success: false, error: 'swipe 操作缺少方向参数' };
- }
- let x1, y1, x2, y2;
- if (inVars.length >= 3) {
- // 从 inVars 读取起始和结束位置
- const startVar = extractVarName(inVars[1]);
- const endVar = extractVarName(inVars[2]);
- const start = variableContext[startVar];
- const end = variableContext[endVar];
- if (start && end) {
- x1 = start.x || start[0];
- y1 = start.y || start[1];
- x2 = end.x || end[0];
- y2 = end.y || end[1];
- }
- }
- // 如果没有提供具体坐标,使用方向计算坐标
- if (x1 === undefined || y1 === undefined || x2 === undefined || y2 === undefined) {
- const coords = calculateSwipeCoordinates(direction, resolution.width, resolution.height);
- x1 = coords.x1;
- y1 = coords.y1;
- x2 = coords.x2;
- y2 = coords.y2;
- }
- if (!electronAPI || !electronAPI.sendSwipe) {
- return { success: false, error: '滑动 API 不可用' };
- }
- const swipeResult = await electronAPI.sendSwipe(device, x1, y1, x2, y2, 300);
- if (!swipeResult.success) {
- return { success: false, error: `滑动失败: ${swipeResult.error}` };
- }
- return { success: true };
- }
- case 'scroll': {
- // 滚动操作:inVars[0] 是方向
- let direction = null;
- if (inVars.length > 0) {
- const dirVar = extractVarName(inVars[0]);
- direction = variableContext[dirVar] || dirVar;
- } else if (action.value) {
- direction = resolveValue(action.value);
- }
- if (!direction) {
- return { success: false, error: 'scroll 操作缺少方向参数' };
- }
- if (!electronAPI || !electronAPI.sendScroll) {
- return { success: false, error: '滚动 API 不可用' };
- }
- const scrollResult = await electronAPI.sendScroll(
- device,
- direction,
- resolution.width,
- resolution.height,
- DEFAULT_SCROLL_DISTANCE,
- 500
- );
- if (!scrollResult.success) {
- return { success: false, error: `滚动失败: ${scrollResult.error}` };
- }
- return { success: true };
- }
- case 'keyevent': {
- // 按键操作:inVars[0] 是按键代码(如 "4" 表示返回键,"KEYCODE_BACK" 也可以)
- let keyCode = null;
- if (inVars.length > 0) {
- const keyVar = extractVarName(inVars[0]);
- keyCode = variableContext[keyVar] || keyVar;
- } else if (action.value) {
- keyCode = resolveValue(action.value);
- }
- if (!keyCode) {
- return { success: false, error: 'keyevent 操作缺少按键代码参数' };
- }
- // 如果是字符串 "KEYCODE_BACK",转换为 "4"
- if (keyCode === 'KEYCODE_BACK') {
- keyCode = '4';
- }
- if (!electronAPI || !electronAPI.sendSystemKey) {
- return { success: false, error: '系统按键 API 不可用' };
- }
- const keyResult = await electronAPI.sendSystemKey(device, String(keyCode));
- if (!keyResult.success) {
- return { success: false, error: `按键失败: ${keyResult.error}` };
- }
- return { success: true };
- }
- case 'press': {
- // 图像匹配并点击:inVars[0] 是图片路径
- let imagePath = null;
- if (inVars.length > 0) {
- const imageVar = extractVarName(inVars[0]);
- imagePath = variableContext[imageVar] || imageVar;
- } else if (action.value) {
- imagePath = action.value;
- }
- if (!imagePath) {
- return { success: false, error: 'press 操作缺少图片路径' };
- }
- const fullPath = imagePath.startsWith('/') || imagePath.includes(':')
- ? imagePath
- : `${folderPath}/${imagePath}`;
- if (!electronAPI || !electronAPI.matchImageAndGetCoordinate) {
- return { success: false, error: '图像匹配 API 不可用' };
- }
- const matchResult = await electronAPI.matchImageAndGetCoordinate(device, fullPath);
- if (!matchResult.success) {
- return { success: false, error: `图像匹配失败: ${matchResult.error}` };
- }
- const { clickPosition } = matchResult;
- const { x, y } = clickPosition;
- if (!electronAPI || !electronAPI.sendTap) {
- return { success: false, error: '点击 API 不可用' };
- }
- const tapResult = await electronAPI.sendTap(device, x, y);
- if (!tapResult.success) {
- return { success: false, error: `点击失败: ${tapResult.error}` };
- }
- return { success: true };
- }
- case 'string-press': {
- // 文字识别并点击:inVars[0] 是文字
- let targetText = null;
- if (inVars.length > 0) {
- const textVar = extractVarName(inVars[0]);
- targetText = variableContext[textVar] || textVar;
- } else if (action.value) {
- targetText = action.value;
- }
- if (!targetText) {
- return { success: false, error: 'string-press 操作缺少文字内容' };
- }
- if (!electronAPI || !electronAPI.findTextAndGetCoordinate) {
- return { success: false, error: '文字识别 API 不可用' };
- }
- const matchResult = await electronAPI.findTextAndGetCoordinate(device, targetText);
- if (!matchResult.success) {
- return { success: false, error: `文字识别失败: ${matchResult.error}` };
- }
- const { clickPosition } = matchResult;
- const { x, y } = clickPosition;
- if (!electronAPI || !electronAPI.sendTap) {
- return { success: false, error: '点击 API 不可用' };
- }
- const tapResult = await electronAPI.sendTap(device, x, y);
- if (!tapResult.success) {
- return { success: false, error: `点击失败: ${tapResult.error}` };
- }
- return { success: true };
- }
- default:
- return { success: false, error: `未知的 adb method: ${method}` };
- }
- }
- case 'locate': {
- // 定位操作
- const method = action.method || 'image';
- let position = null;
- if (method === 'image') {
- const imagePath = action.target.startsWith('/') || action.target.includes(':')
- ? action.target
- : `${folderPath}/${action.target}`;
-
- if (!electronAPI || !electronAPI.matchImageAndGetCoordinate) {
- return { success: false, error: '图像匹配 API 不可用' };
- }
- const matchResult = await electronAPI.matchImageAndGetCoordinate(device, imagePath);
- if (!matchResult.success) {
- return { success: false, error: `图像匹配失败: ${matchResult.error}` };
- }
- position = matchResult.clickPosition;
- } else if (method === 'text') {
- if (!electronAPI || !electronAPI.findTextAndGetCoordinate) {
- return { success: false, error: '文字识别 API 不可用' };
- }
- const matchResult = await electronAPI.findTextAndGetCoordinate(device, action.target);
- if (!matchResult.success) {
- return { success: false, error: `文字识别失败: ${matchResult.error}` };
- }
- position = matchResult.clickPosition;
- } else if (method === 'coordinate') {
- position = Array.isArray(action.target)
- ? { x: action.target[0], y: action.target[1] }
- : action.target;
- }
- // 保存到变量
- if (action.variable && position) {
- variableContext[action.variable] = position;
- }
- return { success: true, result: position };
- }
- case 'click': {
- // 点击操作
- const method = action.method || 'position';
- let position = null;
- if (method === 'position') {
- position = resolveValue(action.target);
- } else if (method === 'image') {
- const imagePath = action.target.startsWith('/') || action.target.includes(':')
- ? action.target
- : `${folderPath}/${action.target}`;
-
- if (!electronAPI || !electronAPI.matchImageAndGetCoordinate) {
- return { success: false, error: '图像匹配 API 不可用' };
- }
- const matchResult = await electronAPI.matchImageAndGetCoordinate(device, imagePath);
- if (!matchResult.success) {
- return { success: false, error: `图像匹配失败: ${matchResult.error}` };
- }
- position = matchResult.clickPosition;
- } else if (method === 'text') {
- if (!electronAPI || !electronAPI.findTextAndGetCoordinate) {
- return { success: false, error: '文字识别 API 不可用' };
- }
- const matchResult = await electronAPI.findTextAndGetCoordinate(device, action.target);
- if (!matchResult.success) {
- return { success: false, error: `文字识别失败: ${matchResult.error}` };
- }
- position = matchResult.clickPosition;
- }
- if (!position || !position.x || !position.y) {
- return { success: false, error: '无法获取点击位置' };
- }
- if (!electronAPI || !electronAPI.sendTap) {
- return { success: false, error: '点击 API 不可用' };
- }
- const tapResult = await electronAPI.sendTap(device, position.x, position.y);
- if (!tapResult.success) {
- return { success: false, error: `点击失败: ${tapResult.error}` };
- }
- return { success: true };
- }
- case 'press': {
- // 向后兼容:图像匹配并点击
- // resources 作为根目录
- const imagePath = `${folderPath}/resources/${action.value}`;
-
- if (!electronAPI || !electronAPI.matchImageAndGetCoordinate) {
- return { success: false, error: '图像匹配 API 不可用' };
- }
- const matchResult = await electronAPI.matchImageAndGetCoordinate(device, imagePath);
-
- if (!matchResult.success) {
- return { success: false, error: `图像匹配失败: ${matchResult.error}` };
- }
- const { clickPosition } = matchResult;
- const { x, y } = clickPosition;
- if (!electronAPI || !electronAPI.sendTap) {
- return { success: false, error: '点击 API 不可用' };
- }
- const tapResult = await electronAPI.sendTap(device, x, y);
-
- if (!tapResult.success) {
- return { success: false, error: `点击失败: ${tapResult.error}` };
- }
- return { success: true };
- }
- case 'input': {
- // 输入文本
- const inputStartTime = Date.now();
-
- // 先解析value(可能在运行时变量才被赋值,需要重新解析)
- let inputValue = resolveValue(action.value);
-
- // 如果value为空或undefined,且target存在,使用target(用于向后兼容,target可能也是定位文字)
- if (!inputValue && action.target) {
- // 如果target看起来像定位文字(不是变量引用),就不使用它
- const resolvedTarget = resolveValue(action.target);
- // 只有当target是变量引用时才使用它作为输入值
- if (resolvedTarget !== action.target || !action.target.includes(' ')) {
- inputValue = resolvedTarget;
- }
- }
-
- // 如果还是没有值,报错
- if (!inputValue) {
- return { success: false, error: '输入内容为空' };
- }
- // 如果target是定位方式,先定位输入框(暂未实现,直接输入文本)
- if (action.method === 'locate' && action.target) {
- // 这里可以添加定位输入框的逻辑
- // 暂时直接使用 sendText
- }
- if (!electronAPI || !electronAPI.sendText) {
- return { success: false, error: '输入 API 不可用' };
- }
- // 如果设置了clear,先清空输入框(通过发送退格键)
- if (action.clear) {
- // 发送退格键清空输入框(假设最多200个字符)
- // 使用Android的KEYCODE_DEL,值为67
- for (let i = 0; i < 200; i++) {
- const clearResult = await electronAPI.sendKeyEvent(device, '67');
- if (!clearResult.success) {
- break;
- }
- await new Promise(resolve => setTimeout(resolve, 10));
- }
- // 等待清空完成
- await new Promise(resolve => setTimeout(resolve, 200));
- }
- const textResult = await electronAPI.sendText(device, inputValue);
-
- if (!textResult.success) {
- return { success: false, error: `输入失败: ${textResult.error}` };
- }
- // 确保正确显示UTF-8编码的中文
- try {
- const displayValue = Buffer.isBuffer(inputValue)
- ? inputValue.toString('utf8')
- : String(inputValue);
- // 输入成功,不打印日志
- } catch (e) {
- // 输入成功,不打印日志
- }
- return { success: true };
- }
- case 'ocr': {
- // OCR识别
- if (!electronAPI || !electronAPI.ocrLastMessage) {
- return { success: false, error: 'OCR API 不可用' };
- }
- const method = action.method || 'full-screen';
- let avatarPath = null;
- const area = action.area;
- // 如果是by-avatar方法,需要获取头像路径
- if (method === 'by-avatar' && action.avatar) {
- const avatarName = resolveValue(action.avatar);
- if (avatarName) {
- // 头像路径:从工作流文件夹路径中提取文件夹名,然后拼接头像文件名
- // folderPath格式可能是:C:\...\static\processing\工作流名称
- // 我们需要传递:工作流名称/头像文件名
- const folderName = folderPath.split(/[/\\]/).pop();
- avatarPath = `${folderName}/${avatarName}`;
- }
- }
- // 调用OCR API,传递工作流文件夹路径
- const ocrResult = await electronAPI.ocrLastMessage(device, method, avatarPath, area, folderPath);
-
- if (!ocrResult.success) {
- return { success: false, error: `OCR识别失败: ${ocrResult.error}` };
- }
- // 保存识别结果到变量
- if (action.variable) {
- variableContext[action.variable] = ocrResult.text || '';
- // 确保正确显示UTF-8编码的中文
- const displayText = ocrResult.text || '';
- try {
- // 如果text是Buffer,转换为字符串
- const textStr = Buffer.isBuffer(displayText)
- ? displayText.toString('utf8')
- : String(displayText);
- // OCR识别结果已保存到变量
- } catch (e) {
- // 如果转换失败,直接输出
- // OCR识别结果已保存到变量
- }
- }
- return {
- success: true,
- text: ocrResult.text,
- position: ocrResult.position
- };
- }
- case 'extract-messages':
- case 'ocr-chat':
- case 'ocr-chat-history': // 向后兼容
- case 'extract-chat-history': { // 向后兼容
- // 提取消息记录
- // 获取头像路径(支持新的 inVars 格式,也支持旧参数 avatar1/avatar2 和 friendAvatar/myAvatar)
- const folderName = folderPath.split(/[/\\]/).pop();
- let avatar1Path = null;
- let avatar2Path = null;
- // 优先使用新的 inVars 格式
- let avatar1Name, avatar2Name, regionArea = null;
- let friendRgb = null, myRgb = null;
-
- if (action.inVars && Array.isArray(action.inVars)) {
- if (action.inVars.length >= 3) {
- // 三个参数:可能是 RGB格式 或 头像+区域格式
- const param1 = resolveValue(action.inVars[0]);
- const param2 = resolveValue(action.inVars[1]);
-
- // 检查是否是RGB格式(格式:"(r,g,b)")
- const rgbPattern = /^\((\d+),(\d+),(\d+)\)$/;
- if (typeof param1 === 'string' && rgbPattern.test(param1.trim()) &&
- typeof param2 === 'string' && rgbPattern.test(param2.trim())) {
- // RGB格式:第一个是好友RGB,第二个是我的RGB,第三个是区域
- friendRgb = param1.trim();
- myRgb = param2.trim();
-
- // 第三个参数是区域
- const regionVar = extractVarName(action.inVars[2]);
- regionArea = variableContext[regionVar];
- if (regionArea === undefined) {
- const regionResolved = resolveValue(action.inVars[2]);
- if (regionResolved && typeof regionResolved === 'object') {
- regionArea = regionResolved;
- }
- }
- } else {
- // 头像格式:头像1、头像2、区域
- avatar1Name = action.inVars[0];
- avatar2Name = action.inVars[1];
- const regionVar = extractVarName(action.inVars[2]);
- regionArea = variableContext[regionVar];
- if (regionArea === undefined) {
- const regionResolved = resolveValue(action.inVars[2]);
- if (regionResolved && typeof regionResolved === 'object') {
- regionArea = regionResolved;
- }
- }
- }
-
- // 验证区域格式
- if (regionArea) {
- if (typeof regionArea === 'string') {
- try {
- regionArea = JSON.parse(regionArea);
- } catch (e) {
- regionArea = null;
- }
- }
- if (regionArea && typeof regionArea === 'object') {
- if (!regionArea.topLeft || !regionArea.bottomRight) {
- regionArea = null;
- }
- }
- }
- } else if (action.inVars.length >= 2) {
- // 两个参数:可能是 RGB格式 或 头像格式
- const param1 = resolveValue(action.inVars[0]);
- const param2 = resolveValue(action.inVars[1]);
-
- // 检查是否是RGB格式
- const rgbPattern = /^\((\d+),(\d+),(\d+)\)$/;
- if (typeof param1 === 'string' && rgbPattern.test(param1.trim()) &&
- typeof param2 === 'string' && rgbPattern.test(param2.trim())) {
- // RGB格式:第一个是好友RGB,第二个是我的RGB
- friendRgb = param1.trim();
- myRgb = param2.trim();
- } else {
- // 头像格式:头像1、头像2(无区域,使用全屏)
- avatar1Name = action.inVars[0];
- avatar2Name = action.inVars[1];
- }
- } else if (action.inVars.length === 1) {
- // 一个参数:头像1(向后兼容)
- avatar1Name = action.inVars[0];
- avatar2Name = action.avatar2 || action.myAvatar;
- }
- } else {
- // 使用旧参数
- avatar1Name = action.avatar1 || action.friendAvatar;
- avatar2Name = action.avatar2 || action.myAvatar;
- }
- if (avatar1Name) {
- const avatar1Resolved = resolveValue(avatar1Name);
- if (avatar1Resolved) {
- // resources 作为根目录
- avatar1Path = `${folderName}/resources/${avatar1Resolved}`;
- }
- }
- if (avatar2Name) {
- const avatar2Resolved = resolveValue(avatar2Name);
- if (avatar2Resolved) {
- // resources 作为根目录
- avatar2Path = `${folderName}/resources/${avatar2Resolved}`;
- }
- }
- // 调用 Func 目录下的执行函数
- // 确保 regionArea 是对象格式(如果是字符串,尝试解析为 JSON)
- let regionParam = regionArea;
- if (regionArea && typeof regionArea === 'string') {
- try {
- regionParam = JSON.parse(regionArea);
- } catch (e) {
- // 解析失败,使用 null(函数内部会处理)
- regionParam = null;
- }
- }
-
- const chatResult = await executeOcrChat({
- device,
- avatar1: avatar1Path,
- avatar2: avatar2Path,
- folderPath,
- region: regionParam, // 传递区域参数(对象格式,如果提供)
- friendRgb: friendRgb, // 传递好友RGB(如果提供)
- myRgb: myRgb // 传递我的RGB(如果提供)
- });
-
- if (!chatResult.success) {
- return { success: false, error: `提取消息记录失败: ${chatResult.error}` };
- }
- // 保存消息记录到变量(支持新的 outVars 格式)
- let outputVarName = null;
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- outputVarName = extractVarName(action.outVars[0]);
- } else if (action.variable) {
- outputVarName = extractVarName(action.variable);
- }
- if (outputVarName) {
- // 使用JSON字符串格式的消息记录
- const messagesJson = chatResult.messagesJson || JSON.stringify(chatResult.messages || []);
- variableContext[outputVarName] = messagesJson;
- await logOutVars(action, variableContext, folderPath);
- }
- return {
- success: true,
- messages: chatResult.messages || [],
- messagesJson: chatResult.messagesJson || JSON.stringify(chatResult.messages || []),
- lastMessage: chatResult.messages && chatResult.messages.length > 0 ? chatResult.messages[chatResult.messages.length - 1] : null
- };
- }
- case 'ai-generate': {
- // AI生成
- let prompt = resolveValue(action.prompt);
-
- // 如果提供了 inVars,替换 prompt 中的变量
- if (action.inVars && Array.isArray(action.inVars)) {
- for (let i = 0; i < action.inVars.length; i++) {
- const varName = extractVarName(action.inVars[i]);
- const varValue = variableContext[varName];
-
- // 替换 prompt 中的变量占位符(例如 {currentMessage})
- if (varValue !== undefined && varValue !== null) {
- const placeholder = `{${varName}}`;
- // 检查是否是空数组 JSON 字符串
- let replaceValue = String(varValue);
- if (typeof varValue === 'string' && varValue.trim() === '[]') {
- try {
- const parsed = JSON.parse(varValue);
- if (Array.isArray(parsed) && parsed.length === 0) {
- replaceValue = '';
- }
- } catch (e) {
- // 不是 JSON,继续使用原值
- }
- }
- prompt = prompt.replace(new RegExp(placeholder.replace(/[{}]/g, '\\$&'), 'g'), replaceValue);
- }
- }
- }
-
- // 替换 prompt 中的变量(包括 historySummary 和其他变量)
- // 注意:这里需要先替换 historySummary,因为它可能包含在 prompt 模板中
- if (prompt.includes('{historySummary}')) {
- let historySummary = variableContext['historySummary'] || '';
-
- // 如果变量中没有历史总结,尝试从文件中读取
- if (!historySummary) {
- historySummary = await getHistorySummary(folderPath);
- // 如果从文件读取成功,也更新变量上下文
- if (historySummary) {
- variableContext['historySummary'] = historySummary;
- }
- }
-
- prompt = prompt.replace(/{historySummary}/g, historySummary);
- }
-
- // 替换 prompt 中所有剩余的变量占位符(支持 {{variable}} 和 {variable} 格式)
- prompt = replaceVariablesInString(prompt, variableContext);
-
- try {
- // 调用AI API(使用现有的GPT API)
- const requestBody = {
- prompt: prompt,
- modelName: action.model || 'gpt-5-nano-ca'
- };
-
- const response = await fetch('https://ai-anim.com/api/text2textByModel', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(requestBody)
- });
- if (!response.ok) {
- const errorText = await response.text();
- return { success: false, error: `AI请求失败: ${response.statusText}` };
- }
- const data = await response.json();
-
- // API 返回格式:{ success: true, data: { output_text: "..." } }
- // 或者:{ data: { output_text: "..." } }
- // 优先从 data.data.output_text 提取,然后是 data.output_text,最后是其他字段
- let rawResult = '';
- if (data.data && typeof data.data === 'object' && data.data.output_text) {
- rawResult = data.data.output_text;
- } else if (data.output_text) {
- rawResult = data.output_text;
- } else if (data.text) {
- rawResult = data.text;
- } else if (data.content) {
- rawResult = data.content;
- } else if (data.data && typeof data.data === 'string') {
- rawResult = data.data;
- } else {
- // 如果都没有,尝试从整个响应中提取
- rawResult = JSON.stringify(data);
- }
-
- // 确保 rawResult 是字符串
- rawResult = rawResult ? String(rawResult) : '';
-
- // 解析AI返回的JSON格式回复
- let result = rawResult;
- try {
- // 尝试从返回文本中提取JSON
- // 方法1: 尝试直接解析整个文本
- try {
- const jsonResult = JSON.parse(rawResult.trim());
- if (jsonResult.reply) {
- result = jsonResult.reply;
- }
- } catch (e) {
- // 方法2: 尝试从代码块中提取JSON
- const codeBlockMatch = rawResult.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
- if (codeBlockMatch) {
- try {
- const jsonResult = JSON.parse(codeBlockMatch[1]);
- if (jsonResult.reply) {
- result = jsonResult.reply;
- }
- } catch (e2) {
- // JSON解析失败,继续使用原始文本
- }
- } else {
- // 方法3: 尝试从文本中查找JSON对象
- const jsonMatch = rawResult.match(/\{\s*"reply"\s*:\s*"([^"]+)"\s*\}/);
- if (jsonMatch) {
- result = jsonMatch[1];
- } else {
- // 方法4: 尝试查找单行的JSON格式
- const lines = rawResult.split('\n').map(line => line.trim()).filter(line => line);
- for (const line of lines) {
- if (line.startsWith('{') && line.includes('"reply"')) {
- try {
- const jsonResult = JSON.parse(line);
- if (jsonResult.reply) {
- result = jsonResult.reply;
- break;
- }
- } catch (e3) {
- // 继续尝试下一行
- }
- }
- }
- }
- }
- }
- } catch (parseError) {
- // 如果解析失败,使用原始文本
- }
-
- // 保存到变量(支持 outVars 格式)
- // outVars[0] 是 AI 生成的结果,outVars[1](如果有)是 aiCallBack 变量
- if (action.outVars && Array.isArray(action.outVars)) {
- // 第一个输出变量保存 AI 生成结果
- if (action.outVars.length > 0) {
- const outputVarName = extractVarName(action.outVars[0]);
- if (outputVarName) {
- variableContext[outputVarName] = result;
- }
- }
- // 第二个输出变量(如果有)设置为 1 表示 AI 生成完成(aiCallBack)
- if (action.outVars.length > 1) {
- const callbackVarName = extractVarName(action.outVars[1]);
- if (callbackVarName) {
- variableContext[callbackVarName] = 1;
- }
- }
- await logOutVars(action, variableContext, folderPath);
- } else if (action.variable) {
- // 向后兼容:使用旧的 variable 字段
- const outputVarName = extractVarName(action.variable);
- if (outputVarName) {
- variableContext[outputVarName] = result;
- }
- }
-
- // 向后兼容:如果 aiCallBack 在 inVars 中提供,也设置它(但优先使用 outVars)
- if (!action.outVars || !Array.isArray(action.outVars) || action.outVars.length <= 1) {
- if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 1) {
- const callbackVarName = extractVarName(action.inVars[1]);
- if (callbackVarName) {
- variableContext[callbackVarName] = 1;
- }
- }
- }
- return { success: true, result };
- } catch (error) {
- return { success: false, error: `AI生成失败: ${error.message}` };
- }
- }
- case 'save-messages':
- case 'generate-summary':
- case 'generate-history-summary': { // 向后兼容
- // 生成消息记录的AI总结
- if (!action.variable) {
- return { success: false, error: '缺少变量名' };
- }
- const messages = variableContext[action.variable];
- if (!messages) {
- return { success: false, error: `变量 ${action.variable} 不存在或为空` };
- }
- const modelName = action.model || 'gpt-5-nano-ca';
- const result = await generateHistorySummary(messages, folderPath, modelName);
-
- if (!result.success) {
- return { success: false, error: `生成消息记录总结失败: ${result.error}` };
- }
- // 保存总结到变量
- if (action.summaryVariable) {
- variableContext[action.summaryVariable] = result.summary;
- // 消息记录总结已保存到变量
- }
- return { success: true, summary: result.summary };
- }
- case 'set': {
- // 设置变量
- if (action.variable) {
- const varName = extractVarName(action.variable);
- // 如果 value 是字符串且包含算术运算符,尝试计算表达式
- let finalValue = action.value;
- if (typeof action.value === 'string' && /[+\-*/]/.test(action.value)) {
- finalValue = evaluateExpression(action.value, variableContext);
- } else if (typeof action.value === 'string') {
- // 如果 value 是字符串,检查是否包含变量引用({variable} 格式)
- // 替换字符串中的所有变量引用
- const varPattern = /\{([\w-]+)\}/g;
- let hasVariables = false;
- finalValue = action.value.replace(varPattern, (match, varName) => {
- hasVariables = true;
- const value = variableContext[varName];
- if (value === undefined || value === null) {
- return match; // 如果变量不存在,保留原样
- }
- return String(value);
- });
- // 如果没有找到变量引用,使用 resolveValue 解析(处理单个变量引用的情况)
- if (!hasVariables) {
- finalValue = resolveValue(action.value, variableContext);
- }
- } else {
- // 否则使用 resolveValue 解析变量引用
- finalValue = resolveValue(action.value, variableContext);
- }
- variableContext[varName] = finalValue;
- }
- return { success: true };
- }
- case 'random': {
- // 生成随机数
- // 支持新格式:inVars[min, max] 和 outVars[{variable}]
- let varName, min, max;
-
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- varName = extractVarName(action.outVars[0]);
- } else if (action.variable) {
- // 向后兼容旧格式
- varName = extractVarName(action.variable);
- } else {
- return { success: false, error: 'random 操作缺少 variable 或 outVars 参数' };
- }
-
- if (action.inVars && Array.isArray(action.inVars) && action.inVars.length >= 2) {
- // 新格式:从 inVars 读取 min 和 max
- min = Number(action.inVars[0]);
- max = Number(action.inVars[1]);
- } else {
- // 向后兼容旧格式
- min = action.min !== undefined ? Number(action.min) : 0;
- max = action.max !== undefined ? Number(action.max) : 100;
- }
-
- const integer = action.integer !== undefined ? action.integer : true;
- if (isNaN(min) || isNaN(max)) {
- return { success: false, error: 'random 操作的 min 和 max 必须是数字' };
- }
- if (min > max) {
- return { success: false, error: 'random 操作的 min 不能大于 max' };
- }
- let randomValue;
- if (integer) {
- randomValue = Math.floor(Math.random() * (max - min + 1)) + min;
- } else {
- randomValue = Math.random() * (max - min) + min;
- }
- variableContext[varName] = randomValue;
- return { success: true };
- }
- case 'echo': {
- try {
- // 打印信息到 console.log、UI 和 log.txt 文件
- // 支持 inVars 或 value 字段
- let message = '';
-
- if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 0) {
- // 从 inVars 中读取变量值
- const messages = action.inVars.map(varWithBraces => {
- const varName = extractVarName(varWithBraces);
- const varValue = variableContext[varName];
- // 如果变量包含 {variable} 或 {{variable}} 格式,尝试解析为变量名
- if (varWithBraces.startsWith('{') && varWithBraces.endsWith('}')) {
- return varValue !== undefined ? String(varValue) : varWithBraces;
- }
- // 如果不是变量格式,直接使用原值
- return varWithBraces;
- });
- message = messages.join(' ');
- } else if (action.value) {
- // 使用 value 字段,支持变量替换(只支持 {{variable}} 格式,用于字符串拼接)
- // 先提取所有变量名,用于调试
- const doubleBracePattern = /\{\{([\w-]+)\}\}/g;
- const variablesInValue = [];
- let match;
- while ((match = doubleBracePattern.exec(action.value)) !== null) {
- variablesInValue.push(match[1]);
- }
-
- message = replaceVariablesInString(action.value, variableContext);
-
- // 如果消息为空或只包含原始变量格式,添加调试信息
- if (!message || message === action.value) {
- const missingVars = variablesInValue.filter(varName => {
- const varValue = variableContext[varName];
- return varValue === undefined || varValue === null || varValue === '';
- });
- if (missingVars.length > 0) {
- message = `${action.value} [变量未定义或为空: ${missingVars.join(', ')}]`;
- }
- }
- } else {
- // 如果没有提供任何内容,输出空字符串
- message = '';
- }
-
- // 输出到 console.log(仅限小红书随机浏览工作流)
- if (folderPath && folderPath.includes('小红书随机浏览工作流')) {
- console.log(message);
- }
-
- // 写入 log.txt 文件(只有 echo 类型写入文件)
- // 添加系统时间到消息中
- // 即使 message 为空也记录,以便调试
- 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');
- const hour = String(now.getHours()).padStart(2, '0');
- const minute = String(now.getMinutes()).padStart(2, '0');
- const second = String(now.getSeconds()).padStart(2, '0');
- const timeStr = `${year}/${month}/${day} ${hour}:${minute}:${second}`;
- const messageWithTime = message ? `${message} [系统时间: ${timeStr}]` : `[空消息] [系统时间: ${timeStr}]`;
- await logMessage(messageWithTime, folderPath);
-
- // 发送 log 消息事件到 UI
- const logEvent = new CustomEvent('log-message', {
- detail: {
- message: message
- }
- });
- window.dispatchEvent(logEvent);
-
- return { success: true };
- } catch (error) {
- // 如果 echo 执行出错,记录错误到 log.txt
- 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');
- const hour = String(now.getHours()).padStart(2, '0');
- const minute = String(now.getMinutes()).padStart(2, '0');
- const second = String(now.getSeconds()).padStart(2, '0');
- const timeStr = `${year}/${month}/${day} ${hour}:${minute}:${second}`;
- const errorMsg = `[错误] echo 执行失败: ${error.message} [系统时间: ${timeStr}]`;
- await logMessage(errorMsg, folderPath);
- return { success: false, error: `echo 执行失败: ${error.message}` };
- }
- }
- case 'log': { // 向后兼容,但不写入 log.txt
- // 打印信息到 console.log 和 UI(不写入 log.txt)
- // 支持 inVars 或 value 字段
- let message = '';
-
- if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 0) {
- // 从 inVars 中读取变量值
- const messages = action.inVars.map(varWithBraces => {
- const varName = extractVarName(varWithBraces);
- const varValue = variableContext[varName];
- // 如果变量包含 {variable} 或 {{variable}} 格式,尝试解析为变量名
- if (varWithBraces.startsWith('{') && varWithBraces.endsWith('}')) {
- return varValue !== undefined ? String(varValue) : varWithBraces;
- }
- // 如果不是变量格式,直接使用原值
- return varWithBraces;
- });
- message = messages.join(' ');
- } else if (action.value) {
- // 使用 value 字段,支持变量替换(只支持 {{variable}} 格式,用于字符串拼接)
- message = replaceVariablesInString(action.value, variableContext);
- } else {
- // 如果没有提供任何内容,输出空字符串
- message = '';
- }
-
- // 输出到 console.log(仅限小红书随机浏览工作流)
- if (folderPath && folderPath.includes('小红书随机浏览工作流')) {
- console.log(message);
- }
-
- // 注意:log 类型不写入 log.txt 文件,只发送到 UI
-
- // 发送 log 消息事件到 UI
- const logEvent = new CustomEvent('log-message', {
- detail: {
- message: message
- }
- });
- window.dispatchEvent(logEvent);
-
- return { success: true };
- }
- case 'img-bounding-box-location': {
- // 图像区域定位
- // 支持新的 inVars/outVars 格式(都可以为空)
- let screenshotPath = action.screenshot;
- let regionPath = action.region;
-
- // 如果提供了 inVars,从变量中读取或直接使用
- if (action.inVars && Array.isArray(action.inVars)) {
- if (action.inVars.length === 1) {
- // 如果只有一个参数,将其作为 region(区域图片)
- const firstVar = extractVarName(action.inVars[0]);
- const firstValue = variableContext[firstVar];
- if (firstValue && typeof firstValue === 'string' && !firstValue.includes('{')) {
- regionPath = firstValue;
- } else {
- // 如果变量不存在,直接使用 inVars[0] 作为路径
- regionPath = action.inVars[0];
- }
- // screenshot 需要自动从设备获取(传递 null)
- screenshotPath = null;
- } else if (action.inVars.length >= 2) {
- // 如果有两个参数,第一个是 screenshot,第二个是 region
- const screenshotVar = extractVarName(action.inVars[0]);
- const screenshotValue = variableContext[screenshotVar];
- if (screenshotValue && typeof screenshotValue === 'string' && !screenshotValue.includes('{')) {
- screenshotPath = screenshotValue;
- } else {
- screenshotPath = action.inVars[0];
- }
-
- const regionVar = extractVarName(action.inVars[1]);
- const regionValue = variableContext[regionVar];
- if (regionValue && typeof regionValue === 'string' && !regionValue.includes('{')) {
- regionPath = regionValue;
- } else {
- regionPath = action.inVars[1];
- }
- }
- }
-
- // 如果没有提供路径,使用默认值或从 action 中读取
- if (screenshotPath !== null && !screenshotPath) screenshotPath = action.screenshot;
- if (!regionPath) regionPath = action.region;
-
- if (!regionPath) {
- return { success: false, error: '缺少区域截图路径' };
- }
-
- // 如果 screenshotPath 为 null,需要自动从设备获取
- if (screenshotPath === null && !device) {
- return { success: false, error: '缺少完整截图路径,且无法自动获取设备截图(缺少设备ID)' };
- }
- // 调用 Func 目录下的执行函数
- const result = await executeImgBoundingBoxLocation({
- device,
- screenshot: screenshotPath,
- region: regionPath,
- folderPath
- });
- if (!result.success) {
- return { success: false, error: `图像区域定位失败: ${result.error}` };
- }
- // 保存结果到变量(支持 outVars 格式)
- // img-bounding-box-location 返回四个顶点坐标
- let outputVarName = null;
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- outputVarName = extractVarName(action.outVars[0]);
- } else if (action.variable) {
- outputVarName = extractVarName(action.variable);
- }
-
- if (outputVarName) {
- // 将对象转换为 JSON 字符串(只允许 string 或 int 类型)
- if (result.corners && typeof result.corners === 'object') {
- variableContext[outputVarName] = JSON.stringify(result.corners);
- } else {
- variableContext[outputVarName] = '';
- }
- // 图像区域定位结果已保存到变量
- await logOutVars(action, variableContext, folderPath);
- }
- return { success: true, result: result.corners };
- }
- case 'img-center-point-location': {
- // 图像中心点定位
- // 支持新的 inVars/outVars 格式(都可以为空)
- let templatePath = action.template;
-
- // 如果提供了 inVars,从变量中读取或直接使用
- if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 0) {
- const templateVar = extractVarName(action.inVars[0]);
- const templateValue = variableContext[templateVar];
- if (templateValue && typeof templateValue === 'string' && !templateValue.includes('{')) {
- templatePath = templateValue;
- } else {
- // 如果变量不存在,直接使用 inVars[0] 作为路径
- templatePath = action.inVars[0];
- }
- }
-
- // 如果没有提供路径,使用默认值或从 action 中读取
- if (!templatePath) templatePath = action.template;
-
- if (!templatePath) {
- return { success: false, error: '缺少模板图片路径' };
- }
-
- if (!device) {
- return { success: false, error: '缺少设备 ID,无法自动获取截图' };
- }
- // 调用 Func 目录下的执行函数
- const result = await executeImgCenterPointLocation({
- device,
- template: templatePath,
- folderPath
- });
- if (!result.success) {
- return { success: false, error: `图像中心点定位失败: ${result.error}` };
- }
- // 保存结果到变量(支持 outVars 格式)
- let outputVarName = null;
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- outputVarName = extractVarName(action.outVars[0]);
- } else if (action.variable) {
- outputVarName = extractVarName(action.variable);
- }
-
- if (outputVarName) {
- // 保存中心点坐标为字符串(JSON 格式):只允许 number 或 string
- if (result.center && typeof result.center === 'object' && result.center.x !== undefined && result.center.y !== undefined) {
- variableContext[outputVarName] = JSON.stringify({ x: result.center.x, y: result.center.y });
- } else {
- variableContext[outputVarName] = '';
- }
- // 图像中心点定位结果已保存到变量
- await logOutVars(action, variableContext, folderPath);
- }
- return { success: true, result: result.center };
- }
- case 'img-cropping': {
- // 裁剪图片区域
- // 支持新的 inVars 格式
- let area = action.area;
- let savePath = action.savePath;
-
- // 如果提供了 inVars,从变量中读取或直接使用
- if (action.inVars && Array.isArray(action.inVars)) {
- if (action.inVars.length > 0) {
- const areaVar = extractVarName(action.inVars[0]);
- const areaValue = variableContext[areaVar];
- if (areaValue !== undefined) {
- area = areaValue;
- } else {
- area = resolveValue(action.inVars[0]);
- }
- }
-
- if (action.inVars.length > 1) {
- const savePathVar = extractVarName(action.inVars[1]);
- const savePathValue = variableContext[savePathVar];
- if (savePathValue !== undefined) {
- savePath = savePathValue;
- } else {
- savePath = resolveValue(action.inVars[1]);
- }
- }
- }
- if (!area) {
- return { success: false, error: 'img-cropping 缺少 area 参数' };
- }
- if (!savePath) {
- return { success: false, error: 'img-cropping 缺少 savePath 参数' };
- }
- const result = await executeImgCropping({
- area,
- savePath,
- folderPath,
- device // 传递设备ID,用于获取最新截图
- });
- if (!result.success) {
- // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
- return { success: false, error: result.error };
- }
-
- // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
- // 如果提供了 outVars,可以将结果保存到变量
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- const outputVarName = extractVarName(action.outVars[0]);
- if (outputVarName) {
- // 只允许 string 或 int 类型,保存成功标志为 "1" 或 1
- variableContext[outputVarName] = result.success ? '1' : '0';
- }
- }
- await logOutVars(action, variableContext, folderPath);
- return { success: true };
- }
- case 'read-last-message': {
- // 读取最后一条消息
- // 支持新的 inVars/outVars 格式,也支持 inputVars/outputVars
- const inputVars = action.inVars || action.inputVars || [];
- const outputVars = action.outVars || action.outputVars || [];
-
- let textVar = action.textVariable;
- let senderVar = action.senderVariable;
- let inputVar = null;
-
- if (outputVars.length > 0) {
- textVar = extractVarName(outputVars[0]);
- }
- if (outputVars.length > 1) {
- senderVar = extractVarName(outputVars[1]);
- }
- if (inputVars.length > 0) {
- inputVar = extractVarName(inputVars[0]);
- }
-
- if (!textVar && !senderVar) {
- return { success: false, error: 'read-last-message 缺少 textVariable 或 senderVariable 参数' };
- }
- // 如果提供了 inputVar,从变量中读取数据
- let inputData = null;
- if (inputVar && variableContext[inputVar] !== undefined) {
- inputData = variableContext[inputVar];
- }
- // 确保 inputData 是字符串类型(如果是对象或数组,转换为 JSON 字符串)
- let inputDataString = inputData;
- if (inputData !== null && inputData !== undefined) {
- if (typeof inputData === 'string') {
- inputDataString = inputData;
- } else if (Array.isArray(inputData) || typeof inputData === 'object') {
- inputDataString = JSON.stringify(inputData);
- } else {
- inputDataString = String(inputData);
- }
- } else {
- inputDataString = null; // null 表示从文件读取
- }
-
- const result = await executeReadLastMessage({
- folderPath,
- inputData: inputDataString, // 确保是字符串类型,如果为 null,则从 history 文件夹读取
- textVariable: textVar,
- senderVariable: senderVar
- });
- if (!result.success) {
- return { success: false, error: result.error };
- }
- // 保存消息文本和发送者到变量
- if (textVar) {
- variableContext[textVar] = result.text;
- // 最后一条消息文本已保存到变量
- }
- if (senderVar) {
- variableContext[senderVar] = result.sender;
- // 最后一条消息发送者已保存到变量
- }
- await logOutVars(action, variableContext, folderPath);
- return { success: true, text: result.text, sender: result.sender };
- }
- case 'read-txt':
- case 'read-text': { // 向后兼容别名
- // 读取根目录下的文本文件
- // 支持新的 inVars/outVars 格式
- let filePath = action.filePath;
- let varName = action.variable;
- if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 0) {
- // 从 inVars 读取文件路径(可能是变量或直接路径)
- const filePathVar = extractVarName(action.inVars[0]);
- const filePathValue = variableContext[filePathVar];
- if (filePathValue !== undefined) {
- filePath = filePathValue;
- } else {
- filePath = resolveValue(action.inVars[0]);
- }
- }
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- varName = extractVarName(action.outVars[0]);
- } else if (action.variable) {
- varName = extractVarName(action.variable);
- }
- if (!filePath) {
- return { success: false, error: 'read-txt 缺少 filePath 参数' };
- }
- if (!varName) {
- return { success: false, error: 'read-txt 缺少 variable 参数' };
- }
- const result = await executeReadTxt({
- filePath,
- folderPath
- });
- if (!result.success) {
- return { success: false, error: result.error };
- }
- // 保存文件内容到变量(确保始终是字符串类型,即使是空字符串)
- const content = result.content || '';
- variableContext[varName] = typeof content === 'string' ? content : String(content);
- // 确保变量始终是字符串类型(即使是空字符串)
- if (variableContext[varName] === undefined || variableContext[varName] === null) {
- variableContext[varName] = '';
- }
- await logOutVars(action, variableContext, folderPath);
- return { success: true, content: result.content };
- }
- case 'smart-chat-append': {
- // 智能合并历史聊天记录和当前聊天记录,自动检测并去除连续重合部分后返回新的聊天记录字符串
- // 支持新的 inVars/outVars 格式
- let history = action.history;
- let current = action.current;
- if (action.inVars && Array.isArray(action.inVars)) {
- // 从 inVars 读取历史记录和当前记录(可能是变量或直接值)
- if (action.inVars.length > 0) {
- const historyVar = extractVarName(action.inVars[0]);
- const historyValue = variableContext[historyVar];
- if (historyValue !== undefined) {
- history = historyValue;
- } else {
- history = resolveValue(action.inVars[0]);
- }
- }
-
- if (action.inVars.length > 1) {
- const currentVar = extractVarName(action.inVars[1]);
- const currentValue = variableContext[currentVar];
- if (currentValue !== undefined) {
- current = currentValue;
- } else {
- current = resolveValue(action.inVars[1]);
- }
- }
- }
- if (history === undefined || history === null) {
- history = '';
- }
- if (current === undefined || current === null) {
- current = '';
- }
- const result = await executeSmartChatAppend({
- history: typeof history === 'string' ? history : String(history),
- current: typeof current === 'string' ? current : String(current)
- });
- if (!result.success) {
- return { success: false, error: result.error };
- }
- // 保存结果到变量
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- const outputVarName = extractVarName(action.outVars[0]);
- if (outputVarName && result.result) {
- variableContext[outputVarName] = result.result;
- }
- } else if (action.variable) {
- const varName = extractVarName(action.variable);
- if (varName && result.result) {
- variableContext[varName] = result.result;
- }
- }
- return { success: true, result: result.result };
- }
- case 'save-txt':
- case 'save-text': { // 向后兼容别名
- // 保存字符串为文本文件
- // 支持新的 inVars/outVars 格式
- let filePath = action.filePath;
- let content = action.content;
- if (action.inVars && Array.isArray(action.inVars)) {
- // 从 inVars 读取内容和文件路径(可能是变量或直接值)
- // 入参顺序:第一个参数是内容,第二个参数是文件路径
- if (action.inVars.length > 0) {
- // 第一个参数是内容
- const contentVar = extractVarName(action.inVars[0]);
- const contentValue = variableContext[contentVar];
- if (contentValue !== undefined) {
- content = contentValue;
- } else {
- content = resolveValue(action.inVars[0]);
- }
- }
-
- if (action.inVars.length > 1) {
- // 第二个参数是文件路径
- const filePathVar = extractVarName(action.inVars[1]);
- const filePathValue = variableContext[filePathVar];
- if (filePathValue !== undefined) {
- filePath = filePathValue;
- } else {
- filePath = resolveValue(action.inVars[1]);
- }
- }
- }
- if (!filePath) {
- return { success: false, error: 'save-txt 缺少 filePath 参数' };
- }
- if (content === undefined || content === null) {
- return { success: false, error: 'save-txt 缺少 content 参数' };
- }
- const result = await executeSaveTxt({
- filePath,
- content,
- folderPath
- });
- if (!result.success) {
- return { success: false, error: result.error };
- }
- // 如果提供了 outVars,可以将结果保存到变量(虽然通常不需要)
- if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
- const outputVarName = extractVarName(action.outVars[0]);
- if (outputVarName) {
- // 只允许 string 或 int 类型,保存成功标志为 "1" 或 1
- variableContext[outputVarName] = result.success ? '1' : '0';
- }
- }
- await logOutVars(action, variableContext, folderPath);
- return { success: true };
- }
- case 'delay': {
- // 延迟
- const delayMs = parseDelayString(action.value || action.delay || '0s');
- if (delayMs > 0) {
- await new Promise(resolve => setTimeout(resolve, delayMs));
- }
- return { success: true };
- }
- case 'swipe': {
- // 滑动操作
- if (!electronAPI || !electronAPI.sendSwipe) {
- return { success: false, error: '滑动 API 不可用' };
- }
- const { x1, y1, x2, y2 } = calculateSwipeCoordinates(
- action.value,
- resolution.width,
- resolution.height
- );
- const swipeResult = await electronAPI.sendSwipe(device, x1, y1, x2, y2, 300);
-
- if (!swipeResult.success) {
- return { success: false, error: `滑动失败: ${swipeResult.error}` };
- }
- // 成功滑动
- return { success: true };
- }
- case 'string-press': {
- // 向后兼容:文字识别并点击
- if (!electronAPI || !electronAPI.findTextAndGetCoordinate) {
- return { success: false, error: '文字识别 API 不可用' };
- }
- const matchResult = await electronAPI.findTextAndGetCoordinate(device, action.value);
-
- if (!matchResult.success) {
- return { success: false, error: `文字识别失败: ${matchResult.error}` };
- }
- const { clickPosition } = matchResult;
- const { x, y } = clickPosition;
- if (!electronAPI || !electronAPI.sendTap) {
- return { success: false, error: '点击 API 不可用' };
- }
- const tapResult = await electronAPI.sendTap(device, x, y);
-
- if (!tapResult.success) {
- return { success: false, error: `点击失败: ${tapResult.error}` };
- }
- // 成功点击文字
- return { success: true };
- }
- case 'scroll': {
- // 滚动操作(小幅度滚动)
- if (!electronAPI || !electronAPI.sendScroll) {
- return { success: false, error: '滚动 API 不可用' };
- }
- const scrollResult = await electronAPI.sendScroll(
- device,
- action.value,
- resolution.width,
- resolution.height,
- DEFAULT_SCROLL_DISTANCE,
- 500
- );
-
- if (!scrollResult.success) {
- return { success: false, error: `滚动失败: ${scrollResult.error}` };
- }
- // 成功滚动
- return { success: true };
- }
- default:
- return { success: false, error: `未知的操作类型: ${action.type}` };
- }
- } catch (error) {
- // 记录错误到 log.txt
- 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');
- const hour = String(now.getHours()).padStart(2, '0');
- const minute = String(now.getMinutes()).padStart(2, '0');
- const second = String(now.getSeconds()).padStart(2, '0');
- const timeStr = `${year}/${month}/${day} ${hour}:${minute}:${second}`;
- const errorMsg = `[错误] 操作执行失败: ${error.message} [系统时间: ${timeStr}]`;
- await logMessage(errorMsg, folderPath).catch(() => {
- // 静默失败,不影响主流程
- });
- return { success: false, error: error.message };
- }
- }
- /**
- * 执行操作序列(支持嵌套和条件)
- * @param {Array} actions - 解析后的操作列表
- * @param {string} device - 设备 ID
- * @param {string} folderPath - 文件夹路径
- * @param {Object} resolution - 设备分辨率
- * @param {number} stepInterval - 步骤间隔时间(毫秒),默认1秒
- * @param {Function} onStepComplete - 每步完成后的回调函数
- * @param {Function} shouldStop - 检查是否应该停止的函数
- * @param {number} depth - 嵌套深度(用于递归)
- * @returns {Promise<Object>} 执行结果 {success, error?, completedSteps}
- */
- async function executeActionSequence(
- actions,
- device,
- folderPath,
- resolution,
- stepInterval = DEFAULT_STEP_INTERVAL,
- onStepComplete = null,
- shouldStop = null,
- depth = 0
- ) {
- // 如果是顶层(depth === 0),重置全局步骤计数器和变量初始化标志
- if (depth === 0) {
- globalStepCounter = 0;
- // 重置变量初始化标志,允许在新工作流开始时重新初始化
- variableContextInitialized = false;
- // 保存当前工作流文件夹路径,用于日志记录
- currentWorkflowFolderPath = folderPath;
- // 添加分割线,分开每次执行的日志
- await logMessage('========================', folderPath);
- }
-
- let completedSteps = 0;
- const stepPrefix = depth > 0 ? ' '.repeat(depth) : '';
- for (let i = 0; i < actions.length; i++) {
- // 检查是否应该停止
- if (shouldStop && shouldStop()) {
- // 执行被停止
- return { success: false, error: '执行被停止', completedSteps };
- }
- const action = actions[i];
-
- // 处理特殊操作类型
- if (action.type === 'schedule') {
- // schedule 操作:根据 condition 中的 interval 和 repeat 执行动作
- const condition = action.condition || {};
- const intervalStr = condition.interval || '0s';
- const repeat = condition.repeat !== undefined ? condition.repeat : 1;
- const actionsToExecute = action.interval || [];
-
- // 解析间隔时间
- const intervalMs = parseDelayString(intervalStr) || 0;
-
- // 确定循环次数(-1 表示无限循环)
- const maxIterations = repeat === -1 ? Infinity : (typeof repeat === 'number' ? repeat : 1);
- let iteration = 0;
-
- while (iteration < maxIterations) {
- if (shouldStop && shouldStop()) {
- return { success: false, error: '执行被停止', completedSteps };
- }
-
- iteration++;
-
- // 如果不是第一次迭代,等待间隔时间
- if (iteration > 1 && intervalMs > 0) {
- // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
- let remainingTime = intervalMs;
- const countdownInterval = 100;
-
- while (remainingTime > 0) {
- if (shouldStop && shouldStop()) {
- return { success: false, error: '执行被停止', completedSteps };
- }
- const waitTime = Math.min(countdownInterval, remainingTime);
- await new Promise(resolve => setTimeout(resolve, waitTime));
- remainingTime -= waitTime;
- }
- }
-
- // 执行动作序列
- if (actionsToExecute.length > 0) {
- const result = await executeActionSequence(
- actionsToExecute,
- device,
- folderPath,
- resolution,
- stepInterval,
- onStepComplete,
- shouldStop,
- depth + 1
- );
-
- if (!result.success) {
- return result;
- }
- completedSteps += result.completedSteps || 0;
- }
- }
-
- continue;
- }
- if (action.type === 'if') {
- const conditionResult = evaluateCondition(action.condition);
-
- // 支持 ture(拼写错误)和 false 作为 then 和 else 的别名
- const actionsToExecute = conditionResult ? (action.then || action.ture || []) : (action.else || action.false || []);
-
- if (actionsToExecute.length > 0) {
- const result = await executeActionSequence(
- actionsToExecute,
- device,
- folderPath,
- resolution,
- stepInterval,
- onStepComplete,
- shouldStop,
- depth + 1
- );
-
- if (!result.success) {
- return result;
- }
- completedSteps += result.completedSteps || 0;
- }
- continue;
- }
- if (action.type === 'for') {
- const items = Array.isArray(action.items) ? action.items : [];
-
- for (const item of items) {
- if (shouldStop && shouldStop()) {
- return { success: false, error: '执行被停止', completedSteps };
- }
- // 设置循环变量
- if (action.variable) {
- variableContext[action.variable] = item;
- }
- if (action.body && action.body.length > 0) {
- const result = await executeActionSequence(
- action.body,
- device,
- folderPath,
- resolution,
- stepInterval,
- onStepComplete,
- shouldStop,
- depth + 1
- );
-
- if (!result.success) {
- return result;
- }
- completedSteps += result.completedSteps || 0;
- }
- }
- continue;
- }
- if (action.type === 'while') {
- while (evaluateCondition(action.condition)) {
- if (shouldStop && shouldStop()) {
- return { success: false, error: '执行被停止', completedSteps };
- }
- if (action.body && action.body.length > 0) {
- const result = await executeActionSequence(
- action.body,
- device,
- folderPath,
- resolution,
- stepInterval,
- onStepComplete,
- shouldStop,
- depth + 1
- );
-
- if (!result.success) {
- return result;
- }
- completedSteps += result.completedSteps || 0;
- }
- }
- continue;
- }
- // 普通操作
- const times = action.times || 1;
-
- // 发送步骤开始执行事件
- if (onStepComplete) {
- const stepName = getActionName(action);
- onStepComplete(i + 1, actions.length, stepName, 0, times, 0);
- }
-
- // 计算等待时间(根据 data 和 delay)
- const waitTime = calculateWaitTime(action.data, action.delay);
-
- if (waitTime > 0) {
- const waitSeconds = Math.round(waitTime / 1000);
- // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
-
- // 在等待期间也更新倒计时
- let remainingTime = waitTime;
- const countdownInterval = 100;
- const stepName = getActionName(action);
-
- while (remainingTime > 0) {
- if (shouldStop && shouldStop()) {
- return { success: false, error: '执行被停止', completedSteps };
- }
-
- if (onStepComplete) {
- onStepComplete(i + 1, actions.length, stepName, remainingTime, times, 0);
- }
-
- const waitTimeChunk = Math.min(countdownInterval, remainingTime);
- await new Promise(resolve => setTimeout(resolve, waitTimeChunk));
- remainingTime -= waitTimeChunk;
- }
- }
- // 根据 times 重复执行操作
- for (let t = 0; t < times; t++) {
- // 检查是否应该停止
- if (shouldStop && shouldStop()) {
- // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
- return { success: false, error: '执行被停止', completedSteps };
- }
- // 发送步骤执行中事件(包含当前执行次数)
- if (onStepComplete) {
- const stepName = getActionName(action);
- onStepComplete(i + 1, actions.length, stepName, 0, times, t + 1);
- }
- // 使用全局步骤计数器
- globalStepCounter++;
- const currentStepNumber = globalStepCounter;
-
- // 记录步骤开始时间
- const stepStartTime = Date.now();
- const startTimeStr = new Date(stepStartTime).toLocaleString('zh-CN', {
- year: 'numeric',
- month: '2-digit',
- day: '2-digit',
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit',
- hour12: false
- });
-
- // 获取操作类型名称
- const typeName = getActionName(action);
-
- // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
- // 执行操作
- const result = await executeAction(action, device, folderPath, resolution);
- // 记录步骤结束时间
- const stepEndTime = Date.now();
- const endTimeStr = new Date(stepEndTime).toLocaleString('zh-CN', {
- year: 'numeric',
- month: '2-digit',
- day: '2-digit',
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit',
- hour12: false
- });
- const stepDuration = (stepEndTime - stepStartTime) / 1000; // 转换为秒
-
- // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
- if (!result.success) {
- // 记录错误到 log.txt
- 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');
- const hour = String(now.getHours()).padStart(2, '0');
- const minute = String(now.getMinutes()).padStart(2, '0');
- const second = String(now.getSeconds()).padStart(2, '0');
- const timeStr = `${year}/${month}/${day} ${hour}:${minute}:${second}`;
- const errorMsg = `[错误] ${getActionName(action)} 执行失败: ${result.error} [系统时间: ${timeStr}]`;
- await logMessage(errorMsg, folderPath).catch(() => {
- // 静默失败,不影响主流程
- });
- return { success: false, error: result.error, completedSteps: i };
- }
- // 如果不是最后一次重复,等待一小段时间
- if (t < times - 1) {
- await new Promise(resolve => setTimeout(resolve, 500));
- }
- }
- completedSteps++;
- // 调用完成回调
- if (onStepComplete) {
- const stepName = getActionName(action);
- onStepComplete(i + 1, actions.length, stepName, 0, times, times);
- }
- // 如果不是最后一步,等待间隔时间
- if (i < actions.length - 1) {
- let remainingTime = stepInterval;
- const countdownInterval = 100;
- const nextStepName = getActionName(actions[i + 1]);
- const nextTimes = actions[i + 1].times || 1;
-
- while (remainingTime > 0) {
- if (shouldStop && shouldStop()) {
- return { success: false, error: '执行被停止', completedSteps };
- }
-
- if (onStepComplete) {
- onStepComplete(i + 1, actions.length, nextStepName, remainingTime, nextTimes, 0);
- }
-
- const waitTime = Math.min(countdownInterval, remainingTime);
- await new Promise(resolve => setTimeout(resolve, waitTime));
- remainingTime -= waitTime;
- }
- }
- }
- if (depth === 0) {
- // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
- }
- return { success: true, completedSteps };
- }
- module.exports = { parseWorkflow, parseActions, calculateSwipeCoordinates, executeAction, executeActionSequence }
|