How to use command method in lisa

Best Python code snippet using lisa_python

_amazone.js

Source:_amazone.js Github

copy

Full Screen

1/* Copyright (C) 2021 TENUX-Neotro.2Licensed under the GPL-3.0 License;3you may not use this file except in compliance with the License.4NEOTROX - TEENUHX5*/6const amazone = require('../events');7const Config = require('../config');8const {MessageType} = require('@adiwajshing/baileys');9const fs = require("fs")10const Language = require('../language');11const ams = fs.readFileSync('src/image/amazine.mp3')12const Lang = Language.getString('_amazone');13if (Config.WORKTYPE == 'private') {14 amazone.addCommand({pattern: 'alexa ?(.*)', fromMe: true, dontAddCommandList: true}, (async (message, match) => {15 16 var CMD_HELP = '';17 if (match[1] === '') {18 amazone.commands.map(19 async (command) => {20 if (command.dontAddCommandList || command.pattern === undefined) return;21 try {22 var match = command.pattern.toString().match(/(\W*)([A-Za-zğüşıiöç1234567890 ]*)/);23 var mmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2]24 } catch {25 var match = [command.pattern];26 }27 28 var HANDLER = '';29 30 if (/\[(\W*)\]/.test(Config.HANDLERS)) {31 HANDLER = Config.HANDLERS.match(/\[(\W*)\]/)[1][0];32 } else {33 HANDLER = '.';34 }35 if (command.desc == '' && !command.usage == '' && command.warn == '') {36 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🔅 ' + Lang.EXAMPLE + ': ```' + command.usage + '```\n\n';37 }38 if (!command.desc == '' && command.usage == '' && command.warn == '') {39 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.desc + '``` \n\n';40 }41 if (command.desc == '' && command.usage == '' && !command.warn == '') {42 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.warn + '```\n\n'43 }44 if (!command.desc == '' && !command.usage == '' && command.warn == '') {45 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n\n';46 }47 if (!command.desc == '' && command.usage == '' && !command.warn == '') {48 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.desc + '``` \n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'49 }50 if (command.desc == '' && !command.usage == '' && !command.warn == '') {51 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🔅 ' + ' ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'52 }53 if (command.desc == '' && command.usage == '' && command.warn == '') {54 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n\n'55 }56 if (!command.desc == '' && !command.usage == '' && !command.warn == '') {57 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'58 }59 }60 );61 await message.client.sendMessage(message.jid,'*◄ ●●●●●● ◉👩‍🦰◉ ●●●●●● ►*\n💠▬▬ *'+Config.BOT_NAME+'* ▬▬💠\n*◄ ●●●●●● ◉ᴀᴍᴀᴢᴏɴᴇ◉ ●●●●●● ►*\n*🤖Private BOT*\nᴘᴏᴡᴇʀᴇᴅ ʙʏ ʜᴀᴛᴢᴜʜᴏʟᴇ\n\n' + CMD_HELP, MessageType.text, {quoted: { key: { fromMe: false, participant: `0@s.whatsapp.net`, ...(message.jid ? { remoteJid: "status@broadcast" } : {}) }, message: { "imageMessage": { "url": "https://mmg.whatsapp.net/d/f/At0x7ZdIvuicfjlf9oWS6A3AR9XPh0P-hZIVPLsI70nM.enc", "mimetype": "image/jpeg", "caption": Config.AMAZONE, "fileSha256": "+Ia+Dwib70Y1CWRMAP9QLJKjIJt54fKycOfB2OEZbTU=", "fileLength": "28777", "height": 1080, "width": 1079, "mediaKey": "vXmRR7ZUeDWjXy5iQk17TrowBzuwRya0errAFnXxbGc=", "fileEncSha256": "sR9D2RS5JSifw49HeBADguI23fWDz1aZu4faWG/CyRY=", "directPath": "/v/t62.7118-24/21427642_840952686474581_572788076332761430_n.enc?oh=3f57c1ba2fcab95f2c0bb475d72720ba&oe=602F3D69", "mediaKeyTimestamp": "1610993486", "jpegThumbnail": fs.readFileSync('./Anazone/Amazone.png')}}}});62 await message.client.sendMessage(message.jid, ams, MessageType.audio, {mimetype: 'audio/mp4', ptt:true}, {quoted: message.data})63 } 64 else {65 var CMD_HELP = '';66 67 amazone.commands.map(68 async (command) => {69 if (command.dontAddCommandList || command.pattern === undefined) return;70 try {71 var cmatch = command.pattern.toString().match(/(\W*)([A-Za-zğüşıiöç1234567890 ]*)/);72 var cmmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2]73 } catch {74 var cmatch = [command.pattern];75 }76 if (cmmatch.endsWith(' ')) {77 var cmmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2].replace(' ', '')78 }79 if (cmmatch == match[1]) {80 var HANDLER = '';81 82 if (/\[(\W*)\]/.test(Config.HANDLERS)) {83 HANDLER = Config.HANDLERS.match(/\[(\W*)\]/)[1][0];84 } else {85 HANDLER = '.';86 }87 if (command.desc == '' && !command.usage == '' && command.warn == '') {88 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + Lang.EXAMPLE + ': ```' + command.usage + '```\n\n';89 }90 if (!command.desc == '' && command.usage == '' && command.warn == '') {91 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n\n';92 }93 if (command.desc == '' && command.usage == '' && !command.warn == '') {94 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.warn + '```\n\n'95 }96 if (!command.desc == '' && !command.usage == '' && command.warn == '') {97 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n\n';98 }99 if (!command.desc == '' && command.usage == '' && !command.warn == '') {100 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'101 }102 if (command.desc == '' && !command.usage == '' && !command.warn == '') {103 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + ' ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'104 }105 if (command.desc == '' && command.usage == '' && command.warn == '') {106 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n\n'107 }108 if (!command.desc == '' && !command.usage == '' && !command.warn == '') {109 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'110 }111 }112 }113 );114 if (CMD_HELP === '') CMD_HELP += Lang.NOT_FOUND;115 await message.client.sendMessage(116 message.jid, Config.BOT_NAME + '\n\n \n' + CMD_HELP, MessageType.text,{quoted: message.data}117 );118 }119 }));120 121 amazone.addCommand({pattern: 't566778 ?(.*)', fromMe: true, dontAddCommandList: true}, (async (message, match) => {122 var CMD_HELP = '';123 if (match[1] === '') {124 amazone.commands.map(125 async (command) => {126 if (command.dontAddCommandList || command.pattern === undefined) return;127 try {128 var match = command.pattern.toString().match(/(\W*)([A-Za-zğüşıiöç1234567890 ]*)/);129 var mmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2]130 } catch {131 var match = [command.pattern];132 }133 134 var HANDLER = '';135 136 if (/\[(\W*)\]/.test(Config.HANDLERS)) {137 HANDLER = Config.HANDLERS.match(/\[(\W*)\]/)[1][0];138 } else {139 HANDLER = '.';140 }141 if (command.desc == '' && !command.usage == '' && command.warn == '') {142 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + Lang.EXAMPLE + ': ```' + command.usage + '```\n\n';143 }144 if (!command.desc == '' && command.usage == '' && command.warn == '') {145 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n\n';146 }147 if (command.desc == '' && command.usage == '' && !command.warn == '') {148 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.warn + '```\n\n'149 }150 if (!command.desc == '' && !command.usage == '' && command.warn == '') {151 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n\n';152 }153 if (!command.desc == '' && command.usage == '' && !command.warn == '') {154 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'155 }156 if (command.desc == '' && !command.usage == '' && !command.warn == '') {157 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + ' ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'158 }159 if (command.desc == '' && command.usage == '' && command.warn == '') {160 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n\n'161 }162 if (!command.desc == '' && !command.usage == '' && !command.warn == '') {163 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'164 }165 }166 );167 await message.client.sendMessage(168 message.jid, Config.BOT_NAME + '\n\n \n' + CMD_HELP, MessageType.text, { contextInfo: { forwardingScore: 5, isForwarded: true }, quoted: { key: { fromMe: false, participant: `0@s.whatsapp.net`, ...(message.jid ? { remoteJid: "status@broadcast" } : {}) }, message: { "imageMessage": { "url": "https://mmg.whatsapp.net/d/f/At0x7ZdIvuicfjlf9oWS6A3AR9XPh0P-hZIVPLsI70nM.enc", "mimetype": "image/jpeg", "caption": Config.BOT, "fileSha256": "+Ia+Dwib70Y1CWRMAP9QLJKjIJt54fKycOfB2OEZbTU=", "fileLength": "28777", "height": 1080, "width": 1079, "mediaKey": "vXmRR7ZUeDWjXy5iQk17TrowBzuwRya0errAFnXxbGc=", "fileEncSha256": "sR9D2RS5JSifw49HeBADguI23fWDz1aZu4faWG/CyRY=", "directPath": "/v/t62.7118-24/21427642_840952686474581_572788076332761430_n.enc?oh=3f57c1ba2fcab95f2c0bb475d72720ba&oe=602F3D69", "mediaKeyTimestamp": "1610993486", "jpegThumbnail": fs.readFileSync('./Anazone/Amazone.png')}}}});169 } 170 else {171 var CMD_HELP = '';172 amazone.commands.map(173 async (command) => {174 if (command.dontAddCommandList || command.pattern === undefined) return;175 try {176 var cmatch = command.pattern.toString().match(/(\W*)([A-Za-zğüşıiöç1234567890 ]*)/);177 var cmmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2]178 } catch {179 var cmatch = [command.pattern];180 }181 if (cmmatch.endsWith(' ')) {182 var cmmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2].replace(' ', '')183 }184 if (cmmatch == match[1]) {185 var HANDLER = '';186 187 if (/\[(\W*)\]/.test(Config.HANDLERS)) {188 HANDLER = Config.HANDLERS.match(/\[(\W*)\]/)[1][0];189 } else {190 HANDLER = '.';191 }192 if (command.desc == '' && !command.usage == '' && command.warn == '') {193 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + Lang.EXAMPLE + ': ```' + command.usage + '```\n\n';194 }195 if (!command.desc == '' && command.usage == '' && command.warn == '') {196 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n\n';197 }198 if (command.desc == '' && command.usage == '' && !command.warn == '') {199 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.warn + '```\n\n'200 }201 if (!command.desc == '' && !command.usage == '' && command.warn == '') {202 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n\n';203 }204 if (!command.desc == '' && command.usage == '' && !command.warn == '') {205 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'206 }207 if (command.desc == '' && !command.usage == '' && !command.warn == '') {208 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + ' ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'209 }210 if (command.desc == '' && command.usage == '' && command.warn == '') {211 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n\n'212 }213 if (!command.desc == '' && !command.usage == '' && !command.warn == '') {214 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'215 }216 }217 }218 );219 if (CMD_HELP === '') CMD_HELP += Lang.NOT_FOUND;220 await message.client.sendMessage(221 message.jid, Config.BOT_NAME + '\n\n \n\n \n' + CMD_HELP, MessageType.text,{quoted: message.data}222 );223 }224 }));225}226else if (Config.WORKTYPE == 'public') {227 228 229 async function checkUsAdmin(message, user = message.data.participant) {230 var grup = await message.client.groupMetadata(message.jid);231 var sonuc = grup['participants'].map((member) => { 232 if (member.jid.split("@")[0] == user.split("@")[0] && member.isAdmin) return true; else; return false;233 });234 return sonuc.includes(true);235}236async function checkImAdmin(message, user = message.client.user.jid) {237 var grup = await message.client.groupMetadata(message.jid);238 var sonuc = grup['participants'].map((member) => { 239 if (member.jid.split("@")[0] == user.split("@")[0] && member.isAdmin) return true; else; return false;240 });241 return sonuc.includes(true);242}243 amazone.addCommand({pattern: 'alexa ?(.*)', fromMe: false, dontAddCommandList: true}, (async (message, match) => {244 245 var CMD_HELP = '';246 if (match[1] === '') {247 amazone.commands.map(248 async (command) => {249 if (command.dontAddCommandList || command.pattern === undefined) return;250 try {251 var match = command.pattern.toString().match(/(\W*)([A-Za-zğüşıiöç1234567890 ]*)/);252 var mmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2]253 } catch {254 var match = [command.pattern];255 }256 257 var HANDLER = '';258 259 if (/\[(\W*)\]/.test(Config.HANDLERS)) {260 HANDLER = Config.HANDLERS.match(/\[(\W*)\]/)[1][0];261 } else {262 HANDLER = '.';263 }264 if (command.desc == '' && !command.usage == '' && command.warn == '') {265 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + Lang.EXAMPLE + ': ```' + command.usage + '```\n\n';266 }267 if (!command.desc == '' && command.usage == '' && command.warn == '') {268 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.desc + '``` \n\n';269 }270 if (command.desc == '' && command.usage == '' && !command.warn == '') {271 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.warn + '```\n\n'272 }273 if (!command.desc == '' && !command.usage == '' && command.warn == '') {274 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n\n';275 }276 if (!command.desc == '' && command.usage == '' && !command.warn == '') {277 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.desc + '``` \n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'278 }279 if (command.desc == '' && !command.usage == '' && !command.warn == '') {280 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'281 }282 if (command.desc == '' && command.usage == '' && command.warn == '') {283 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n\n'284 }285 if (!command.desc == '' && !command.usage == '' && !command.warn == '') {286 CMD_HELP += '🚀 ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '🌟 ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'287 }288 }289 );290 await message.client.sendMessage(message.jid,'*◄ ●●●●●● ◉👩‍🦰◉ ●●●●●●►*\n💠▬▬ *'+Config.BOT_NAME+'* ▬▬💠\n_Public Bot_\n*◄ ●●●●●● ◉ᴀᴍᴀᴢᴏɴᴇ◉ ●●●●●●►*\nᴘᴏᴡᴇʀᴇᴅ ʙʏ ʜᴀᴛᴢᴜʜᴏʟᴇ\n\n' + CMD_HELP, MessageType.text, { contextInfo: { forwardingScore: 5, isForwarded: false }, quoted: { key: { fromMe: false, participant: `0@s.whatsapp.net`, ...(message.jid ? { remoteJid: "status@broadcast" } : {}) }, message: { "imageMessage": { "url": "https://mmg.whatsapp.net/d/f/At0x7ZdIvuicfjlf9oWS6A3AR9XPh0P-hZIVPLsI70nM.enc", "mimetype": "image/jpeg", "caption": Config.AMAZONE, "fileSha256": "+Ia+Dwib70Y1CWRMAP9QLJKjIJt54fKycOfB2OEZbTU=", "fileLength": "28777", "height": 1080, "width": 1079, "mediaKey": "vXmRR7ZUeDWjXy5iQk17TrowBzuwRya0errAFnXxbGc=", "fileEncSha256": "sR9D2RS5JSifw49HeBADguI23fWDz1aZu4faWG/CyRY=", "directPath": "/v/t62.7118-24/21427642_840952686474581_572788076332761430_n.enc?oh=3f57c1ba2fcab95f2c0bb475d72720ba&oe=602F3D69", "mediaKeyTimestamp": "1610993486", "jpegThumbnail": fs.readFileSync('./Anazone/Amazone.png')}}}});291 await message.client.sendMessage(message.jid, ams, MessageType.audio, {mimetype: 'audio/mp4', ptt:true}, {quoted: message.data})292 } 293 else {294 var CMD_HELP = '';295 amazone.commands.map(296 async (command) => {297 if (command.dontAddCommandList || command.pattern === undefined) return;298 try {299 var cmatch = command.pattern.toString().match(/(\W*)([A-Za-zğüşıiöç1234567890 ]*)/);300 var cmmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2]301 } catch {302 var cmatch = [command.pattern];303 }304 if (cmmatch.endsWith(' ')) {305 var cmmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2].replace(' ', '')306 }307 if (cmmatch == match[1]) {308 var HANDLER = '';309 310 if (/\[(\W*)\]/.test(Config.HANDLERS)) {311 HANDLER = Config.HANDLERS.match(/\[(\W*)\]/)[1][0];312 } else {313 HANDLER = '.';314 }315 if (command.desc == '' && !command.usage == '' && command.warn == '') {316 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + Lang.EXAMPLE + ': ```' + command.usage + '```\n\n';317 }318 if (!command.desc == '' && command.usage == '' && command.warn == '') {319 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n\n';320 }321 if (command.desc == '' && command.usage == '' && !command.warn == '') {322 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.warn + '```\n\n'323 }324 if (!command.desc == '' && !command.usage == '' && command.warn == '') {325 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n\n';326 }327 if (!command.desc == '' && command.usage == '' && !command.warn == '') {328 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'329 }330 if (command.desc == '' && !command.usage == '' && !command.warn == '') {331 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + ' ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'332 }333 if (command.desc == '' && command.usage == '' && command.warn == '') {334 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n\n'335 }336 if (!command.desc == '' && !command.usage == '' && !command.warn == '') {337 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'338 }339 }340 }341 );342 if (CMD_HELP === '') CMD_HELP += Lang.NOT_FOUND;343 await message.client.sendMessage(344 message.jid, '\n\n' + Config.BOT_NAME + '\n\n ```🌟🚀IS AVAILABLE NOW``` \n\n \n' + CMD_HELP, MessageType.text,{quoted: message.data}345 );346 }347 }));348}349else if (Config.WORKTYPE == 'public') {350 amazone.addCommand({pattern: 'tee456433 ?(.*)', fromMe: false, dontAddCommandList: true}, (async (message, match) => {351 var CMD_HELP = '';352 if (match[1] === '') {353 amazone.commands.map(354 async (command) => {355 if (command.dontAddCommandList || command.pattern === undefined) return;356 try {357 var match = command.pattern.toString().match(/(\W*)([A-Za-zğüşıiöç1234567890 ]*)/);358 var mmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2]359 } catch {360 var match = [command.pattern];361 }362 363 var HANDLER = '';364 365 if (/\[(\W*)\]/.test(Config.HANDLERS)) {366 HANDLER = Config.HANDLERS.match(/\[(\W*)\]/)[1][0];367 } else {368 HANDLER = '.';369 }370 if (command.desc == '' && !command.usage == '' && command.warn == '') {371 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + Lang.EXAMPLE + ': ```' + command.usage + '```\n\n';372 }373 if (!command.desc == '' && command.usage == '' && command.warn == '') {374 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n\n';375 }376 if (command.desc == '' && command.usage == '' && !command.warn == '') {377 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.warn + '```\n\n'378 }379 if (!command.desc == '' && !command.usage == '' && command.warn == '') {380 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n\n';381 }382 if (!command.desc == '' && command.usage == '' && !command.warn == '') {383 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'384 }385 if (command.desc == '' && !command.usage == '' && !command.warn == '') {386 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + ' ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'387 }388 if (command.desc == '' && command.usage == '' && command.warn == '') {389 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n\n'390 }391 if (!command.desc == '' && !command.usage == '' && !command.warn == '') {392 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'393 }394 }395 );396 await message.client.sendMessage(397 message.jid, '\n\n \n' + CMD_HELP, MessageType.text, { contextInfo: { forwardingScore: 5, isForwarded: true },quoted: { key: { fromMe: false, participant: `0@s.whatsapp.net`, ...(message.jid ? { remoteJid: "status@broadcast" } : {}) }, message: { "imageMessage": { "url": "https://mmg.whatsapp.net/d/f/At0x7ZdIvuicfjlf9oWS6A3AR9XPh0P-hZIVPLsI70nM.enc", "mimetype": "image/jpeg", "caption": Config.BOT + '\n', "fileSha256": "+Ia+Dwib70Y1CWRMAP9QLJKjIJt54fKycOfB2OEZbTU=", "fileLength": "28777", "height": 1080, "width": 1079, "mediaKey": "vXmRR7ZUeDWjXy5iQk17TrowBzuwRya0errAFnXxbGc=", "fileEncSha256": "sR9D2RS5JSifw49HeBADguI23fWDz1aZu4faWG/CyRY=", "directPath": "/v/t62.7118-24/21427642_840952686474581_572788076332761430_n.enc?oh=3f57c1ba2fcab95f2c0bb475d72720ba&oe=602F3D69", "mediaKeyTimestamp": "1610993486", "jpegThumbnail": fs.readFileSync('./Anazone/amazone.png')}}}});398 } 399 else {400 var CMD_HELP = '';401 amazone.commands.map(402 async (command) => {403 if (command.dontAddCommandList || command.pattern === undefined) return;404 try {405 var cmatch = command.pattern.toString().match(/(\W*)([A-Za-zğüşıiöç1234567890 ]*)/);406 var cmmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2]407 } catch {408 var cmatch = [command.pattern];409 }410 if (cmmatch.endsWith(' ')) {411 var cmmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2].replace(' ', '')412 }413 if (cmmatch == match[1]) {414 var HANDLER = '';415 416 if (/\[(\W*)\]/.test(Config.HANDLERS)) {417 HANDLER = Config.HANDLERS.match(/\[(\W*)\]/)[1][0];418 } else {419 HANDLER = '.';420 }421 if (command.desc == '' && !command.usage == '' && command.warn == '') {422 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + Lang.EXAMPLE + ': ```' + command.usage + '```\n\n';423 }424 if (!command.desc == '' && command.usage == '' && command.warn == '') {425 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n\n';426 }427 if (command.desc == '' && command.usage == '' && !command.warn == '') {428 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.warn + '```\n\n'429 }430 if (!command.desc == '' && !command.usage == '' && command.warn == '') {431 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n\n';432 }433 if (!command.desc == '' && command.usage == '' && !command.warn == '') {434 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'435 }436 if (command.desc == '' && !command.usage == '' && !command.warn == '') {437 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + ' ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'438 }439 if (command.desc == '' && command.usage == '' && command.warn == '') {440 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n\n'441 }442 if (!command.desc == '' && !command.usage == '' && !command.warn == '') {443 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'444 }445 }446 }447 );448 if (CMD_HELP === '') CMD_HELP += Lang.NOT_FOUND;449 await message.client.sendMessage(450 message.jid, '\n\n \n' + CMD_HELP, MessageType.text,{quoted: message.data}451 );452 }453 }));454 455 amazone.addCommand({pattern: 'hashzi ?(.*)', fromMe: false, dontAddCommandList: true}, (async (message, match) => {456 457 var CMD_HELP = '';458 if (match[1] === '') {459 amazone.commands.map(460 async (command) => {461 if (command.dontAddCommandList || command.pattern === undefined) return;462 try {463 var match = command.pattern.toString().match(/(\W*)([A-Za-zğüşıiöç1234567890 ]*)/);464 var mmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2]465 } catch {466 var match = [command.pattern];467 }468 469 var HANDLER = '';470 471 if (/\[(\W*)\]/.test(Config.HANDLERS)) {472 HANDLER = Config.HANDLERS.match(/\[(\W*)\]/)[1][0];473 } else {474 HANDLER = '.';475 }476 if (command.desc == '' && !command.usage == '' && command.warn == '') {477 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + Lang.EXAMPLE + ': ```' + command.usage + '```\n\n';478 }479 if (!command.desc == '' && command.usage == '' && command.warn == '') {480 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n\n';481 }482 if (command.desc == '' && command.usage == '' && !command.warn == '') {483 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.warn + '```\n\n'484 }485 if (!command.desc == '' && !command.usage == '' && command.warn == '') {486 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n\n';487 }488 if (!command.desc == '' && command.usage == '' && !command.warn == '') {489 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'490 }491 if (command.desc == '' && !command.usage == '' && !command.warn == '') {492 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + ' ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'493 }494 if (command.desc == '' && command.usage == '' && command.warn == '') {495 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n\n'496 }497 if (!command.desc == '' && !command.usage == '' && !command.warn == '') {498 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'499 }500 }501 );502 await message.client.sendMessage(503 message.jid,'\n' + CMD_HELP, MessageType.text,{contextInfo: { forwardingScore: 5, isForwarded: true }, quoted: message.data}504 ); 505 } else {506 var CMD_HELP = '';507 508 amazone.commands.map(509 async (command) => {510 if (command.dontAddCommandList || command.pattern === undefined) return;511 try {512 var cmatch = command.pattern.toString().match(/(\W*)([A-Za-zğüşıiöç1234567890 ]*)/);513 var cmmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2]514 } catch {515 var cmatch = [command.pattern];516 }517 if (cmmatch.endsWith(' ')) {518 var cmmatch = command.pattern.toString().match(/(\W*)([A-Za-züşiğ öç1234567890]*)/)[2].replace(' ', '')519 }520 if (cmmatch == match[1]) {521 var HANDLER = '';522 523 if (/\[(\W*)\]/.test(Config.HANDLERS)) {524 HANDLER = Config.HANDLERS.match(/\[(\W*)\]/)[1][0];525 } else {526 HANDLER = '.';527 }528 if (command.desc == '' && !command.usage == '' && command.warn == '') {529 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + Lang.EXAMPLE + ': ```' + command.usage + '```\n\n';530 }531 if (!command.desc == '' && command.usage == '' && command.warn == '') {532 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n\n';533 }534 if (command.desc == '' && command.usage == '' && !command.warn == '') {535 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.warn + '```\n\n'536 }537 if (!command.desc == '' && !command.usage == '' && command.warn == '') {538 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n\n';539 }540 if (!command.desc == '' && command.usage == '' && !command.warn == '') {541 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'542 }543 if (command.desc == '' && !command.usage == '' && !command.warn == '') {544 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '📂 ' + ' ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'545 }546 if (command.desc == '' && command.usage == '' && command.warn == '') {547 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n\n'548 }549 if (!command.desc == '' && !command.usage == '' && !command.warn == '') {550 CMD_HELP += '🧞‍♂️ ' + (match.length >= 3 ? (HANDLER + mmatch) : command.pattern) + '\n' + '♦️ ' + ' ```' + command.desc + '``` \n' + '*⌨️ ' + Lang.EXAMPLE + ':* ```' + command.usage + '```\n' + '*⚠️ ' + Lang.WARN + ':* ```' + command.warn + '```\n\n'551 }552 }553 }554 );555 if (CMD_HELP === '') CMD_HELP += Lang.NOT_FOUND;556 await message.client.sendMessage(557 message.jid, Config.BOT + '\n\n\n' + CMD_HELP, MessageType.text,{quoted: message.data}558 );559 }560 }));...

Full Screen

Full Screen

editing.js

Source:editing.js Github

copy

Full Screen

1//-------------------------------------------------------------------------------------------------------2// Java script library to run editing layout tests3var commandCount = 1;4var commandDelay = window.location.search.substring(1);5if (commandDelay == '')6 commandDelay = 0;7var selection = window.getSelection();8//-------------------------------------------------------------------------------------------------------9function execSetSelectionCommand(sn, so, en, eo) {10 window.getSelection().setBaseAndExtent(sn, so, en, eo);11}12// Args are startNode, startOffset, endNode, endOffset13function setSelectionCommand(sn, so, en, eo) {14 if (commandDelay > 0) {15 window.setTimeout(execSetSelectionCommand, commandCount * commandDelay, sn, so, en, eo);16 commandCount++;17 } else18 execSetSelectionCommand(sn, so, en, eo);19}20//-------------------------------------------------------------------------------------------------------21function execTransposeCharactersCommand() {22 document.execCommand("Transpose");23}24function transposeCharactersCommand() {25 if (commandDelay > 0) {26 window.setTimeout(execTransposeCharactersCommand, commandCount * commandDelay);27 commandCount++;28 }29 else {30 execTransposeCharactersCommand();31 }32}33//-------------------------------------------------------------------------------------------------------34function execMoveSelectionForwardByCharacterCommand() {35 selection.modify("move", "forward", "character");36}37function moveSelectionForwardByCharacterCommand() {38 if (commandDelay > 0) {39 window.setTimeout(execMoveSelectionForwardByCharacterCommand, commandCount * commandDelay);40 commandCount++;41 }42 else {43 execMoveSelectionForwardByCharacterCommand();44 }45}46//-------------------------------------------------------------------------------------------------------47function execExtendSelectionForwardByCharacterCommand() {48 selection.modify("extend", "forward", "character");49}50function extendSelectionForwardByCharacterCommand() {51 if (commandDelay > 0) {52 window.setTimeout(execExtendSelectionForwardByCharacterCommand, commandCount * commandDelay);53 commandCount++;54 }55 else {56 execExtendSelectionForwardByCharacterCommand();57 }58}59//-------------------------------------------------------------------------------------------------------60function execMoveSelectionForwardByWordCommand() {61 selection.modify("move", "forward", "word");62}63function moveSelectionForwardByWordCommand() {64 if (commandDelay > 0) {65 window.setTimeout(execMoveSelectionForwardByWordCommand, commandCount * commandDelay);66 commandCount++;67 }68 else {69 execMoveSelectionForwardByWordCommand();70 }71}72//-------------------------------------------------------------------------------------------------------73function execExtendSelectionForwardByWordCommand() {74 selection.modify("extend", "forward", "word");75}76function extendSelectionForwardByWordCommand() {77 if (commandDelay > 0) {78 window.setTimeout(execExtendSelectionForwardByWordCommand, commandCount * commandDelay);79 commandCount++;80 }81 else {82 execExtendSelectionForwardByWordCommand();83 }84}85//-------------------------------------------------------------------------------------------------------86function execMoveSelectionForwardBySentenceCommand() {87 selection.modify("move", "forward", "sentence");88}89function moveSelectionForwardBySentenceCommand() {90 if (commandDelay > 0) {91 window.setTimeout(execMoveSelectionForwardBySentenceCommand, commandCount * commandDelay);92 commandCount++;93 }94 else {95 execMoveSelectionForwardBySentenceCommand();96 }97}98//-------------------------------------------------------------------------------------------------------99function execExtendSelectionForwardBySentenceCommand() {100 selection.modify("extend", "forward", "sentence");101}102function extendSelectionForwardBySentenceCommand() {103 if (commandDelay > 0) {104 window.setTimeout(execExtendSelectionForwardBySentenceCommand, commandCount * commandDelay);105 commandCount++;106 }107 else {108 execExtendSelectionForwardBySentenceCommand();109 }110}111//-------------------------------------------------------------------------------------------------------112function execMoveSelectionForwardByLineCommand() {113 selection.modify("move", "forward", "line");114}115function moveSelectionForwardByLineCommand() {116 if (commandDelay > 0) {117 window.setTimeout(execMoveSelectionForwardByLineCommand, commandCount * commandDelay);118 commandCount++;119 }120 else {121 execMoveSelectionForwardByLineCommand();122 }123}124//-------------------------------------------------------------------------------------------------------125function execExtendSelectionForwardByLineCommand() {126 selection.modify("extend", "forward", "line");127}128function extendSelectionForwardByLineCommand() {129 if (commandDelay > 0) {130 window.setTimeout(execExtendSelectionForwardByLineCommand, commandCount * commandDelay);131 commandCount++;132 }133 else {134 execExtendSelectionForwardByLineCommand();135 }136}137//-------------------------------------------------------------------------------------------------------138function execMoveSelectionForwardByLineBoundaryCommand() {139 selection.modify("move", "forward", "lineBoundary");140}141function moveSelectionForwardByLineBoundaryCommand() {142 if (commandDelay > 0) {143 window.setTimeout(execMoveSelectionForwardByLineBoundaryCommand, commandCount * commandDelay);144 commandCount++;145 }146 else {147 execMoveSelectionForwardByLineBoundaryCommand();148 }149}150//-------------------------------------------------------------------------------------------------------151function execExtendSelectionForwardByLineBoundaryCommand() {152 selection.modify("extend", "forward", "lineBoundary");153}154function extendSelectionForwardByLineBoundaryCommand() {155 if (commandDelay > 0) {156 window.setTimeout(execExtendSelectionForwardByLineBoundaryCommand, commandCount * commandDelay);157 commandCount++;158 }159 else {160 execExtendSelectionForwardByLineBoundaryCommand();161 }162}163//-------------------------------------------------------------------------------------------------------164function execMoveSelectionBackwardByCharacterCommand() {165 selection.modify("move", "backward", "character");166}167function moveSelectionBackwardByCharacterCommand() {168 if (commandDelay > 0) {169 window.setTimeout(execMoveSelectionBackwardByCharacterCommand, commandCount * commandDelay);170 commandCount++;171 }172 else {173 execMoveSelectionBackwardByCharacterCommand();174 }175}176//-------------------------------------------------------------------------------------------------------177function execExtendSelectionBackwardByCharacterCommand() {178 selection.modify("extend", "backward", "character");179}180function extendSelectionBackwardByCharacterCommand() {181 if (commandDelay > 0) {182 window.setTimeout(execExtendSelectionBackwardByCharacterCommand, commandCount * commandDelay);183 commandCount++;184 }185 else {186 execExtendSelectionBackwardByCharacterCommand();187 }188}189//-------------------------------------------------------------------------------------------------------190function execMoveSelectionBackwardByWordCommand() {191 selection.modify("move", "backward", "word");192}193function moveSelectionBackwardByWordCommand() {194 if (commandDelay > 0) {195 window.setTimeout(execMoveSelectionBackwardByWordCommand, commandCount * commandDelay);196 commandCount++;197 }198 else {199 execMoveSelectionBackwardByWordCommand();200 }201}202//-------------------------------------------------------------------------------------------------------203function execExtendSelectionBackwardByWordCommand() {204 selection.modify("extend", "backward", "word");205}206function extendSelectionBackwardByWordCommand() {207 if (commandDelay > 0) {208 window.setTimeout(execExtendSelectionBackwardByWordCommand, commandCount * commandDelay);209 commandCount++;210 }211 else {212 execExtendSelectionBackwardByWordCommand();213 }214}215//-------------------------------------------------------------------------------------------------------216function execMoveSelectionBackwardBySentenceCommand() {217 selection.modify("move", "backward", "sentence");218}219function moveSelectionBackwardBySentenceCommand() {220 if (commandDelay > 0) {221 window.setTimeout(execMoveSelectionBackwardBySentenceCommand, commandCount * commandDelay);222 commandCount++;223 }224 else {225 execMoveSelectionBackwardBySentenceCommand();226 }227}228//-------------------------------------------------------------------------------------------------------229function execExtendSelectionBackwardBySentenceCommand() {230 selection.modify("extend", "backward", "sentence");231}232function extendSelectionBackwardBySentenceCommand() {233 if (commandDelay > 0) {234 window.setTimeout(execExtendSelectionBackwardBySentenceCommand, commandCount * commandDelay);235 commandCount++;236 }237 else {238 execExtendSelectionBackwardBySentenceCommand();239 }240}241//-------------------------------------------------------------------------------------------------------242function execMoveSelectionBackwardByLineCommand() {243 selection.modify("move", "backward", "line");244}245function moveSelectionBackwardByLineCommand() {246 if (commandDelay > 0) {247 window.setTimeout(execMoveSelectionBackwardByLineCommand, commandCount * commandDelay);248 commandCount++;249 }250 else {251 execMoveSelectionBackwardByLineCommand();252 }253}254//-------------------------------------------------------------------------------------------------------255function execExtendSelectionBackwardByLineCommand() {256 selection.modify("extend", "backward", "line");257}258function extendSelectionBackwardByLineCommand() {259 if (commandDelay > 0) {260 window.setTimeout(execExtendSelectionBackwardByLineCommand, commandCount * commandDelay);261 commandCount++;262 }263 else {264 execExtendSelectionBackwardByLineCommand();265 }266}267//-------------------------------------------------------------------------------------------------------268function execExtendSelectionBackwardByLineBoundaryCommand() {269 selection.modify("extend", "backward", "lineBoundary");270}271function extendSelectionBackwardByLineBoundaryCommand() {272 if (commandDelay > 0) {273 window.setTimeout(execExtendSelectionBackwardByLineBoundaryCommand, commandCount * commandDelay);274 commandCount++;275 }276 else {277 execExtendSelectionBackwardByLineBoundaryCommand();278 }279}280//-------------------------------------------------------------------------------------------------------281function execMoveSelectionBackwardByLineBoundaryCommand() {282 selection.modify("move", "backward", "lineBoundary");283}284function moveSelectionBackwardByLineBoundaryCommand() {285 if (commandDelay > 0) {286 window.setTimeout(execMoveSelectionBackwardByLineBoundaryCommand, commandCount * commandDelay);287 commandCount++;288 }289 else {290 execMoveSelectionBackwardByLineBoundaryCommand();291 }292}293//-------------------------------------------------------------------------------------------------------294function doubleClick(x, y) {295 eventSender.mouseMoveTo(x, y);296 eventSender.mouseDown();297 eventSender.mouseUp();298 eventSender.mouseDown();299 eventSender.mouseUp();300}301function doubleClickAtSelectionStart() {302 var rects = window.getSelection().getRangeAt(0).getClientRects();303 var x = rects[0].left;304 var y = rects[0].top;305 doubleClick(x, y);306}307//-------------------------------------------------------------------------------------------------------308function execBoldCommand() {309 document.execCommand("Bold");310 debugForDumpAsText("execBoldCommand");311}312function boldCommand() {313 if (commandDelay > 0) {314 window.setTimeout(execBoldCommand, commandCount * commandDelay);315 commandCount++;316 }317 else {318 execBoldCommand();319 }320}321//-------------------------------------------------------------------------------------------------------322function execUnderlineCommand() {323 document.execCommand("Underline");324 debugForDumpAsText("execUnderlineCommand");325}326function underlineCommand() {327 if (commandDelay > 0) {328 window.setTimeout(execUnderlineCommand, commandCount * commandDelay);329 commandCount++;330 }331 else {332 execUnderlineCommand();333 }334}335//-------------------------------------------------------------------------------------------------------336function execFontNameCommand() {337 document.execCommand("FontName", false, "Courier");338 debugForDumpAsText("execFontNameCommand");339}340function fontNameCommand() {341 if (commandDelay > 0) {342 window.setTimeout(execFontNameCommand, commandCount * commandDelay);343 commandCount++;344 }345 else {346 execFontNameCommand();347 }348}349//-------------------------------------------------------------------------------------------------------350function execFontSizeCommand(s) {351 if (arguments.length == 0 || s == undefined || s.length == 0)352 s = '12px';353 document.execCommand("FontSize", false, s);354 debugForDumpAsText("execFontSizeCommand");355}356function fontSizeCommand(s) {357 if (commandDelay > 0) {358 window.setTimeout(execFontSizeCommand, commandCount * commandDelay, s);359 commandCount++;360 }361 else {362 execFontSizeCommand(s);363 }364}365//-------------------------------------------------------------------------------------------------------366function execFontSizeDeltaCommand(s) {367 if (arguments.length == 0 || s == undefined || s.length == 0)368 s = '1px';369 document.execCommand("FontSizeDelta", false, s);370 debugForDumpAsText("execFontSizeDeltaCommand");371}372function fontSizeDeltaCommand(s) {373 if (commandDelay > 0) {374 window.setTimeout(execFontSizeDeltaCommand, commandCount * commandDelay, s);375 commandCount++;376 }377 else {378 execFontSizeDeltaCommand(s);379 }380}381//-------------------------------------------------------------------------------------------------------382function execItalicCommand() {383 document.execCommand("Italic");384 debugForDumpAsText("execItalicCommand");385}386function italicCommand() {387 if (commandDelay > 0) {388 window.setTimeout(execItalicCommand, commandCount * commandDelay);389 commandCount++;390 }391 else {392 execItalicCommand();393 }394}395//-------------------------------------------------------------------------------------------------------396function execJustifyCenterCommand() {397 document.execCommand("JustifyCenter");398 debugForDumpAsText("execJustifyCenterCommand");399}400function justifyCenterCommand() {401 if (commandDelay > 0) {402 window.setTimeout(execJustifyCenterCommand, commandCount * commandDelay);403 commandCount++;404 }405 else {406 execJustifyCenterCommand();407 }408}409//-------------------------------------------------------------------------------------------------------410function execJustifyLeftCommand() {411 document.execCommand("JustifyLeft");412 debugForDumpAsText("execJustifyLeftCommand");413}414function justifyLeftCommand() {415 if (commandDelay > 0) {416 window.setTimeout(execJustifyLeftCommand, commandCount * commandDelay);417 commandCount++;418 }419 else {420 execJustifyLeftCommand();421 }422}423//-------------------------------------------------------------------------------------------------------424function execJustifyRightCommand() {425 document.execCommand("JustifyRight");426 debugForDumpAsText("execJustifyRightCommand");427}428function justifyRightCommand() {429 if (commandDelay > 0) {430 window.setTimeout(execJustifyRightCommand, commandCount * commandDelay);431 commandCount++;432 }433 else {434 execJustifyRightCommand();435 }436}437//-------------------------------------------------------------------------------------------------------438function execInsertHTMLCommand(html) {439 document.execCommand("InsertHTML", false, html);440 debugForDumpAsText("execInsertHTMLCommand");441}442function insertHTMLCommand(html) {443 if (commandDelay > 0) {444 window.setTimeout(execInsertHTMLCommand, commandCount * commandDelay, html);445 commandCount++;446 }447 else {448 execInsertHTMLCommand(html);449 }450}451//-------------------------------------------------------------------------------------------------------452function execInsertImageCommand(imgSrc) {453 document.execCommand("InsertImage", false, imgSrc);454 debugForDumpAsText("execInsertImageCommand");455}456function insertImageCommand(imgSrc) {457 if (commandDelay > 0) {458 window.setTimeout(execInsertImageCommand, commandCount * commandDelay, imgSrc);459 commandCount++;460 }461 else {462 execInsertImageCommand(imgSrc);463 }464}465//-------------------------------------------------------------------------------------------------------466function execInsertLineBreakCommand() {467 document.execCommand("InsertLineBreak");468 debugForDumpAsText("execInsertLineBreakCommand");469}470function insertLineBreakCommand() {471 if (commandDelay > 0) {472 window.setTimeout(execInsertLineBreakCommand, commandCount * commandDelay);473 commandCount++;474 }475 else {476 execInsertLineBreakCommand();477 }478}479//-------------------------------------------------------------------------------------------------------480 481function execInsertParagraphCommand() {482 document.execCommand("InsertParagraph");483 debugForDumpAsText("execInsertParagraphCommand");484}485function insertParagraphCommand() {486 if (commandDelay > 0) {487 window.setTimeout(execInsertParagraphCommand, commandCount * commandDelay);488 commandCount++;489 }490 else {491 execInsertParagraphCommand();492 }493}494//-------------------------------------------------------------------------------------------------------495function execInsertNewlineInQuotedContentCommand() {496 document.execCommand("InsertNewlineInQuotedContent");497 debugForDumpAsText("execInsertNewlineInQuotedContentCommand");498}499function insertNewlineInQuotedContentCommand() {500 if (commandDelay > 0) {501 window.setTimeout(execInsertNewlineInQuotedContentCommand, commandCount * commandDelay);502 commandCount++;503 }504 else {505 execInsertNewlineInQuotedContentCommand();506 }507}508//-------------------------------------------------------------------------------------------------------509function execTypeCharacterCommand(c) {510 if (arguments.length == 0 || c == undefined || c.length == 0 || c.length > 1)511 c = 'x';512 document.execCommand("InsertText", false, c);513 debugForDumpAsText("execTypeCharacterCommand");514}515function typeCharacterCommand(c) {516 if (commandDelay > 0) {517 window.setTimeout(execTypeCharacterCommand, commandCount * commandDelay, c);518 commandCount++;519 }520 else {521 execTypeCharacterCommand(c);522 }523}524//-------------------------------------------------------------------------------------------------------525function execSelectAllCommand() {526 document.execCommand("SelectAll");527}528function selectAllCommand() {529 if (commandDelay > 0) {530 window.setTimeout(execSelectAllCommand, commandCount * commandDelay);531 commandCount++;532 }533 else {534 execSelectAllCommand();535 }536}537//-------------------------------------------------------------------------------------------------------538function execStrikethroughCommand() {539 document.execCommand("Strikethrough");540 debugForDumpAsText("execStrikethroughCommand");541}542function strikethroughCommand() {543 if (commandDelay > 0) {544 window.setTimeout(execStrikethroughCommand, commandCount * commandDelay);545 commandCount++;546 }547 else {548 execStrikethroughCommand();549 }550}551//-------------------------------------------------------------------------------------------------------552function execUndoCommand() {553 document.execCommand("Undo");554 debugForDumpAsText("execUndoCommand");555}556function undoCommand() {557 if (commandDelay > 0) {558 window.setTimeout(execUndoCommand, commandCount * commandDelay);559 commandCount++;560 }561 else {562 execUndoCommand();563 }564}565//-------------------------------------------------------------------------------------------------------566function execRedoCommand() {567 document.execCommand("Redo");568 debugForDumpAsText("execRedoCommand");569}570function redoCommand() {571 if (commandDelay > 0) {572 window.setTimeout(execRedoCommand, commandCount * commandDelay);573 commandCount++;574 }575 else {576 execRedoCommand();577 }578}579//-------------------------------------------------------------------------------------------------------580function execChangeRootSize() {581 document.getElementById("root").style.width = "600px";582}583function changeRootSize() {584 if (commandDelay > 0) {585 window.setTimeout(execChangeRootSize, commandCount * commandDelay);586 commandCount++;587 }588 else {589 execChangeRootSize();590 }591}592//-------------------------------------------------------------------------------------------------------593function execCutCommand() {594 document.execCommand("Cut");595 debugForDumpAsText("execCutCommand");596}597function cutCommand() {598 if (commandDelay > 0) {599 window.setTimeout(execCutCommand, commandCount * commandDelay);600 commandCount++;601 }602 else {603 execCutCommand();604 }605}606//-------------------------------------------------------------------------------------------------------607function execCopyCommand() {608 document.execCommand("Copy");609 debugForDumpAsText("execCopyCommand");610}611function copyCommand() {612 if (commandDelay > 0) {613 window.setTimeout(execCopyCommand, commandCount * commandDelay);614 commandCount++;615 }616 else {617 execCopyCommand();618 }619}620//-------------------------------------------------------------------------------------------------------621function execPasteCommand() {622 document.execCommand("Paste");623 debugForDumpAsText("execPasteCommand");624}625function pasteCommand() {626 if (commandDelay > 0) {627 window.setTimeout(execPasteCommand, commandCount * commandDelay);628 commandCount++;629 }630 else {631 execPasteCommand();632 }633}634//-------------------------------------------------------------------------------------------------------635function execCreateLinkCommand(url) {636 document.execCommand("CreateLink", false, url);637 debugForDumpAsText("execCreateLinkCommand");638}639function createLinkCommand(url) {640 if (commandDelay > 0) {641 window.setTimeout(execCreateLinkCommand, commandCount * commandDelay, url);642 commandCount++;643 } else644 execCreateLinkCommand(url);645}646//-------------------------------------------------------------------------------------------------------647function execUnlinkCommand() {648 document.execCommand("Unlink");649 debugForDumpAsText("execUnlinkCommand");650}651function unlinkCommand() {652 if (commandDelay > 0) {653 window.setTimeout(execUnlinkCommand, commandCount * commandDelay);654 commandCount++;655 } else656 execUnlinkCommand();657}658//-------------------------------------------------------------------------------------------------------659function execPasteAndMatchStyleCommand() {660 document.execCommand("PasteAndMatchStyle");661 debugForDumpAsText("execPasteAndMatchStyleCommand");662}663function pasteAndMatchStyleCommand() {664 if (commandDelay > 0) {665 window.setTimeout(execPasteAndMatchStyleCommand, commandCount * commandDelay);666 commandCount++;667 }668 else {669 execPasteAndMatchStyleCommand();670 }671}672//-------------------------------------------------------------------------------------------------------673function execDeleteCommand() {674 document.execCommand("Delete");675 debugForDumpAsText("execDeleteCommand");676}677function deleteCommand() {678 if (commandDelay > 0) {679 window.setTimeout(execDeleteCommand, commandCount * commandDelay);680 commandCount++;681 }682 else {683 execDeleteCommand();684 }685}686//-------------------------------------------------------------------------------------------------------687function execForwardDeleteCommand() {688 document.execCommand("ForwardDelete");689 debugForDumpAsText("execForwardDeleteCommand");690}691function forwardDeleteCommand() {692 if (commandDelay > 0) {693 window.setTimeout(execForwardDeleteCommand, commandCount * commandDelay);694 commandCount++;695 }696 else {697 execForwardDeleteCommand();698 }699}700//-------------------------------------------------------------------------------------------------------701function runEditingTest() {702 if (window.layoutTestController)703 layoutTestController.dumpEditingCallbacks();704 var elem = document.getElementById("test");705 var selection = window.getSelection();706 selection.setPosition(elem, 0);707 editingTest();708}709var dumpAsText = false;710var markupResultList = document.createElement('ol');711function runDumpAsTextEditingTest(enableCallbacks) {712 if (window.layoutTestController) {713 layoutTestController.dumpAsText();714 if (enableCallbacks)715 layoutTestController.dumpEditingCallbacks();716 }717 dumpAsText = true;718 var elem = document.getElementById("test");719 var selection = window.getSelection();720 selection.setPosition(elem, 0);721 editingTest();722 document.body.appendChild(markupResultList);723}724function debugForDumpAsText(name) {725 if (dumpAsText && document.getElementById("root")) {726 var newItem = document.createElement('li');727 newItem.appendChild(document.createTextNode(name+": "+document.getElementById("root").innerHTML));728 markupResultList.appendChild(newItem);729 }730}731//-------------------------------------------------------------------------------------------------------732function execBackColorCommand() {733 document.execCommand("BackColor", false, "Chartreuse");734 debugForDumpAsText('execBackColorCommand');735}736function backColorCommand() {737 if (commandDelay > 0) {738 window.setTimeout(execBackColorCommand, commandCount * commandDelay);739 commandCount++;740 }741 else {742 execBackColorCommand();743 }744}745function execForeColorCommand(color) {746 document.execCommand("ForeColor", false, color);747 debugForDumpAsText('execForeColorCommand');748}749function foreColorCommand(color) {750 if (commandDelay > 0) {751 window.setTimeout(execForeColorCommand, commandCount * commandDelay, color);752 commandCount++;753 } else754 execForeColorCommand(color);755}756//-------------------------------------------------------------------------------------------------------757function runCommand(command, arg1, arg2) {758 document.execCommand(command,arg1,arg2);759}760function executeCommand(command,arg1,arg2) {761 if (commandDelay > 0) {762 window.setTimeout(runCommand, commandCount * commandDelay);763 commandCount++;764 }765 else {766 runCommand(command,arg1,arg2);767 }...

Full Screen

Full Screen

commands.js

Source:commands.js Github

copy

Full Screen

1// Copyright 2012 Selenium committers2// Copyright 2012 Software Freedom Conservancy3//4// Licensed under the Apache License, Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS,12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13// See the License for the specific language governing permissions and14// limitations under the License.15/**16 * @fileoverview Command handlers used by the SafariDriver's injected script.17 */18goog.provide('safaridriver.inject.commands');19goog.require('bot');20goog.require('bot.Error');21goog.require('bot.ErrorCode');22goog.require('bot.action');23goog.require('bot.dom');24goog.require('bot.frame');25goog.require('bot.inject');26goog.require('bot.inject.cache');27goog.require('bot.locators');28goog.require('bot.window');29goog.require('goog.array');30goog.require('goog.debug.Logger');31goog.require('goog.math.Coordinate');32goog.require('goog.math.Size');33goog.require('goog.net.cookies');34goog.require('goog.style');35goog.require('safaridriver.inject.CommandRegistry');36goog.require('safaridriver.inject.message.Activate');37goog.require('webdriver.atoms.element');38/**39 * @private {!goog.debug.Logger}40 * @const41 */42safaridriver.inject.commands.LOG_ = goog.debug.Logger.getLogger(43 'safaridriver.inject.commands');44/** @return {string} The name of the current window. */45safaridriver.inject.commands.getWindowName = function() {46 return window.name;47};48/** @return {string} The current URL. */49safaridriver.inject.commands.getCurrentUrl = function() {50 return window.location.href;51};52/**53 * Loads a new URL in the current page.54 * @param {!safaridriver.Command} command The command object.55 */56safaridriver.inject.commands.loadUrl = function(command) {57 window.location.href = /** @type {string} */ (command.getParameter('url'));58 // No need to send a response. The global page should be listening for the59 // navigate event.60};61/** Reloads the current page. */62safaridriver.inject.commands.reloadPage = function() {63 window.location.reload();64 // No need to send a response. The global page should be listening for the65 // navigate event.66};67/**68 * Stub that reports an error that navigating through the browser history does69 * not work for the SafariDriver.70 */71safaridriver.inject.commands.unsupportedHistoryNavigation = function() {72 throw Error('Yikes! Safari history navigation does not work. We can ' +73 'go forward or back, but once we do, we can no longer ' +74 'communicate with the page...');75};76/** @return {string} The document title. */77safaridriver.inject.commands.getTitle = function() {78 return document.title;79};80/** @return {string} A string representation of the current page source. */81safaridriver.inject.commands.getPageSource = function() {82 return new XMLSerializer().serializeToString(document);83};84/**85 * Defines an element locating command.86 * @param {function(!Object, (Document|Element)=):87 * (Element|!goog.array.ArrayLike.<Element>)} locatorFn The locator function88 * that should be used.89 * @return {function(!safaridriver.Command): !bot.response.ResponseObject} The90 * locator command function.91 * @private92 */93safaridriver.inject.commands.findElementCommand_ = function(locatorFn) {94 return function(command) {95 var locator = {};96 locator[command.getParameter('using')] = command.getParameter('value');97 var args = [locator];98 if (command.getParameter('id')) {99 args.push({'ELEMENT': command.getParameter('id')});100 }101 return bot.inject.executeScript(locatorFn, args);102 };103};104/**105 * Locates an element on the page.106 * @param {!safaridriver.Command} command The command object.107 * @return {!bot.response.ResponseObject} The command response.108 */109safaridriver.inject.commands.findElement =110 safaridriver.inject.commands.findElementCommand_(bot.locators.findElement);111/**112 * Locates multiple elements on the page.113 * @param {!safaridriver.Command} command The command object.114 * @return {bot.response.ResponseObject} The command response.115 */116safaridriver.inject.commands.findElements =117 safaridriver.inject.commands.findElementCommand_(bot.locators.findElements);118/**119 * Retrieves the element that currently has focus.120 * @return {!bot.response.ResponseObject} The response object.121 */122safaridriver.inject.commands.getActiveElement = function() {123 var getActiveElement = goog.partial(bot.dom.getActiveElement, document);124 return /** @type {!bot.response.ResponseObject} */ (bot.inject.executeScript(125 getActiveElement, []));126};127/**128 * Adds a new cookie to the page.129 * @param {!safaridriver.Command} command The command object.130 */131safaridriver.inject.commands.addCookie = function(command) {132 var cookie = command.getParameter('cookie');133 // The WebDriver wire protocol defines cookie expiration times in seconds134 // since midnight, January 1, 1970 UTC, but goog.net.Cookies expects them135 // to be in seconds since "right now".136 var maxAge = cookie['expiry'];137 if (goog.isNumber(maxAge)) {138 maxAge = new Date(maxAge - goog.now());139 }140 // TODO: check whether cookie['domain'] is valid.141 goog.net.cookies.set(cookie['name'], cookie['value'], maxAge,142 cookie['path'], cookie['domain'], cookie['secure']);143};144/**145 * @return {!Array.<{name:string, value:string}>} A list of the cookies visible146 * to the current page.147 */148safaridriver.inject.commands.getCookies = function() {149 var keys = goog.net.cookies.getKeys();150 return goog.array.map(keys, function(key) {151 return {152 'name': key,153 'value': goog.net.cookies.get(key)154 };155 });156};157/** Deletes all cookies visible to the current page. */158safaridriver.inject.commands.deleteCookies = function() {159 goog.net.cookies.clear();160};161/**162 * Deletes a specified cookie.163 * @param {!safaridriver.Command} command The command object.164 */165safaridriver.inject.commands.deleteCookie = function(command) {166 goog.net.cookies.remove(/** @type {string} */ (command.getParameter('name')));167};168/**169 * Creates a command that targets a specific DOM element.170 * @param {!Function} handlerFn The actual handler function. The first parameter171 * should be the Element to target.172 * @param {...string} var_args Any named parameters which should be extracted173 * and passed as arguments to {@code commandFn}.174 * @return {function(!safaridriver.Command)} The new element command function.175 * @private176 */177safaridriver.inject.commands.elementCommand_ = function(handlerFn, var_args) {178 var keys = goog.array.slice(arguments, 1);179 return function(command) {180 command = safaridriver.inject.commands.util.prepareElementCommand(command);181 var element = command.getParameter('id');182 var args = goog.array.concat(element, goog.array.map(keys, function(key) {183 return command.getParameter(key);184 }));185 return bot.inject.executeScript(handlerFn, args);186 };187};188/**189 * @param {!safaridriver.Command} command The command to execute.190 * @see bot.action.clear191 */192safaridriver.inject.commands.clearElement =193 safaridriver.inject.commands.elementCommand_(bot.action.clear);194/**195 * @param {!safaridriver.Command} command The command to execute.196 * @see bot.action.click197 */198safaridriver.inject.commands.clickElement =199 safaridriver.inject.commands.elementCommand_(bot.action.click);200/**201 * @param {!safaridriver.Command} command The command to execute.202 * @see bot.action.submit203 */204safaridriver.inject.commands.submitElement =205 safaridriver.inject.commands.elementCommand_(bot.action.submit);206/**207 * @param {!safaridriver.Command} command The command to execute.208 * @see webdriver.atoms.element.getAttribute209 */210safaridriver.inject.commands.getElementAttribute =211 safaridriver.inject.commands.elementCommand_(212 webdriver.atoms.element.getAttribute, 'name');213/**214 * @param {!safaridriver.Command} command The command to execute.215 * @see goog.style.getPageOffset216 */217safaridriver.inject.commands.getElementLocation =218 safaridriver.inject.commands.elementCommand_(goog.style.getPageOffset);219/**220 * @param {!safaridriver.Command} command The command to execute.221 * @see webdriver.atoms.element.getLocationInView222 */223safaridriver.inject.commands.getLocationInView =224 safaridriver.inject.commands.elementCommand_(225 webdriver.atoms.element.getLocationInView);226/**227 * @param {!safaridriver.Command} command The command to execute.228 * @see goog.style.getSize229 */230safaridriver.inject.commands.getElementSize =231 safaridriver.inject.commands.elementCommand_(goog.style.getSize);232/**233 * @param {!safaridriver.Command} command The command to execute.234 * @see webdriver.atoms.element.getText235 */236safaridriver.inject.commands.getElementText =237 safaridriver.inject.commands.elementCommand_(238 webdriver.atoms.element.getText);239/**240 * @param {!safaridriver.Command} command The command to execute.241 */242safaridriver.inject.commands.getElementTagName =243 safaridriver.inject.commands.elementCommand_(function(el) {244 return el.tagName.toLowerCase();245 });246/**247 * @param {!safaridriver.Command} command The command to execute.248 * @see bot.dom.isShown249 */250safaridriver.inject.commands.isElementDisplayed =251 safaridriver.inject.commands.elementCommand_(bot.dom.isShown);252/**253 * @param {!safaridriver.Command} command The command to execute.254 * @see bot.dom.isEnabled255 */256safaridriver.inject.commands.isElementEnabled =257 safaridriver.inject.commands.elementCommand_(bot.dom.isEnabled);258/**259 * @param {!safaridriver.Command} command The command to execute.260 * @see webdriver.atoms.element.isSelected261 */262safaridriver.inject.commands.isElementSelected =263 safaridriver.inject.commands.elementCommand_(264 webdriver.atoms.element.isSelected);265/**266 * @param {!safaridriver.Command} command The command to execute.267 */268safaridriver.inject.commands.elementEquals =269 safaridriver.inject.commands.elementCommand_(function(a, b) {270 return a === b;271 }, 'other');272/**273 * @param {!safaridriver.Command} command The command to execute.274 * @see bot.dom.getEffectiveStyle275 */276safaridriver.inject.commands.getCssValue =277 safaridriver.inject.commands.elementCommand_(bot.dom.getEffectiveStyle,278 'propertyName');279/**280 * @return {!goog.math.Coordinate} The position of the window.281 * @see bot.window.getPosition282 */283safaridriver.inject.commands.getWindowPosition = function() {284 return bot.window.getPosition();285};286/**287 * @param {!safaridriver.Command} command The command to execute.288 * @see bot.window.setPosition289 */290safaridriver.inject.commands.setWindowPosition = function(command) {291 var position = new goog.math.Coordinate(292 /** @type {number} */ (command.getParameter('x')),293 /** @type {number} */ (command.getParameter('y')));294 bot.window.setPosition(position);295};296/**297 * @return {!goog.math.Size} The size of the window.298 * @see bot.window.getSize299 */300safaridriver.inject.commands.getWindowSize = function() {301 return bot.window.getSize();302};303/**304 * @param {!safaridriver.Command} command The command to execute.305 * @see bot.window.setSize306 */307safaridriver.inject.commands.setWindowSize = function(command) {308 var size = new goog.math.Size(309 /** @type {number} */ (command.getParameter('width')),310 /** @type {number} */ (command.getParameter('height')));311 bot.window.setSize(size);312};313/** Maximizes the window. */314safaridriver.inject.commands.maximizeWindow = function() {315 window.moveTo(0, 0);316 window.resizeTo(window.screen.width, window.screen.height);317};318/**319 * Executes a command in the context of the current page.320 * @param {!safaridriver.Command} command The command to execute.321 * @param {!safaridriver.inject.Tab} tab A reference to the tab issuing this322 * command.323 * @return {!webdriver.promise.Promise} A promise that will be resolved with the324 * {@link bot.response.ResponseObject} from the page.325 * @throws {Error} If there is an error while sending the command to the page.326 */327safaridriver.inject.commands.executeInPage = function(command, tab) {328 command = safaridriver.inject.commands.util.prepareElementCommand(command);329 return tab.executeInPage(command);330};331/**332 * Locates a frame and sends a message to it to activate itself with the333 * extension. The located frame will be334 * @param {!safaridriver.Command} command The command to execute.335 * the target of all subsequent commands.336 * @throws {Error} If there is an error whilst locating the frame.337 */338safaridriver.inject.commands.switchToFrame = function(command) {339 var id = command.getParameter('id');340 var frameWindow;341 if (goog.isNull(id)) {342 safaridriver.inject.commands.LOG_.info('Resetting focus to window.top');343 frameWindow = window.top;344 } else if (goog.isString(id)) {345 safaridriver.inject.commands.LOG_.info(346 'Switching to frame by name or ID: ' + id);347 frameWindow = bot.frame.findFrameByNameOrId(/** @type {string} */ (id));348 } else if (goog.isNumber(id)) {349 safaridriver.inject.commands.LOG_.info(350 'Switching to frame by index: ' + id);351 frameWindow = bot.frame.findFrameByIndex(/** @type {number} */ (id));352 } else {353 var elementKey = /** @type {string} */ (id[bot.inject.ELEMENT_KEY]);354 safaridriver.inject.commands.LOG_.info('Switching to frame by ' +355 'WebElement: ' + elementKey);356 // ID must be a WebElement. Pull it from the cache.357 var frameElement = bot.inject.cache.getElement(elementKey);358 frameWindow = bot.frame.getFrameWindow(359 /** @type {!(HTMLIFrameElement|HTMLFrameElement)} */ (frameElement));360 }361 if (!frameWindow) {362 throw new bot.Error(bot.ErrorCode.NO_SUCH_FRAME,363 'Unable to locate frame with ' + id);364 }365 // De-activate ourselves. We should no longer respond to commands until366 // we are re-activated.367 safaridriver.inject.Tab.getInstance().setActive(false);368 var message = new safaridriver.inject.message.Activate(command);369 message.send(frameWindow);370};371goog.scope(function() {372var CommandName = webdriver.CommandName;373var commands = safaridriver.inject.commands;374// Commands that should be defined for every frame.375safaridriver.inject.CommandRegistry.getInstance()376 .defineModule(safaridriver.inject.commands.module.ID, goog.object.create(377 CommandName.ADD_COOKIE, commands.addCookie,378 CommandName.CLEAR_ELEMENT, commands.clearElement,379 CommandName.CLICK_ELEMENT, commands.clickElement,380 CommandName.DELETE_ALL_COOKIES, commands.deleteCookies,381 CommandName.DELETE_COOKIE, commands.deleteCookie,382 CommandName.ELEMENT_EQUALS, commands.elementEquals,383 CommandName.FIND_CHILD_ELEMENT, commands.findElement,384 CommandName.FIND_CHILD_ELEMENTS, commands.findElements,385 CommandName.FIND_ELEMENT, commands.findElement,386 CommandName.FIND_ELEMENTS, commands.findElements,387 CommandName.GET, commands.loadUrl,388 CommandName.GET_ACTIVE_ELEMENT, commands.getActiveElement,389 CommandName.GET_ALL_COOKIES, commands.getCookies,390 CommandName.GET_CURRENT_URL, commands.getCurrentUrl,391 CommandName.GET_ELEMENT_ATTRIBUTE, commands.getElementAttribute,392 CommandName.GET_ELEMENT_LOCATION, commands.getElementLocation,393 CommandName.GET_ELEMENT_LOCATION_IN_VIEW, commands.getLocationInView,394 CommandName.GET_ELEMENT_SIZE, commands.getElementSize,395 CommandName.GET_ELEMENT_TAG_NAME, commands.getElementTagName,396 CommandName.GET_ELEMENT_TEXT, commands.getElementText,397 CommandName.GET_ELEMENT_VALUE_OF_CSS_PROPERTY, commands.getCssValue,398 CommandName.GET_PAGE_SOURCE, commands.getPageSource,399 CommandName.GET_TITLE, commands.getTitle,400 CommandName.GET_WINDOW_POSITION, commands.getWindowPosition,401 CommandName.GET_WINDOW_SIZE, commands.getWindowSize,402 CommandName.GO_BACK, commands.unsupportedHistoryNavigation,403 CommandName.GO_FORWARD, commands.unsupportedHistoryNavigation,404 CommandName.IS_ELEMENT_DISPLAYED, commands.isElementDisplayed,405 CommandName.IS_ELEMENT_ENABLED, commands.isElementEnabled,406 CommandName.IS_ELEMENT_SELECTED, commands.isElementSelected,407 CommandName.MAXIMIZE_WINDOW, commands.maximizeWindow,408 CommandName.REFRESH, commands.reloadPage,409 CommandName.SET_WINDOW_POSITION, commands.setWindowPosition,410 CommandName.SET_WINDOW_SIZE, commands.setWindowSize,411 CommandName.SUBMIT_ELEMENT, commands.submitElement,412 CommandName.SWITCH_TO_FRAME, commands.switchToFrame,413 // The extension handles window switches. It sends the command to this414 // injected script only as a means of retrieving the window name.415 CommandName.SWITCH_TO_WINDOW, commands.getWindowName));...

Full Screen

Full Screen

server.js

Source:server.js Github

copy

Full Screen

1// Copyright 2012 Selenium committers2// Copyright 2012 Software Freedom Conservancy3//4// Licensed under the Apache License, Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS,12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13// See the License for the specific language governing permissions and14// limitations under the License.15goog.provide('safaridriver.extension.Server');16goog.require('bot.ErrorCode');17goog.require('bot.response');18goog.require('goog.Disposable');19goog.require('goog.debug.Logger');20goog.require('goog.object');21goog.require('goog.string');22goog.require('safaridriver.Command');23goog.require('safaridriver.alert');24goog.require('safaridriver.extension.commands');25goog.require('safaridriver.message.Command');26goog.require('safaridriver.message.Response');27goog.require('webdriver.CommandName');28goog.require('webdriver.promise');29/**30 * Creates a new WebSocket server that may be used to communicate with a31 * SafariDriver client.32 *33 * <p>Note the name of this class is a bit misleading as it uses a WebSocket34 * to communicate with the client (i.e., the actual HTTP server is run by the35 * client).36 *37 * @param {!safaridriver.extension.Session} session The session associated with38 * this server.39 * @constructor40 * @implements {webdriver.CommandExecutor}41 * @extends {goog.Disposable}42 */43safaridriver.extension.Server = function(session) {44 goog.base(this);45 /** @private {!goog.debug.Logger} */46 this.log_ = goog.debug.Logger.getLogger('safaridriver.extension.Server');47 /** @private {!safaridriver.extension.Session} */48 this.session_ = session;49 /** @private {!webdriver.promise.Deferred} */50 this.ready_ = new webdriver.promise.Deferred();51 /** @private {!Array.<function()>} */52 this.disposeCallbacks_ = [];53};54goog.inherits(safaridriver.extension.Server, goog.Disposable);55/**56 * @typedef {(function(!safaridriver.extension.Session, !safaridriver.Command)|57 * function(!safaridriver.extension.Session))}58 */59safaridriver.extension.Server.CommandHandler;60/**61 * Maps command names to their handler functions.62 * @private {!Object.<webdriver.CommandName,63 * safaridriver.extension.Server.CommandHandler>}64 * @const65 */66safaridriver.extension.Server.COMMAND_MAP_ = {};67goog.scope(function() {68var CommandName = webdriver.CommandName;69var commands = safaridriver.extension.commands;70var map = safaridriver.extension.Server.COMMAND_MAP_;71map[CommandName.NEW_SESSION] = commands.newSession;72map[CommandName.DESCRIBE_SESSION] = commands.describeSession;73// We can't shutdown Safari from an extension, but we can quietly handle the74// command so we don't return an unknown command error.75map[CommandName.QUIT] = goog.nullFunction;76map[CommandName.CLOSE] = commands.closeTab;77map[CommandName.GET_CURRENT_WINDOW_HANDLE] = commands.getWindowHandle;78map[CommandName.GET_WINDOW_HANDLES] = commands.getWindowHandles;79map[CommandName.GET_CURRENT_URL] = commands.sendCommand;80map[CommandName.GET_TITLE] = commands.sendCommand;81map[CommandName.GET_PAGE_SOURCE] = commands.sendCommand;82map[CommandName.GET] = commands.loadUrl;83map[CommandName.REFRESH] = commands.refresh;84map[CommandName.GO_BACK] = commands.sendCommand;85map[CommandName.GO_FORWARD] = commands.sendCommand;86map[CommandName.GO_BACK] = commands.sendCommand;87map[CommandName.ADD_COOKIE] = commands.sendCommand;88map[CommandName.GET_ALL_COOKIES] = commands.sendCommand;89map[CommandName.DELETE_ALL_COOKIES] = commands.sendCommand;90map[CommandName.DELETE_COOKIE] = commands.sendCommand;91map[CommandName.IMPLICITLY_WAIT] = commands.implicitlyWait;92map[CommandName.FIND_ELEMENT] = commands.findElement;93map[CommandName.FIND_ELEMENTS] = commands.findElement;94map[CommandName.FIND_CHILD_ELEMENT] = commands.findElement;95map[CommandName.FIND_CHILD_ELEMENTS] = commands.findElement;96map[CommandName.GET_ACTIVE_ELEMENT] = commands.sendCommand;97map[CommandName.CLEAR_ELEMENT] = commands.sendCommand;98map[CommandName.CLICK_ELEMENT] = commands.sendCommand;99map[CommandName.SUBMIT_ELEMENT] = commands.sendCommand;100map[CommandName.GET_ELEMENT_TEXT] = commands.sendCommand;101map[CommandName.GET_ELEMENT_TAG_NAME] = commands.sendCommand;102map[CommandName.IS_ELEMENT_SELECTED] = commands.sendCommand;103map[CommandName.IS_ELEMENT_ENABLED] = commands.sendCommand;104map[CommandName.IS_ELEMENT_DISPLAYED] = commands.sendCommand;105map[CommandName.GET_ELEMENT_LOCATION] = commands.sendCommand;106map[CommandName.GET_ELEMENT_LOCATION_IN_VIEW] = commands.sendCommand;107map[CommandName.GET_ELEMENT_SIZE] = commands.sendCommand;108map[CommandName.GET_ELEMENT_ATTRIBUTE] = commands.sendCommand;109map[CommandName.GET_ELEMENT_VALUE_OF_CSS_PROPERTY] = commands.sendCommand;110map[CommandName.ELEMENT_EQUALS] = commands.sendCommand;111map[CommandName.SEND_KEYS_TO_ELEMENT] = commands.sendCommand;112map[CommandName.CLICK] = commands.sendCommand;113map[CommandName.DOUBLE_CLICK] = commands.sendCommand;114map[CommandName.MOUSE_DOWN] = commands.sendCommand;115map[CommandName.MOUSE_UP] = commands.sendCommand;116map[CommandName.MOVE_TO] = commands.sendCommand;117map[CommandName.SEND_KEYS_TO_ACTIVE_ELEMENT] = commands.sendCommand;118map[CommandName.SWITCH_TO_FRAME] = commands.sendCommand;119map[CommandName.SWITCH_TO_WINDOW] = commands.switchToWindow;120map[CommandName.SET_WINDOW_SIZE] = commands.sendWindowCommand;121map[CommandName.SET_WINDOW_POSITION] = commands.sendWindowCommand;122map[CommandName.GET_WINDOW_SIZE] = commands.sendWindowCommand;123map[CommandName.GET_WINDOW_POSITION] = commands.sendWindowCommand;124map[CommandName.MAXIMIZE_WINDOW] = commands.sendWindowCommand;125map[CommandName.EXECUTE_SCRIPT] = commands.sendCommand;126map[CommandName.EXECUTE_ASYNC_SCRIPT] = commands.executeAsyncScript;127map[CommandName.SET_SCRIPT_TIMEOUT] = commands.setScriptTimeout;128map[CommandName.SCREENSHOT] = commands.takeScreenshot;129map[CommandName.ACCEPT_ALERT] = commands.handleNoAlertsPresent;130map[CommandName.DISMISS_ALERT] = commands.handleNoAlertsPresent;131map[CommandName.GET_ALERT_TEXT] = commands.handleNoAlertsPresent;132map[CommandName.SET_ALERT_TEXT] = commands.handleNoAlertsPresent133map[CommandName.GET_AVAILABLE_LOG_TYPES] = commands.getAvailableLogTypes;134map[CommandName.GET_LOG] = commands.getLogs;135}); // goog.scope136/**137 * The WebSocket used by this instance, lazily initialized in {@link #connect}.138 * @private {WebSocket}139 */140safaridriver.extension.Server.prototype.webSocket_ = null;141/** @override */142safaridriver.extension.Server.prototype.disposeInternal = function() {143 this.logMessage_('Disposing of server', goog.debug.Logger.Level.FINE);144 if (this.webSocket_) {145 if (this.ready_.isPending()) {146 this.ready_.cancel(Error('Server has been disposed'));147 }148 this.disposeWebSocket_();149 }150 while (this.disposeCallbacks_.length) {151 var callback = this.disposeCallbacks_.shift();152 callback();153 }154 delete this.disposeCallbacks_;155 delete this.log_;156 delete this.session_;157 delete this.ready_;158 delete this.webSocket_;159 goog.base(this, 'disposeInternal');160};161/** @private */162safaridriver.extension.Server.prototype.disposeWebSocket_ = function() {163 if (this.webSocket_) {164 var webSocket = this.webSocket_;165 this.webSocket_ = null;166 webSocket.onopen = goog.nullFunction;167 webSocket.onclose = goog.nullFunction;168 webSocket.onmessage = goog.nullFunction;169 webSocket.onerror = goog.nullFunction;170 webSocket.close();171 }172};173/** @return {!safaridriver.extension.Session} The session for this server. */174safaridriver.extension.Server.prototype.getSession = function() {175 return this.session_;176};177/**178 * Registers a callback to be called when this server is disposed. If the server179 * has already been disposed, the callback will be invoked immediately.180 * @param {function()} fn The callback function.181 */182safaridriver.extension.Server.prototype.onDispose = function(fn) {183 if (this.isDisposed()) {184 fn();185 } else {186 this.disposeCallbacks_.push(fn);187 }188};189/**190 * Set of URLs that {@link safaridriver.extension.Server} instances are191 * connected to.192 * @private {!Object}193 */194safaridriver.extension.Server.connectedUrls_ = {};195/**196 * Connects to a server.197 * @param {string} url URL to connect to.198 * @return {!webdriver.promise.Promise} A promise that will be resolved when199 * this server has connected.200 * @throws {Error} If this server has already connected to a server.201 */202safaridriver.extension.Server.prototype.connect = function(url) {203 if (this.isDisposed()) {204 throw Error('This server has been disposed!');205 }206 if (this.webSocket_) {207 throw Error('This server has already connected!');208 }209 this.attemptConnect_(url);210 return this.ready_.promise;211};212/**213 * Attempts to open a WebSocket connection with the given URL.214 * @param {string} url The URL to attempt to connect to.215 * @private216 */217safaridriver.extension.Server.prototype.attemptConnect_ = function(url) {218 if (safaridriver.extension.Server.connectedUrls_[url]) {219 throw Error('Another instance is already connected to ' + url);220 }221 safaridriver.extension.Server.connectedUrls_[url] = true;222 this.logMessage_('Attempting to connect to ' + url);223 // Register the event handlers. Note that it is not possible for these224 // callbacks to be missed because it is registered after the web socket is225 // instantiated. Because of the synchronous nature of JavaScript, this code226 // will execute before the browser creates the resource and makes any calls227 // to these callbacks.228 this.webSocket_ = new WebSocket(url);229 this.webSocket_.onopen = goog.bind(this.onOpen_, this);230 this.webSocket_.onclose = goog.bind(this.onClose_, this, url);231 this.webSocket_.onmessage = goog.bind(this.onMessage_, this);232 this.webSocket_.onerror = goog.bind(this.onError_, this);233};234/**235 * Executes a single command once all those received before it have completed.236 * @param {!webdriver.Command} command The command to execute.237 * @param {function(Error, !bot.response.ResponseObject=)=} opt_callback A238 * callback function for adherence to the {@link webdriver.CommandExecutor}239 * interface.240 * @return {!webdriver.promise.Promise} A promise that will be resolved with a241 * {@link bot.response.ResponseObject} object once the command has242 * completed.243 */244safaridriver.extension.Server.prototype.execute = function(245 command, opt_callback) {246 // Normally command will be an instanceof safaridriver.Command, but it will be247 // a standard webdriver.Command if it came from248 // safaridriver.extension.driver (via the extension builder REPL).249 command = new safaridriver.Command(goog.string.getRandomString(),250 command.getName(), command.getParameters());251 var handler = safaridriver.extension.Server.COMMAND_MAP_[command.getName()];252 if (!handler) {253 this.logMessage_('Unknown command: ' + command.getName(),254 goog.debug.Logger.Level.SEVERE);255 return webdriver.promise.rejected(bot.response.createErrorResponse(256 Error('Unknown command: ' + command.getName())));257 }258 var description = this.session_.getId() + '::' + command.getName();259 var fn = goog.bind(this.executeCommand_, this, command, handler);260 var flow = webdriver.promise.controlFlow();261 var result = flow.execute(fn, description).262 then(bot.response.createResponse, bot.response.createErrorResponse).263 thenFinally(goog.bind(function(response) {264 this.session_.setCurrentCommand(null);265 return response;266 }, this));267 // If we were given a callback, massage the result to fit the268 // webdriver.CommandExecutor contract.269 if (opt_callback) {270 result.then(bot.response.checkResponse).271 then(goog.partial(opt_callback, null), opt_callback);272 }273 return result;274};275/**276 * @param {!safaridriver.Command} command The command to execute.277 * @param {safaridriver.extension.Server.CommandHandler} handler The command278 * handler.279 * @return {*} The command result.280 * @private281 */282safaridriver.extension.Server.prototype.executeCommand_ = function(283 command, handler) {284 this.logMessage_('Executing command: ' + command.getName());285 var alertText = this.session_.getUnhandledAlertText();286 if (!goog.isNull(alertText)) {287 this.session_.setUnhandledAlertText(null);288 return safaridriver.alert.createResponse(alertText);289 }290 this.session_.setCurrentCommand(command);291 return handler(this.session_, command);292};293/**294 * @param {string} message The message to log.295 * @param {goog.debug.Logger.Level=} opt_level The level to log the message at;296 * Defaults to INFO.297 * @private298 */299safaridriver.extension.Server.prototype.logMessage_ = function(300 message, opt_level) {301 this.log_.log(opt_level || goog.debug.Logger.Level.INFO,302 '[' + this.session_.getId() + '] ' + message);303};304/**305 * Called when the WebSocket connection is opened.306 * @private307 */308safaridriver.extension.Server.prototype.onOpen_ = function() {309 this.logMessage_('WebSocket connection established.');310 if (!this.isDisposed() && this.ready_.isPending()) {311 this.ready_.fulfill();312 }313};314/**315 * Called when an attempt to open the WebSocket fails or there is a connection316 * failure after a successful connection has been established. Triggers the317 * disposable of this server.318 * @param {string} url The URL the WebSocket was connected to.319 * @private320 */321safaridriver.extension.Server.prototype.onClose_ = function(url) {322 safaridriver.extension.Server.connectedUrls_[url] = false;323 this.logMessage_('WebSocket connection was closed.',324 goog.debug.Logger.Level.WARNING);325 if (!this.isDisposed()) {326 if (this.ready_.isPending()) {327 var message = 'Failed to connect to ' + url;328 this.logMessage_(message);329 this.disposeWebSocket_();330 setTimeout(goog.bind(this.attemptConnect_, this, url), 500);331 } else {332 this.dispose();333 }334 }335};336/**337 * Called when there is a communication error with the WebSocket.338 * @param {!MessageEvent} event The error event.339 * @private340 */341safaridriver.extension.Server.prototype.onError_ = function(event) {342 this.logMessage_('There was an error in the WebSocket: ' + event.data,343 goog.debug.Logger.Level.SEVERE);344};345/**346 * Called when the WebSocket receives a message.347 * @param {!MessageEvent} event The message event.348 * @private349 */350safaridriver.extension.Server.prototype.onMessage_ = function(event) {351 this.logMessage_('Received a message: ' + event.data,352 goog.debug.Logger.Level.FINER);353 try {354 var message = safaridriver.message.fromEvent(event);355 if (!message.isType(safaridriver.message.Command.TYPE)) {356 throw Error('Not a command message: ' + message);357 }358 } catch (ex) {359 this.send_(null, bot.response.createErrorResponse(ex));360 return;361 }362 var command = message.getCommand();363 this.execute(command).364 thenCatch(bot.response.createErrorResponse).365 then(goog.bind(function(response) {366 this.send_(command, response);367 }, this));368};369/**370 * Sends a response to the client.371 * @param {safaridriver.Command} command The command this is a response to, or372 * {@code null} if the response indicates a parse error with the command.373 * @param {!bot.response.ResponseObject} response The response to send.374 * @private375 */376safaridriver.extension.Server.prototype.send_ = function(command, response) {377 var id = command ? command.id : '';378 var message = new safaridriver.message.Response(id, response);379 var str = message.toString();380 this.logMessage_('Sending response: ' + str);381 if (!command && response['status'] === bot.ErrorCode.SUCCESS) {382 this.logMessage_('Sending success response with a null command: ' + str,383 goog.debug.Logger.Level.WARNING);384 }385 this.webSocket_.send(str);...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run lisa automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful