Best JavaScript code snippet using playwright-internal
chat.js
Source:chat.js
1var app = getApp();2const qiniuUploader = require("../../../utils/sdk/qiniu/qiniuUploader");3const {4 request5} = require('./../../../utils/request.js');6const common = require('./../../../utils/common.js');7let baseConfig = require('./../../../utils/config.js')8var socketOpen = false;9var frameBuffer_Data, session, SocketTask;10var url = 'wss://group.gzywudao.top/wss'; //é¿é¾æ¥æ¥å£11var timing; //å®æ¶12Page({13 data: {14 inputValue: '',15 InputBottom: 0, //è¾å
¥æ¡äº¤äº16 crowd_id: null, //群id17 crowd_name: null, //群å称18 owner_id: null, //群主id19 user_id: null, //ç¨æ·id20 chatdata: [], //è天记å½æ°æ®21 groupnum: 0, //å¨çº¿äººæ°22 offchat: 0, //æ¯å¦ç¦è¨ã0æ£å¸¸1ç¦è¨23 modalName: null,24 scrollTop: 10000000,25 CustomBar: app.globalData.CustomBar,26 onlinelist: [],//å¨çº¿äººæ°å表27 hideNotice: false,//å
³éå
¬å28 notice: '',//å
¬åå
容29 keyworddata: [],//æ¥è¯¢ç¾¤å
³é®å30 password: null,//æå¡å£ä»¤31 },32 //è¾å
¥æ¡äº¤äº33 InputFocus(e) {34 this.setData({35 InputBottom: e.detail.height36 })37 },38 InputBlur(e) {39 this.setData({40 InputBottom: 041 })42 },43 //跳转åéå
¬å页é¢44 pushnotice: function () {45 let crowd_id = this.data.crowd_id;46 wx.navigateTo({47 url: '/pages/group/chat/pushnotice/pushnotice?crowd_id=' + crowd_id48 })49 },50 //跳转å°æå¡è®¾ç½®é¡µé¢51 punchseting: function () {52 let crowd_id = this.data.crowd_id;53 wx.navigateTo({54 url: '/pages/group/chat/punchseting/punchseting?crowd_id=' + crowd_id55 })56 },57 //跳转å
³é®å设置页é¢58 keyword: function () {59 let crowd_id = this.data.crowd_id;60 wx.navigateTo({61 url: '/pages/group/chat/keyword/keyword?crowd_id=' + crowd_id62 })63 },64 //å
¬åå¼å§65 noticestart: function () {66 console.log("å
¬åå¼å§å¨èµ·æ¥")67 let data = {};68 var that = this;69 var oldlength = that.data.notice;70 if (!oldlength) {71 console.log("å
¬åä¸åå¨")72 return;73 }74 var length = oldlength * 12;75 // console.log("å
¬åé¿åº¦")76 // console.log(length)77 // return;78 var windowWidth = wx.getSystemInfoSync().windowWidth; // å±å¹å®½åº¦79 that.setData({80 length: length,81 windowWidth: windowWidth82 });83 //marqueeDistance: 10, //åå§æ»å¨è·ç¦»84 that.setData({85 marqueeDistance: windowWidth86 });87 that.noticerun();88 },89 //å
¬åå¨èµ·æ¥90 noticerun: function () {91 var that = this;92 that.data.countTime = setInterval(function () {93 let noticelong = that.data.notice.length || 0;94 if (-that.data.marqueeDistance < noticelong * 12) {95 that.setData({96 marqueeDistance: that.data.marqueeDistance - 1,//1æ¯æ»å¨é度97 });98 } else {99 clearInterval(that.data.countTime);100 that.setData({101 marqueeDistance: that.data.windowWidth102 });103 that.noticerun();104 }105 }, 20);//20æ¯æ¶é´é´éï¼åæ»106 },107 //å
³éå
¬å108 closeNotice: function () {109 this.setData({110 hideNotice: true111 })112 },113 // 页é¢å è½½114 onLoad: function (e) {115 let user_id = wx.getStorageSync('userdata').id;116 this.setData({117 crowd_id: e.crowd_id,118 crowd_name: e.crowd_name,119 user_id: user_id120 })121 // this.textdata()122 // this.noticestart()//å
¬åå¨èµ·æ¥123 this.chatconfig()124 this.havekeyword()125 this.punchdata()126 },127 onShow: function (e) {128 if (!socketOpen) {129 this.webSocket()130 }131 this.sendCode()132 },133 //å®æ¶åéæ¶æ¯å°æå¡å¨134 sendCode: function (e) {135 var that = this;136 var times = 0137 timing = setInterval(function () {138 times++139 if (times >= 15) {140 let data = {141 type: "ping"142 }143 sendSocketMessage(data)144 times = 0145 } else {146 //console.log("æ¶é´æ²¡å°ä¸åå¿è·³")147 }148 }, 2000) //两ç§æ§è¡ä¸æ¬¡149 },150 //è·åé
置信æ¯151 chatconfig: function () {152 let crowd_id = this.data.crowd_id;153 request({154 service: 'group/chat/chatconfig',155 method: 'GET',156 data: {157 crowd_id: crowd_id,158 },159 success: res => {160 console.log("é
置信æ¯", res)161 this.setData({162 chatdata: res.chatdata,163 owner_id: res.configdata.owner_id,164 offchat: res.configdata.offchat,165 notice: res.configdata.notice,166 })167 this.noticestart()//å
¬åå¨èµ·æ¥168 setTimeout(function () {169 wx.pageScrollTo({170 scrollTop: 10000000,171 })172 }, 1000);173 }174 })175 },176 punchdata: function () {177 let crowd_id = this.data.crowd_id178 request({179 service: 'group/punchcard/querypunchdata',180 method: 'GET',181 data: {182 crowd_id: crowd_id,183 },184 success: res => {185 let punchdata = res.punchdata;186 if (punchdata) {187 this.setData({188 password: punchdata.password,189 })190 }191 },192 })193 },194 //è·åå
³é®åé
ç½®195 havekeyword: function () {196 var that = this197 let crowd_id = this.data.crowd_id;198 request({199 service: 'group/chatkeyword/crowdkeyword',200 method: 'GET',201 data: {202 crowd_id: crowd_id,203 type: 1//æ¥è¯¢å¼å¯çå
³é®å204 },205 success: res => {206 console.log("è·å群设置çå¼å¯çå
³é®å", res)207 that.setData({208 keyworddata: res.data,209 })210 }211 })212 },213 //æ°æ®åºä¿®æ¹ç¦è¨ç¶æ214 updateoffchat: function (offchat) {215 let crowd_id = this.data.crowd_id;216 request({217 service: 'group/chat/offchat',218 method: 'GET',219 data: {220 crowd_id: crowd_id,221 offchat: offchat222 },223 success: res => {224 console.log("ä¿®æ¹ç¦è¨ç¶ææå", res)225 }226 })227 },228 //ç¹å»ä¿®æ¹ç¦è¨ç¶æ229 clickoffchat: function () {230 let offchat = this.data.offchat;231 (offchat == 0) ? offchat = 1 : offchat = 0;232 this.setData({233 offchat: offchat,234 })235 this.updateoffchat(offchat) //è°æ¥å£æ¹ç¶æ236 console.log(offchat)237 let crowd_id = this.data.crowd_id;238 let data = {239 type: "offchat",240 message: "ä¿®æ¹ç¦è¨ç¶æ",241 to_client_id: "all",242 offchat: offchat,243 room_id: crowd_id244 }245 if (socketOpen) {246 sendSocketMessage(data)247 }248 },249 //页é¢å è½½é¾æ¥é¿é¾æ¥250 onReady: function () {251 console.log("å¼å§å è½½")252 var that = this;253 SocketTask.onOpen(res => {254 socketOpen = true;255 console.log('çå¬ WebSocket è¿æ¥æå¼äºä»¶ã', res)256 })257 SocketTask.onClose(onClose => {258 console.log('çå¬ WebSocket è¿æ¥å
³éäºä»¶ã', onClose)259 socketOpen = false;260 that.webSocket()261 })262 SocketTask.onError(onError => {263 console.log('çå¬ WebSocket é误ãé误信æ¯', onError)264 socketOpen = false265 })266 SocketTask.onMessage(onMessage => {267 console.log('çå¬WebSocketæ¥åå°æå¡å¨çæ¶æ¯äºä»¶ãæå¡å¨è¿åçæ¶æ¯', JSON.parse(onMessage.data))268 var onMessage_data = JSON.parse(onMessage.data)269 if (onMessage_data.type == "connect") {270 console.log("é¿é¾æ¥å建æå")271 that.userlogin()272 } else if (onMessage_data.type == "login" || onMessage_data.type == "bye") {273 console.log("ç¨æ·ç»å½æåï¼ä¿¡æ¯ç»å®æå")274 let groupnum = onMessage_data.groupnum; //å¨çº¿äººæ°275 let onlinelistdata = onMessage_data.onlinelist; //å¨çº¿å表276 var onlinelist = [];277 for (let key in onlinelistdata) {278 onlinelist.push(onlinelistdata[key])279 }280 that.setData({281 groupnum: groupnum,282 onlinelist: onlinelist283 })284 } else if (onMessage_data.type == "say") {285 console.log("ææ¶æ¯è¿æ¥ï¼å¤æä¸ä¸æ¯ä¸æ¯èªå·±ç,ä¸æ¯èªå·±åçæsetå°æ°æ®ä¸å»")286 if (onMessage_data.user_id != that.data.user_id) {287 that.data.chatdata.push(onMessage_data);288 that.setData({289 chatdata: this.data.chatdata,290 })291 wx.pageScrollTo({292 scrollTop: 10000000,293 })294 }295 } else if (onMessage_data.type == "ping") {296 console.log("æå¡å¨å¿è·³åè°")297 } else if (onMessage_data.type == "offchat") {298 console.log("ä¿®æ¹ç¦è¨ç¶æ")299 let offchat = onMessage_data.offchat;300 that.setData({301 offchat: offchat,302 })303 }304 return;305 })306 },307 //ç¨æ·ç»å½308 userlogin: function () {309 let user_id = wx.getStorageSync('userdata').id;310 let user_name = wx.getStorageSync('userdata').nickName;311 let avatarUrl = wx.getStorageSync('userdata').avatarUrl;312 let crowd_id = this.data.crowd_id;313 var data = {314 type: "login",315 message: "è¿åçæ°æ®",316 user_id: user_id,317 imgurl: avatarUrl,318 name: user_name,319 to_client_id: "all",320 room_id: crowd_id321 }322 if (socketOpen) {323 // å¦ææå¼äºsocketå°±åéæ°æ®ç»æå¡å¨324 sendSocketMessage(data)325 }326 },327 //åéå
容å328 sendmsg: function (content, say_type) {329 let user_id = wx.getStorageSync('userdata').id;330 let user_name = wx.getStorageSync('userdata').nickName;331 let avatarUrl = wx.getStorageSync('userdata').avatarUrl;332 let crowd_id = this.data.crowd_id;333 var data = {334 type: "say",335 message: "åéç»æå¡å¨çæ°æ®",336 user_id: user_id,337 imgurl: avatarUrl,338 name: user_name,339 to_client_id: "all",340 say_type: say_type,341 content: content,342 room_id: crowd_id343 }344 //å°æ°æ®setå°é¡µé¢ä¸345 this.data.chatdata.push(data);346 this.setData({347 chatdata: this.data.chatdata,348 inputValue: ''349 })350 console.log("å°é¡µé¢æ»å¨å°åºé¨")351 wx.pageScrollTo({352 scrollTop: 10000000,353 })354 if (socketOpen) {355 sendSocketMessage(data)356 }357 },358 // å建Socket359 webSocket: function () {360 SocketTask = wx.connectSocket({361 url: url,362 data: 'data',363 header: {364 'content-type': 'application/json'365 },366 method: 'post',367 success: function (res) {368 console.log('WebSocketè¿æ¥å建', res)369 },370 fail: function (err) {371 wx.showToast({372 title: 'ç½ç»å¼å¸¸ï¼',373 })374 wx.navigateBack({375 delta: 1376 })377 console.log(err)378 },379 })380 },381 // æ交æå382 submitTo: function (e) {383 console.log("æ交æå")384 var content = this.data.inputValue;385 if (content == '' || content == null) {386 wx.showToast({387 title: 'å
容ä¸è½ä¸ºç©ºï¼',388 icon: 'none'389 })390 return;391 }392 this.sendmsg(content, "text")393 this.punchcard(content)//æ£æ¥æå¡394 this.checkkeyword(content)395 },396 //æ£æ¥å
³é®å397 checkkeyword: function (content) {398 var that = this;399 let newcontent = content;400 let keyworddata = this.data.keyworddata;401 if (keyworddata.length > 0) {402 for (var i = 0; i < keyworddata.length; i++) {403 let newkeyword = keyworddata[i].keyword;404 // console.log("æå°å
³é®å", keyworddata[i])405 let keywordid = keyworddata[i].id;406 if (keyworddata[i].matching == 1) {407 if (newcontent == newkeyword) {408 // console.log("触åç²¾åå¹é
", newkeyword)409 if (keyworddata[i].content) {410 console.log("åéç²¾åå¹é
æ¶æ¯", newkeyword)411 that.setkeyword(keywordid, 'text', keyworddata[i].content)412 }413 if (keyworddata[i].cover) {414 console.log("åéç²¾åå¹é
æ¶æ¯", newkeyword)415 that.setkeyword(keywordid, 'image', keyworddata[i].cover)416 }417 }418 } else {419 console.log("模ç³å¹é
ææ¡", newkeyword)420 let successcheck = newkeyword.indexOf(newcontent) != -1;421 let newsuccesscheck = newcontent.indexOf(newkeyword) != -1;422 console.log("successcheck", successcheck)423 console.log("newsuccesscheck", newsuccesscheck)424 if (successcheck || newsuccesscheck) {425 console.log("触å模ç³å¹é
", newkeyword)426 if (keyworddata[i].content) {427 console.log("åé模ç³å¹é
æ¶æ¯", newkeyword)428 that.setkeyword(keywordid, 'text', keyworddata[i].content)429 }430 if (keyworddata[i].cover) {431 console.log("åé模ç³å¹é
æ¶æ¯", newkeyword)432 that.setkeyword(keywordid, 'image', keyworddata[i].cover)433 }434 }435 }436 }437 }438 },439 //触åå
³é®å440 setkeyword: function (id, newsay_type, newcontent) {441 let keywork_id = id;442 let say_type = newsay_type;443 let content = newcontent;444 let crowd_id = this.data.crowd_id;445 var data = {446 type: "keyword",447 message: "åéç»æå¡å¨çæ°æ®",448 keywork_id: keywork_id,449 to_client_id: "all",450 say_type: say_type,451 content: content,452 room_id: crowd_id453 }454 if (socketOpen) {455 sendSocketMessage(data)456 }457 },458 //ç¨æ·æå¡459 punchcard: function (content) {460 var that = this461 let password = this.data.password;462 if (content == password) {463 console.log("触åæå¡")464 let crowd_id = this.data.crowd_id;465 let user_id = wx.getStorageSync('userdata').id;466 request({467 service: 'group/punchcard/userpunchcard',468 method: 'GET',469 data: {470 crowd_id: crowd_id,471 user_id: user_id472 },473 success: res => {474 console.log("ç¨æ·æå¡æåè¿å", res)475 that.successpunchcard(res.message)476 // {"state":"200","message":"ç¨æ·æå¡æå","ifcontinuity_punch":false,"new_all_punch_number":10,"new_continuity_number":1,"ranking":1}477 }478 })479 }480 return;481 },482 //触åæå¡483 successpunchcard: function (newcontent) {484 let say_type = 'text';485 let content = newcontent;486 let crowd_id = this.data.crowd_id;487 var data = {488 type: "punchcard",489 message: "åéç»æå¡å¨çæ°æ®",490 to_client_id: "all",491 say_type: say_type,492 content: content,493 room_id: crowd_id494 }495 if (socketOpen) {496 sendSocketMessage(data)497 }498 },499 //é¿æè天ææ¡500 longclick: function (e) {501 //console.log("longclick",e)502 let data = e.currentTarget.dataset.data503 wx.setClipboardData({504 data: data,505 success: function (res) {506 wx.showToast({507 title: 'å¤å¶æå',508 icon: 'success',509 duration: 2000,510 })511 }512 })513 },514 //ç¨æ·è¾å
¥æå515 bindKeyInput: function (e) {516 //console.log("è¾å
¥æ¡è¾å
¥ææ¡£", e.detail.value)517 this.setData({518 inputValue: e.detail.value519 })520 },521 //ä¸ä¼ å¾ç522 upload: function (e) {523 var that = this;524 wx.chooseImage({525 count: 1, // é»è®¤1526 sizeType: ['original', 'compressed'], // å¯ä»¥æå®æ¯åå¾è¿æ¯å缩å¾ï¼é»è®¤äºè
é½æ527 sourceType: ['album', 'camera'], // å¯ä»¥æå®æ¥æºæ¯ç¸åè¿æ¯ç¸æºï¼é»è®¤äºè
é½æ528 success: function (res) {529 // console.log("è¿åéå®ç
§ççæ¬å°æ件路å¾å表", res)530 // // è¿åéå®ç
§ççæ¬å°æ件路å¾å表ï¼tempFilePathå¯ä»¥ä½ä¸ºimgæ ç¾çsrcå±æ§æ¾ç¤ºå¾ç531 let tempFilePaths = res.tempFilePaths[0];532 //console.log("æå°ä¸ä¼ ç
§ççæ¬å°è·¯å¾", res.tempFilePaths[0])533 that.qiuniuupload(tempFilePaths) //æ¿å°æ¬å°é¾æ¥ï¼å»è°ç¨ä¸çä¸ä¼ 534 }535 })536 },537 //æå¾çä¸ä¼ å°ä¸ç538 qiuniuupload: function (tempFilePaths) {539 var that = this;540 new Promise(function (resolve, reject) {541 qiniuUploader.upload(tempFilePaths, (res) => {542 let qiniuimgurl = res.imageURL;543 resolve(qiniuimgurl);544 //console.log('ä¸ä¼ ä¸çè¿å: ' , qiniuimgurl);545 }, (error) => {546 reject('error');547 console.log('error: ' + error);548 }, {549 region: 'ECN',550 uploadURL: 'https://up.qiniup.com',551 domain: 'http://groupsixty.gzywudao.top/',552 uptokenURL: baseConfig.host + 'qiniu/groupsixty',553 })554 }).then(function (qiniuimgurl) {555 that.sendmsg(qiniuimgurl, "image") //æ¿å°å¾çå°åå»åéæ¶æ¯556 })557 },558 //å¾çç¹å»äºä»¶559 imgYu: function (event) {560 var src = event.currentTarget.dataset.src; //è·ådata-src561 var imgList = [src]; //è·ådata-list562 //å¾çé¢è§563 wx.previewImage({564 current: src, // å½åæ¾ç¤ºå¾ççhttpé¾æ¥565 urls: imgList // éè¦é¢è§çå¾çhttpé¾æ¥å表566 })567 },568 //页é¢éèå°±å
³éè¿æ¥569 onHide: function () {570 // SocketTask.close(function (close) {571 // console.log('å
³é WebSocket è¿æ¥ã', close)572 // })573 clearInterval(timing)574 },575 showModal(e) {576 console.log("å¨çº¿äººå", this.data.onlinelist)577 this.setData({578 modalName: e.currentTarget.dataset.target579 })580 },581 hideModal(e) {582 this.setData({583 modalName: null584 })585 wx.pageScrollTo({586 scrollTop: 10000000,587 })588 },589 //页é¢å¸è½½å°±å
³éè¿æ¥590 onUnload: function () {591 SocketTask.close(function (close) {592 console.log('页é¢å¸è½½å°±å
³éè¿æ¥', close)593 })594 clearInterval(timing)595 }596})597//éè¿ WebSocket è¿æ¥åéæ°æ®ï¼éè¦å
wx.connectSocketï¼å¹¶å¨ wx.onSocketOpen åè°ä¹åæè½åéã598function sendSocketMessage(msg) {599 console.log("åéæ¶æ¯å°æå¡å¨", msg)600 var that = this;601 // console.log('éè¿ WebSocket è¿æ¥åéæ°æ®', JSON.stringify(msg))602 console.log('éè¿ WebSocket è¿æ¥åéæ°æ®')603 SocketTask.send({604 data: JSON.stringify(msg)605 }, function (res) {606 console.log('å·²åé', res)607 })...
average-position-bidding.js
Source:average-position-bidding.js
1// ID: fc0e24f9577d1f8f2279b1e5d4ee50f92/**3 *4 * Average Position Bidding Tool5 *6 * This script changes keyword bids so that they target specified positions,7 * based on recent performance.8 *9 * Version: 1.510 * Updated 2015-09-28 to correct for report column name changes11 * Updated 2016-02-05 to correct label reading, add extra checks and12 * be able to adjust maximum bid increases and decreases separately13 * Updated 2016-08-30 to correct label reading from reports14 * Updated 2016-09-14 to update keywords in batches15 * Updated 2016-10-26 to avoid DriveApp bug16 * Google AdWords Script maintained on brainlabsdigital.com17 *18 */19// Options20var maxBid = 3.00;21// Bids will not be increased past this maximum.22var minBid = 0.15;23// Bids will not be decreased below this minimum.24var firstPageMaxBid = 0.90;25// The script avoids reducing a keyword's bid below its first page bid estimate. If you think26// Google's first page bid estimates are too high then use this to overrule them.27var dataFile = 'AveragePositionData.txt';28// This name is used to create a file in your Google Drive to store today's performance so far,29// for reference the next time the script is run.30var useFirstPageBidsOnKeywordsWithNoImpressions = false;31// If this is true, then if a keyword has had no impressions since the last time the script was run32// its bid will be increased to the first page bid estimate (or the firsPageMaxBid if that is smaller).33// If this is false, keywords with no recent impressions will be left alone.34// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//35// Advanced Options36var bidIncreaseProportion = 0.2;37var bidDecreaseProportion = 0.2;38var targetPositionTolerance = 0.3;39// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//40function main() {41 var fieldJoin = ',';42 var lineJoin = '$';43 var idJoin = '#';44 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//45 var files = DriveApp.getFilesByName(dataFile);46 if (!files.hasNext()) {47 var file = DriveApp.createFile(dataFile, '\n');48 Logger.log("File '" + dataFile + "' has been created.");49 } else {50 var file = files.next();51 if (files.hasNext()) {52 Logger.log("Error - more than one file named '" + dataFile + "'");53 return;54 }55 Logger.log("File '" + dataFile + "' has been read.");56 }57 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//58 var labelIds = [];59 var labelIterator = AdWordsApp.labels()60 .withCondition('KeywordsCount > 0')61 .withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")62 .get();63 while (labelIterator.hasNext()) {64 var label = labelIterator.next();65 if (label.getName().substr(0, 'position '.length).toLowerCase() == 'position ') {66 labelIds.push(label.getId());67 }68 }69 if (labelIds.length == 0) {70 Logger.log('No position labels found.');71 return;72 }73 Logger.log(labelIds.length + ' position labels have been found.');74 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//75 var keywordData = {76 // UniqueId1: {LastHour: {Impressions: , AveragePosition: }, ThisHour: {Impressions: , AveragePosition: },77 // CpcBid: , FirstPageCpc: , MaxBid, MinBid, FirstPageMaxBid, PositionTarget: , CurrentAveragePosition:,78 // Criteria: }79 };80 var ids = [];81 var uniqueIds = [];82 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//83 var report = AdWordsApp.report(84 'SELECT Id, Criteria, AdGroupId, AdGroupName, CampaignName, Impressions, AveragePosition, CpcBid, FirstPageCpc, Labels, BiddingStrategyType '85 + 'FROM KEYWORDS_PERFORMANCE_REPORT '86 + 'WHERE Status = ENABLED AND AdGroupStatus = ENABLED AND CampaignStatus = ENABLED '87 + 'AND LabelIds CONTAINS_ANY [' + labelIds.join(',') + '] '88 + 'AND AdNetworkType2 = SEARCH '89 + 'AND Device NOT_IN ["HIGH_END_MOBILE"] '90 + 'DURING TODAY'91 );92 var rows = report.rows();93 while (rows.hasNext()) {94 var row = rows.next();95 if (row.BiddingStrategyType != 'cpc') {96 if (row.BiddingStrategyType == 'Enhanced CPC'97 || row.BiddingStrategyType == 'Target search page location'98 || row.BiddingStrategyType == 'Target Outranking Share'99 || row.BiddingStrategyType == 'None'100 || row.BiddingStrategyType == 'unknown') {101 Logger.log('Warning: keyword ' + row.Criteria + "' in campaign '" + row.CampaignName102 + "' uses '" + row.BiddingStrategyType + "' rather than manual CPC. This may overrule keyword bids and interfere with the script working.");103 } else {104 Logger.log('Warning: keyword ' + row.Criteria + "' in campaign '" + row.CampaignName105 + "' uses the bidding strategy '" + row.BiddingStrategyType + "' rather than manual CPC. This keyword will be skipped.");106 continue;107 }108 }109 var positionTarget = '';110 if (row.Labels.trim() == '--') {111 continue;112 }113 var labels = JSON.parse(row.Labels.toLowerCase()); // Labels are returned as a JSON formatted string114 for (var i = 0; i < labels.length; i++) {115 if (labels[i].substr(0, 'position '.length) == 'position ') {116 var positionTarget = parseFloat(labels[i].substr('position '.length - 1).replace(/,/g, '.'), 10);117 break;118 }119 }120 if (positionTarget == '') {121 continue;122 }123 if (integrityCheck(positionTarget) == -1) {124 Logger.log("Invalid position target '" + positionTarget + "' for keyword '" + row.Criteria + "' in campaign '" + row.CampaignName + "'");125 continue;126 }127 ids.push(parseFloat(row.Id, 10));128 var uniqueId = row.AdGroupId + idJoin + row.Id;129 uniqueIds.push(uniqueId);130 keywordData[uniqueId] = {};131 keywordData[uniqueId].Criteria = row.Criteria;132 keywordData[uniqueId].ThisHour = {};133 keywordData[uniqueId].ThisHour.Impressions = parseFloat(row.Impressions.replace(/,/g, ''), 10);134 keywordData[uniqueId].ThisHour.AveragePosition = parseFloat(row.AveragePosition.replace(/,/g, ''), 10);135 keywordData[uniqueId].CpcBid = parseFloat(row.CpcBid.replace(/,/g, ''), 10);136 keywordData[uniqueId].FirstPageCpc = parseFloat(row.FirstPageCpc.replace(/,/g, ''), 10);137 setPositionTargets(uniqueId, positionTarget);138 }139 Logger.log(uniqueIds.length + ' labelled keywords found');140 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//141 setBidChange();142 setMinMaxBids();143 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//144 var currentHour = parseInt(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), 'HH'), 10);145 if (currentHour != 0) {146 var data = file.getBlob().getDataAsString();147 var data = data.split(lineJoin);148 for (var i = 0; i < data.length; i++) {149 data[i] = data[i].split(fieldJoin);150 var uniqueId = data[i][0];151 if (keywordData.hasOwnProperty(uniqueId)) {152 keywordData[uniqueId].LastHour = {};153 keywordData[uniqueId].LastHour.Impressions = parseFloat(data[i][1], 10);154 keywordData[uniqueId].LastHour.AveragePosition = parseFloat(data[i][2], 10);155 }156 }157 }158 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//159 findCurrentAveragePosition();160 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//161 // Batch the keyword IDs, as the iterator can't take them all at once162 var idBatches = [];163 var batchSize = 5000;164 for (var i = 0; i < uniqueIds.length; i += batchSize) {165 idBatches.push(uniqueIds.slice(i, i + batchSize));166 }167 Logger.log('Updating keywords');168 // Update each batch169 for (var i = 0; i < idBatches.length; i++) {170 try {171 updateKeywords(idBatches[i]);172 } catch (e) {173 Logger.log('Error updating keywords: ' + e);174 Logger.log('Retrying after one minute.');175 Utilities.sleep(60000);176 updateKeywords(idBatches[i]);177 }178 }179 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//180 Logger.log('Writing file.');181 var content = resultsString();182 file.setContent(content);183 Logger.log('Finished.');184 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//185 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//186 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//187 // Functions188 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//189 function integrityCheck(target) {190 var n = parseFloat(target, 10);191 if (!isNaN(n) && n >= 1) {192 return n;193 }194 return -1;195 }196 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//197 function setPositionTargets(uniqueId, target) {198 if (target !== -1) {199 keywordData[uniqueId].HigherPositionTarget = Math.max(target - targetPositionTolerance, 1);200 keywordData[uniqueId].LowerPositionTarget = target + targetPositionTolerance;201 } else {202 keywordData[uniqueId].HigherPositionTarget = -1;203 keywordData[uniqueId].LowerPositionTarget = -1;204 }205 }206 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//207 function bidChange(uniqueId) {208 var newBid = -1;209 if (keywordData[uniqueId].HigherPositionTarget === -1) {210 return newBid;211 }212 var cpcBid = keywordData[uniqueId].CpcBid;213 var minBid = keywordData[uniqueId].MinBid;214 var maxBid = keywordData[uniqueId].MaxBid;215 if (isNaN(keywordData[uniqueId].FirstPageCpc)) {216 Logger.log("Warning: first page CPC estimate is not a number for keyword '" + keywordData[uniqueId].Criteria + "'. This keyword will be skipped");217 return -1;218 }219 var firstPageBid = Math.min(keywordData[uniqueId].FirstPageCpc, keywordData[uniqueId].FirstPageMaxBid, maxBid);220 var currentPosition = keywordData[uniqueId].CurrentAveragePosition;221 var higherPositionTarget = keywordData[uniqueId].HigherPositionTarget;222 var lowerPositionTarget = keywordData[uniqueId].LowerPositionTarget;223 var bidIncrease = keywordData[uniqueId].BidIncrease;224 var bidDecrease = keywordData[uniqueId].BidDecrease;225 if ((currentPosition > lowerPositionTarget) && (currentPosition !== 0)) {226 var linearBidModel = Math.min(2 * bidIncrease, (2 * bidIncrease / lowerPositionTarget) * (currentPosition - lowerPositionTarget));227 var newBid = Math.min((cpcBid + linearBidModel), maxBid);228 }229 if ((currentPosition < higherPositionTarget) && (currentPosition !== 0)) {230 var linearBidModel = Math.min(2 * bidDecrease, ((-4) * bidDecrease / higherPositionTarget) * (currentPosition - higherPositionTarget));231 var newBid = Math.max((cpcBid - linearBidModel), minBid);232 if (cpcBid > firstPageBid) {233 var newBid = Math.max(firstPageBid, newBid);234 }235 }236 if ((currentPosition === 0) && useFirstPageBidsOnKeywordsWithNoImpressions && (cpcBid < firstPageBid)) {237 var newBid = firstPageBid;238 }239 if (isNaN(newBid)) {240 Logger.log("Warning: new bid is not a number for keyword '" + keywordData[uniqueId].Criteria + "'. This keyword will be skipped");241 return -1;242 }243 return newBid;244 }245 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//246 function findCurrentAveragePosition() {247 for (var x in keywordData) {248 if (keywordData[x].hasOwnProperty('LastHour')) {249 keywordData[x].CurrentAveragePosition = calculateAveragePosition(keywordData[x]);250 } else {251 keywordData[x].CurrentAveragePosition = keywordData[x].ThisHour.AveragePosition;252 }253 }254 }255 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//256 function calculateAveragePosition(keywordDataElement) {257 var lastHourImpressions = keywordDataElement.LastHour.Impressions;258 var lastHourAveragePosition = keywordDataElement.LastHour.AveragePosition;259 var thisHourImpressions = keywordDataElement.ThisHour.Impressions;260 var thisHourAveragePosition = keywordDataElement.ThisHour.AveragePosition;261 if (thisHourImpressions == lastHourImpressions) {262 return 0;263 }264 var currentPosition = (thisHourImpressions * thisHourAveragePosition - lastHourImpressions * lastHourAveragePosition) / (thisHourImpressions - lastHourImpressions);265 if (currentPosition < 1) {266 return 0;267 }268 return currentPosition;269 }270 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//271 function keywordUniqueId(keyword) {272 var id = keyword.getId();273 var idsIndex = ids.indexOf(id);274 if (idsIndex === ids.lastIndexOf(id)) {275 return uniqueIds[idsIndex];276 }277 var adGroupId = keyword.getAdGroup().getId();278 return adGroupId + idJoin + id;279 }280 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//281 function setMinMaxBids() {282 for (var x in keywordData) {283 keywordData[x].MinBid = minBid;284 keywordData[x].MaxBid = maxBid;285 keywordData[x].FirstPageMaxBid = firstPageMaxBid;286 }287 }288 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//289 function setBidChange() {290 for (var x in keywordData) {291 keywordData[x].BidIncrease = keywordData[x].CpcBid * bidIncreaseProportion / 2;292 keywordData[x].BidDecrease = keywordData[x].CpcBid * bidDecreaseProportion / 2;293 }294 }295 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//296 function updateKeywords(idBatch) {297 var keywordIterator = AdWordsApp.keywords()298 .withIds(idBatch.map(function (str) {299 return str.split(idJoin);300 }))301 .get();302 while (keywordIterator.hasNext()) {303 var keyword = keywordIterator.next();304 var uniqueId = keywordUniqueId(keyword);305 var newBid = bidChange(uniqueId);306 if (newBid !== -1) {307 keyword.setMaxCpc(newBid);308 }309 }310 }311 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//312 function resultsString() {313 var results = [];314 for (var uniqueId in keywordData) {315 var resultsRow = [uniqueId, keywordData[uniqueId].ThisHour.Impressions, keywordData[uniqueId].ThisHour.AveragePosition];316 results.push(resultsRow.join(fieldJoin));317 }318 return results.join(lineJoin);319 }320 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//...
newsfeed.js
Source:newsfeed.js
1const Newsfeed = require("../models/newsfeed");2const User = require("../models/user");3const Preference = require("../models/preference");4const Keyword = require("../models/keyword");5const Article = require("../models/article");6const mongoose = require("mongoose");7const Publisher = require("../models/publisher");8const Audio = require("../models/audio");9const Video = require("../models/video");10exports.saveNewsfeedForMobile = async () => {11 try {12 let users = await User.find({}).sort({ _id: -1 });13 /**only fetch for those users14 * 1. paid / trial15 * 2. email verified16 * 3. last login(add field in user and mainatain)17 */18 for (let i = 0; i < users.length - 1; i++) {19 let userId = users[i]._id;20 let preferencePage = 0;21 let preferenceLimit = 4;22 let keywordPage = 0;23 let keywordLimit = 4;24 let articleLimit = 4;25 /**get preference list for loggedin user */26 let preferences = await Preference.aggregate([27 { $match: { user: mongoose.Types.ObjectId(userId) } },28 { $sort: { _id: -1 } },29 { $skip: preferencePage * preferenceLimit },30 { $limit: preferenceLimit },31 {32 $lookup: {33 from: Keyword.collection.name,34 localField: "keyword",35 foreignField: "_id",36 as: "keywordData",37 },38 },39 { $unwind: "$keywordData" },40 {41 $project: {42 // _id: "$keywordData._id",43 count: "$keywordData.count",44 keyword: "$keywordData.keyword",45 },46 },47 ]);48 /**get top counter keyword list */49 let keywords = await Keyword.aggregate([50 { $sort: { count: -1, _id: -1 } },51 { $skip: keywordPage * keywordLimit },52 { $limit: keywordLimit },53 {54 $project: {55 keyword: 1,56 count: 1,57 },58 },59 ]);60 /**get lastPreferenceId */61 let lastPreferenceId;62 if (preferences.length > 0) {63 lastPreferenceId = preferences[preferences.length - 1]._id;64 } else {65 lastPreferenceId = null;66 }67 /**add preferences and keyword array and remove duplicates */68 let finalKeywordList = [...preferences, ...keywords].filter(69 (v, i, a) => a.findIndex((t) => t.keyword === v.keyword) === i70 );71 /**get that array shuffled */72 finalKeywordList = await shuffleArray(finalKeywordList);73 /**get articles with promise */74 let prmForArticle = [];75 let finalKeywordListLen = finalKeywordList.length;76 for (let i = 0; i < finalKeywordListLen; i++) {77 /**article */78 let articlePrm = Article.aggregate([79 {80 $match: {81 $and: [82 { category: new RegExp(finalKeywordList[i].keyword, "i") },83 { $or: [{ device: "both" }, { device: "app" }] },84 ],85 },86 },87 { $sort: { _id: -1 } },88 { $limit: articleLimit },89 {90 $lookup: {91 from: Publisher.collection.name,92 localField: "publisher",93 foreignField: "_id",94 as: "publisherData",95 },96 },97 { $unwind: "$publisherData" },98 {99 $project: {100 _id: 0,101 title: 1,102 description: 1,103 price: 1,104 author: 1,105 cover: 1,106 publisher: "$publisherData",107 website: 1,108 category: 1,109 time: 1,110 date: "$publishingDate",111 id: "$_id",112 lan: 1,113 urlStr: 1,114 public: 1,115 created_at: 1,116 type: "article",117 },118 },119 ]);120 prmForArticle.push(articlePrm);121 }122 /**create final list with lastArticleId after promise resolution with shuffled articles */123 let finalList = [];124 let articlesPromisesResponse = await Promise.all(prmForArticle);125 for (let i = 0; i < finalKeywordListLen; i++) {126 let articles = articlesPromisesResponse[i];127 let allItems = await shuffleArray(articles);128 finalList.push({129 keywordData: finalKeywordList[i],130 data: allItems,131 });132 }133 /**create response object with list, lastPreferenceId and lastKeywordId */134 let data = {135 finalList,136 lastPreferenceId,137 };138 let exist = await Newsfeed.findOne({ user: userId });139 if (exist) {140 await Newsfeed.findOneAndUpdate(141 { user: userId },142 {143 $set: {144 mobileFeed: data,145 updatedAt: new Date(),146 },147 },148 { new: true }149 );150 } else {151 await new Newsfeed({152 user: userId,153 mobileFeed: data,154 }).save();155 }156 }157 } catch (error) {158 console.log(error);159 }160};161exports.saveNewsfeedForWebsite = async () => {162 try {163 let users = await User.find({}).sort({ _id: -1 });164 /**only fetch for those users165 * 1. paid / trial166 * 2. email verified167 * 3. last login(add field in user and mainatain)168 */169 for (let i = 0; i < users.length - 1; i++) {170 let userId = users[i]._id;171 let preferencePage = 0;172 let preferenceLimit = 4;173 let keywordPage = 0;174 let keywordLimit = 4;175 let articleLimit = 3;176 let kwPrm = [];177 /**get preference list for loggedin user */178 let preferencesPrm = Preference.aggregate([179 { $match: { user: mongoose.Types.ObjectId(userId) } },180 { $sort: { _id: -1 } },181 { $skip: preferencePage * preferenceLimit },182 { $limit: preferenceLimit },183 {184 $lookup: {185 from: Keyword.collection.name,186 localField: "keyword",187 foreignField: "_id",188 as: "keywordData",189 },190 },191 { $unwind: "$keywordData" },192 {193 $project: {194 // _id: "$keywordData._id",195 count: "$keywordData.count",196 keyword: "$keywordData.keyword",197 },198 },199 ]);200 kwPrm.push(preferencesPrm);201 /**get top counter keyword list */202 let keywordsPrm = Keyword.aggregate([203 { $sort: { count: -1, _id: -1 } },204 { $skip: keywordPage * keywordLimit },205 { $limit: keywordLimit },206 {207 $project: {208 keyword: 1,209 count: 1,210 },211 },212 ]);213 kwPrm.push(keywordsPrm);214 let resp = await Promise.all(kwPrm);215 let preferences = resp[0];216 let keywords = resp[1];217 /**get lastPreferenceId */218 let lastPreferenceId;219 if (preferences.length > 0) {220 lastPreferenceId = preferences[preferences.length - 1]._id;221 } else {222 lastPreferenceId = null;223 }224 /**add preferences and keyword array and remove duplicates */225 let finalKeywordList = [...preferences, ...keywords].filter(226 (v, i, a) => a.findIndex((t) => t.keyword === v.keyword) === i227 );228 /**get that array shuffled */229 finalKeywordList = await shuffleArray(finalKeywordList);230 /**get articles with promise */231 let prmForArticle = [];232 let prmForAudio = [];233 let prmForVideo = [];234 let finalKeywordListLen = finalKeywordList.length;235 for (let i = 0; i < finalKeywordListLen; i++) {236 //checking if audio and video exist237 let articleCount = Math.round(articleLimit / 3);238 let audioCount = Math.round(articleLimit / 3);239 let videoCount = Math.round(articleLimit / 3);240 let existAudio = await Audio.findOne({241 category: new RegExp(finalKeywordList[i].keyword, "i"),242 });243 if (!existAudio) {244 articleCount = articleCount + 1;245 }246 let existVideo = await Video.findOne({247 category: new RegExp(finalKeywordList[i].keyword, "i"),248 });249 if (!existVideo) {250 articleCount = articleCount + 1;251 }252 /**article */253 let articlePrm = Article.aggregate([254 {255 $match: {256 $and: [257 { category: new RegExp(finalKeywordList[i].keyword, "i") },258 { $or: [{ device: "both" }, { device: "website" }] },259 ],260 },261 },262 { $sort: { _id: -1 } },263 { $limit: articleCount },264 {265 $lookup: {266 from: Publisher.collection.name,267 localField: "publisher",268 foreignField: "_id",269 as: "publisherData",270 },271 },272 { $unwind: "$publisherData" },273 {274 $project: {275 _id: 0,276 title: 1,277 description: 1,278 price: 1,279 author: 1,280 cover: 1,281 publisher: "$publisherData",282 website: 1,283 category: 1,284 time: 1,285 date: "$publishingDate",286 id: "$_id",287 lan: 1,288 urlStr: 1,289 public: 1,290 created_at: 1,291 type: "article",292 },293 },294 ]);295 prmForArticle.push(articlePrm);296 /**audio */297 let audioPrm = Audio.aggregate([298 {299 $match: {300 category: new RegExp(finalKeywordList[i].keyword, "i"),301 },302 },303 { $sort: { _id: -1 } },304 { $limit: audioCount },305 {306 $lookup: {307 from: Publisher.collection.name,308 localField: "publisher",309 foreignField: "_id",310 as: "publisherData",311 },312 },313 { $unwind: "$publisherData" },314 {315 $project: {316 _id: 0,317 title: 1,318 description: 1,319 price: 1,320 thumbnail: 1,321 cover: "$thumbnail",322 audioUrl: 1,323 publisher: "$publisherData",324 category: 1,325 date: "$publishingDate",326 id: "$_id",327 altImage: 1,328 externalLink: 1,329 urlStr: 1,330 public: 1,331 type: "audio",332 },333 },334 ]);335 prmForAudio.push(audioPrm);336 /**video */337 let videoPrm = Video.aggregate([338 {339 $match: {340 category: new RegExp(finalKeywordList[i].keyword, "i"),341 },342 },343 { $sort: { _id: -1 } },344 { $limit: videoCount },345 {346 $lookup: {347 from: Publisher.collection.name,348 localField: "publisher",349 foreignField: "_id",350 as: "publisherData",351 },352 },353 { $unwind: "$publisherData" },354 {355 $project: {356 _id: 0,357 title: 1,358 description: 1,359 price: 1,360 thumbnail: 1,361 cover: "$thumbnail",362 videoUrl: 1,363 publisher: "$publisherData",364 category: 1,365 date: "$publishingDate",366 id: "$_id",367 altImage: 1,368 urlStr: 1,369 externalLink: 1,370 public: 1,371 type: "video",372 },373 },374 ]);375 prmForVideo.push(videoPrm);376 }377 /**create final list with lastArticleId after promise resolution with shuffled articles */378 let finalList = [];379 let articlesPrm = Promise.all(prmForArticle);380 let audioPrm = Promise.all(prmForAudio);381 let videoPrm = Promise.all(prmForVideo);382 let allResp = await Promise.all([articlesPrm, audioPrm, videoPrm]);383 let articlesPromisesResponse = allResp[0];384 let audioPromisesResponse = allResp[1];385 let videoPromisesResponse = allResp[2];386 for (let i = 0; i < finalKeywordListLen; i++) {387 let articles = articlesPromisesResponse[i];388 let audios = audioPromisesResponse[i];389 let videos = videoPromisesResponse[i];390 let allItems = await shuffleArray(391 articles.concat(audios).concat(videos)392 );393 finalList.push({394 keywordData: finalKeywordList[i],395 data: allItems,396 });397 }398 /**create response object with list, lastPreferenceId and lastKeywordId */399 let data = {400 finalList,401 lastPreferenceId,402 };403 let exist = await Newsfeed.findOne({ user: userId });404 if (exist) {405 await Newsfeed.findOneAndUpdate(406 { user: userId },407 {408 $set: {409 websiteFeed: data,410 updatedAt: new Date(),411 },412 },413 { new: true }414 );415 } else {416 await new Newsfeed({417 user: userId,418 websiteFeed: data,419 }).save();420 }421 }422 } catch (error) {423 console.log(error);424 }425};426const shuffleArray = async (array) => {427 let len = array.length;428 for (let i = len - 1; i > 0; i--) {429 const j = Math.floor(Math.random() * i);430 const temp = array[i];431 array[i] = array[j];432 array[j] = temp;433 }434 return array;...
thunderNoteBG.js
Source:thunderNoteBG.js
1// Localization2function getFirefoxMessage (messageName, params) {3 if (params !== undefined) return browser.i18n.getMessage(messageName, params)4 return browser.i18n.getMessage(messageName)5}6const getMsg = getFirefoxMessage7// -------------------------------------------------------------------------------------------------------8function handleAlarms (evt) {9 browser.storage.local.get('feeds').then(function (data) {10 if (data.feeds === undefined) return11 if (data.feeds[evt.name][0] === 'rss') handleRSS(evt.name)12 // TODO: else => handleWebpage13 }, errorHandle)14}15// -------------------------------------------------------------------------------------------------------16function handleRSS (URI) {17 const request = new XMLHttpRequest()18 request.addEventListener('readystatechange', function (evt) {19 if (evt.target.readyState === 4) {20 if (evt.target.status === 200 || evt.target.status === 304) {21 let xml = evt.target.responseXML22 if (xml === null) {23 const xmlParser = new DOMParser()24 xml = xmlParser.parseFromString(evt.target.response, 'text/xml')25 }26 if (processXMLData(xml, URI)) return27 }28 browser.storage.local.get('addon').then(function (data) {29 if (data.addon.notifications === 'enabled') browser.notifications.create(null, { type: 'basic', iconUrl: 'icons/thunderNote.svg', title: getMsg('RSSupdateFailTitle'), message: getMsg('RSSupdateError', URI) })30 })31 }32 })33 request.timeout = 4000034 request.open('GET', URI)35 request.send()36}37// -------------------------------------------------------------------------------------------------------38function processXMLData (xmlDoc, URI) {39 if (xmlDoc === null) {40 browser.storage.local.get('addon').then(function (data) {41 if (data.addon.notifications === 'enabled') browser.notifications.create(null, { type: 'basic', iconUrl: 'icons/thunderNote.svg', title: getMsg('RSSupdateFailTitle'), message: getMsg('RSSupdateError', URI) })42 })43 return false44 }45 const x2js = new X2JS()46 let json47 try {48 json = x2js.xml2json(xmlDoc)49 } catch (error) {50 browser.notifications.create(null, { type: 'basic', iconUrl: 'icons/thunderNote.svg', title: getMsg('RSSupdateFailTitle'), message: getMsg('RSSupdateError', URI) })51 console.warn(getMsg('RSSupdateError', URI))52 console.warn(error)53 return false54 }55 let jsonData56 if (json.channel !== undefined) {57 jsonData = json.channel58 } else if (json.rss !== undefined || json.rss.channel !== undefined) {59 jsonData = json.rss.channel60 }61 if (jsonData.item === undefined) {62 return false63 }64 browser.storage.local.get().then(function (data) {65 if (data.feedData === undefined) data.feedData = {}66 if (data.feedData[URI] === undefined) data.feedData[URI] = {}67 let refreshTime = 068 for (const item of jsonData.item) {69 const link = item.link70 const title = item.title71 const description = item.description72 const time = Date.parse(item.pubDate)73 if (refreshTime === 0 || refreshTime < time) refreshTime = time74 if (data.feedData[URI][link] === undefined) {75 data.feedData[URI][link] = [title, time, description, link, null]76 } else {77 data.feedData[URI][link][0] = title78 data.feedData[URI][link][1] = time79 data.feedData[URI][link][2] = description80 data.feedData[URI][link][3] = link81 data.feedData[URI][link][4] = null82 }83 let mediaMatch = null84 if (item.enclosure !== undefined) {85 if (item.enclosure._url !== undefined) data.feedData[URI][link][4] = item.enclosure._url86 } else if (item.encoded !== undefined) {87 mediaMatch = item.encoded.toString().match(/img.*src=["']((http|https):\/\/.*\.(jpg|jpeg|png|gif|webm|mp4|tiff))/i)88 if (mediaMatch !== null && mediaMatch[1] !== undefined) data.feedData[URI][link][4] = mediaMatch[1]89 }90 }91 if (data.feeds[URI][3] === undefined) {92 data.feeds[URI].push(refreshTime)93 if (data.addon.notifications === 'enabled') browser.notifications.create(null, { type: 'basic', iconUrl: 'icons/thunderNote.svg', title: getMsg('RSSnewTitle'), message: getMsg('RSSnewInformation', URI) })94 } else {95 if (data.feeds[URI][3] !== refreshTime) {96 if (data.addon.notifications === 'enabled') browser.notifications.create(null, { type: 'basic', iconUrl: 'icons/thunderNote.svg', title: getMsg('RSSnewTitle'), message: getMsg('RSSnewInformation', URI) })97 }98 data.feeds[URI][3] = refreshTime99 }100 browser.storage.local.set(data)101 })102 browser.storage.local.get('keywords').then(function (keywordData) {103 if (keywordData === undefined) return true104 if (keywordData.keywords === undefined) return true105 for (const keyword of Object.keys(keywordData.keywords.cnt)) {106 for (const item of jsonData.item) {107 const link = item.link108 const title = item.title109 const description = item.description110 const time = Date.parse(item.pubDate)111 const itemData = [link, title, description]112 let mediaMatch = null113 if (item.encoded !== undefined) {114 itemData.push(item.encoded.toString())115 mediaMatch = item.encoded.toString().match(/img src=["']((http|https):\/\/.*\.(jpg|jpeg|png|gif|webm|mp4|tiff))/i)116 }117 const keyRegEx = new RegExp(keyword, 'gm')118 for (const element of itemData) {119 const matches = element.match(keyRegEx)120 if (matches !== null) {121 if (keywordData.keywords.urls[keyword] === undefined) keywordData.keywords.urls[keyword] = {}122 if (keywordData.keywords.urls[keyword][link] === undefined) {123 if (mediaMatch === null || mediaMatch[1] === undefined) keywordData.keywords.urls[keyword][link] = [title, matches.length, time, description, URI]124 else keywordData.keywords.urls[keyword][link] = [title, matches.length, time, description, URI, mediaMatch[1]]125 } else {126 keywordData.keywords.urls[keyword][link][0] = title127 keywordData.keywords.urls[keyword][link][2] = time128 keywordData.keywords.urls[keyword][link][3] = description129 keywordData.keywords.urls[keyword][link][4] = URI130 if (mediaMatch !== null && mediaMatch[1] !== undefined) keywordData.keywords.urls[keyword][link][5] = mediaMatch[1]131 }132 }133 }134 }135 keywordData.keywords.cnt[keyword] = Object.keys(keywordData.keywords.urls[keyword]).length136 browser.storage.local.set(keywordData)137 }138 }, errorHandle)139 return true140}141// -------------------------------------------------------------------------------------------------------142function addKeyword (keywordData, info) {143 if (keywordData.keywords === undefined) keywordData.keywords = { cnt: {}, urls: {} }144 let keywordText = info.linkText !== undefined ? info.linkText : info.selectionText145 keywordText = keywordText.trim()146 if (keywordText.length === 0) return147 if (keywordData.keywords.cnt[keywordText] !== undefined) return148 keywordData.keywords.cnt[keywordText] = 0149 if (keywordData.keywords.urls === undefined) keywordData.keywords.urls = {}150 browser.storage.local.set(keywordData)151 browser.runtime.sendMessage({ addKeyword: keywordText })152}153// -------------------------------------------------------------------------------------------------------154function errorHandle (error) {155 console.warn('An error occured:')156 console.warn(error)157}158// -------------------------------------------------------------------------------------------------------159browser.alarms.onAlarm.addListener(handleAlarms)160browser.contextMenus.create({ title: getMsg('contextMenuToggleThunderNote'), contexts: ['all'], command: '_execute_sidebar_action' })161browser.contextMenus.create({ title: getMsg('contextMenuAddKeyword'), contexts: ['link', 'selection'], onclick (info) { browser.storage.local.get('keywords').then(function (data) { addKeyword(data, info) }, errorHandle) } })162browser.contextMenus.create({ title: getMsg('contextMenuHighlightOn'), contexts: ['all'], onclick (info) { browser.find.highlightResults() } })163browser.contextMenus.create({ title: getMsg('contextMenuHighlightOff'), contexts: ['all'], onclick (info) { browser.find.removeHighlighting() } })164browser.storage.local.get().then(function (data) {165 browser.alarms.clearAll()166 if (data.feedData === undefined) data.feedData = {}167 if (data.feeds === undefined) return168 for (const url of Object.keys(data.feeds)) {169 if (data.feedData[url] === undefined) data.feedData[url] = {}170 }171 browser.storage.local.set(data)172 if ((data.addon === undefined || data.addon.status === undefined) || data.addon.status === 'enabled') {173 for (const url of Object.keys(data.feeds)) {174 browser.alarms.create(url, { when: Date.now() + 3000, periodInMinutes: data.feeds[url][1] })175 }176 }177}, errorHandle)178// -------------------------------------------------------------------------------------------------------179browser.runtime.onInstalled.addListener(async ({ reason, temporary }) => {180 if (temporary) return181 switch (reason) {182 case 'install':183 browser.tabs.create({ url: browser.runtime.getURL('postInstall.html') })184 break185 case 'update':186 browser.tabs.create({ url: browser.runtime.getURL('postUpdate.html') })187 break188 default:189 break190 }191})192// -------------------------------------------------------------------------------------------------------193browser.browserAction.onClicked.addListener(function () {194 browser.sidebarAction.toggle()...
ReportFilterForm.js
Source:ReportFilterForm.js
1/**2 * Builds a form panel for Report filters3 */4Ext.define('auscope.layer.filterer.forms.ReportFilterForm', {5 extend: 'portal.layer.filterer.BaseFilterForm',67 /**8 * Accepts a config for portal.layer.filterer.BaseFilterForm9 */10 constructor : function(config) {11 //First build our keyword/resource data from our list of CSWRecords12 var cswRecords = config.layer.get('cswRecords');13 var keywordData = {}; //store the counts of keywords keyed by the keyword name14 var resourceData = {}; //sotre the counts of providers keyed by provider names15 for (var i = 0; i < cswRecords.length; i++) {16 //Add keywords17 var keywordArray = cswRecords[i].get('descriptiveKeywords');18 for (var j = 0; j < keywordArray.length; j++) {19 var keyword = keywordArray[j];20 if (keywordData[keyword]) {21 keywordData[keyword]++;22 } else {23 keywordData[keyword] = 1;24 }25 }2627 //Add resource providers28 var resourceProvider = cswRecords[i].get('resourceProvider');29 if (resourceData[resourceProvider]) {30 resourceData[resourceProvider]++;31 } else {32 resourceData[resourceProvider] = 1;33 }34 }3536 //Turn that keyword data into something we can plug into a store37 var keywordList = [];38 for (var keyword in keywordData) {39 var temp={};40 temp.keyword=keyword;41 temp.count=keywordData[keyword];42 keywordList.push(temp);43 }44 var keywordStore = Ext.create('Ext.data.Store', {45 fields : ['keyword', 'count'],46 data : keywordList47 });4849 //Do the same for our resource data50 var providerList = [];51 for (var provider in resourceData) {52 var temp={};53 temp.resourceProvider=provider;54 temp.count=resourceData[provider];55 providerList.push(temp);56 }57 var resourceProviderStore = Ext.create('Ext.data.Store', {58 fields : ['resourceProvider', 'count'],59 data : providerList60 });6162 Ext.apply(config, {63 delayedFormLoading: false,64 border: false,65 autoScroll: true,66 hideMode:'offsets',67 width:'100%',68 buttonAlign:'right',69 labelAlign:'right',70 labelWidth: 70,71 bodyStyle:'padding:5px',72 autoHeight: true,73 items: [{74 xtype:'fieldset',75 title: 'Report Filter Properties',76 autoHeight: true,77 items: [{78 anchor: '100%',79 xtype: 'textfield',80 fieldLabel: '<span data-qtip="Do not use wildcard characters in the search"> Title</span>',81 name: 'title'82 },{83 xtype: 'combo',84 tpl: '<tpl for="."><li style="word-wrap" data-qtip="{keyword} - {count} record(s)" class="x-boundlist-item" role="option" >{keyword}</li></tpl>',85 tplWriteMode: 'set',86 anchor: '100%',87 queryMode: 'local',88 name: 'keyword',89 fieldLabel: '<span data-qtip="Search based on keywords"> Keyword</span>',90 labelAlign: 'left',91 forceSelection: true,92 store: keywordStore,93 triggerAction: 'all',94 typeAhead: true,95 displayField:'keyword',96 valueField:'keyword',97 autoScroll: true98 },{99 xtype: 'combo',100 tpl: '<tpl for="."><li style="word-wrap" data-qtip="{resourceProvider} - {count} record(s)" class="x-boundlist-item" role="option">{resourceProvider}</li></tpl>',101 anchor: '100%',102 queryMode: 'local',103 name: 'resourceProvider',104 fieldLabel: '<span data-qtip="Search based on Provider"> Resource Provider</span>',105 labelAlign: 'left',106 forceSelection: true,107 store: resourceProviderStore,108 triggerAction: 'all',109 typeAhead: true,110 displayField:'resourceProvider',111 valueField:'resourceProvider',112 autoScroll: true113 }]114 }]115 });116117 this.callParent(arguments);118 }
...
agent.update-keyword.service.js
Source:agent.update-keyword.service.js
1import _ from 'lodash';2import {3 MODEL_AGENT,4 MODEL_CATEGORY,5 MODEL_KEYWORD,6 STATUS_OUT_OF_DATE,7 MODEL_ACTION,8 MODEL_AGENT_VERSION9} from '../../../util/constants';10import RedisErrorHandler from '../../errors/redis.error-handler';11module.exports = async function ({ id, keywordId, keywordData, returnModel = false, isVersionCreation = false }) {12 const { globalService, agentService } = await this.server.services();13 try {14 const modelPath = isVersionCreation ? [MODEL_AGENT_VERSION, MODEL_KEYWORD] : [MODEL_AGENT, MODEL_KEYWORD];15 const modelPathIds = [id, keywordId];16 // Load Used Models17 const models = await globalService.getAllModelsInPath({ modelPath, ids: modelPathIds, returnModel: true });18 const AgentModel = models[isVersionCreation ? MODEL_AGENT_VERSION : MODEL_AGENT];19 const KeywordModel = models[MODEL_KEYWORD];20 const changedName = KeywordModel.property('keywordName') !== keywordData.keywordName;21 const oldKeywordName = KeywordModel.property('keywordName')22 await KeywordModel.updateInstance({ data: keywordData });23 // Update Agent and related categories status24 // TODO: Publish Agent update25 AgentModel.property('status', STATUS_OUT_OF_DATE);26 await AgentModel.saveInstance();27 const keywordCategoryIds = await KeywordModel.getAll(MODEL_CATEGORY, MODEL_CATEGORY);28 const KeywordCategoryModels = await globalService.loadAllByIds({29 ids: keywordCategoryIds, //Only load the keywords we are going to use30 model: MODEL_CATEGORY,31 returnModel: true32 });33 const categoryStatusUpdatePromise = KeywordCategoryModels.map(async (CategoryModel) => {34 CategoryModel.property('status', STATUS_OUT_OF_DATE);35 return await CategoryModel.saveInstance();36 });37 await Promise.all(categoryStatusUpdatePromise);38 const agentActionsModels = await globalService.loadAllLinked({ parentModel: AgentModel, model: MODEL_ACTION, returnModel: true });39 const actionsUpdatePromise = agentActionsModels.map(async (ActionModel) => {40 let updated = false;41 ActionModel.property('slots', ActionModel.property('slots').map((actionSlot) => {42 if (actionSlot.keywordId === keywordId) {43 updated = true;44 actionSlot.keyword = keywordData.keywordName ? keywordData.keywordName : KeywordModel.property('keywordName');45 actionSlot.uiColor = keywordData.uiColor ? keywordData.uiColor : KeywordModel.property('uiColor');46 }47 return actionSlot;48 }));49 if (updated) {50 return await ActionModel.saveInstance();51 }52 return null;53 });54 await Promise.all(actionsUpdatePromise);55 if (changedName && !isVersionCreation) {56 var sayings = await agentService.findAllSayings({ id, skip: 0, limit: -1, filter: { keywords: [oldKeywordName] } });57 var sayingsModified = sayings.data.map(58 saying => {59 return {60 ...saying, keywords: saying.keywords.map((keyword) => {61 return {62 ...keyword,63 keyword: keyword.keyword === oldKeywordName ? keywordData.keywordName : keyword.keyword64 }65 })66 }67 })68 await Promise.all(_.map(sayingsModified, async (saying) => {69 const sayingId = saying.id;70 const categoryId = saying.Category[0].id;71 delete saying.id72 delete saying.Category;73 delete saying.Action;74 return await agentService.upsertSayingInCategory({75 id: AgentModel.id,76 sayingId,77 categoryId,78 sayingData: saying,79 isImport: false80 })81 }))82 }83 return returnModel ? KeywordModel : KeywordModel.allProperties();84 }85 catch (error) {86 throw RedisErrorHandler({ error });87 }...
keyword-list.js
Source:keyword-list.js
1import './keyword-list.css';2import { html } from 'lighterhtml';3import { cssPreviewKeyword } from 'lib/util.js';4export { KeywordList, ToggleEnable, ToggleSelectAll, ToggleDisplay };5function KeywordList({6 props: {7 title,8 showEnableKeywordToggle,9 keywordData,10 keywords: allKeywords,11 allEnabled,12 allSelected,13 minimized,14 selectedKeyword,15 descriptions,16 toggleEnableKeyword,17 toggleEnableAll,18 toggleSelectAll,19 toggleDisplayAll,20 copyFromKeywordToKeyword,21 selectKeyword,22 },23}) {24 const keywords = allKeywords.filter(k => keywordData[k].active);25 return html`26 <nav class="keyword-list">27 <div class="keyword-list-header">28 <div29 class="keyword-list-title"30 onclick="${toggleDisplayAll}"31 data-selected="${selectedKeyword.some(k => keywords.includes(k))}"32 >33 ${title}34 </div>35 <div class="keyword-buttons">36 ${allEnabled !== undefined37 ? ToggleEnable({38 enabled: allEnabled,39 toggle: toggleEnableAll,40 })41 : null}42 ${ToggleSelectAll({43 allSelected,44 toggle: toggleSelectAll,45 })}46 ${ToggleDisplay({47 minimized,48 toggle: toggleDisplayAll,49 })}50 </div>51 </div>52 ${!minimized53 ? html`54 <ol class="items" onclick="${selectKeyword}">55 ${keywords.map(56 keyword => html`57 <li data-selected="${selectedKeyword.includes(keyword)}">58 <div59 title="${descriptions[keyword]}"60 class="keyword-preview"61 data-name="${keyword}"62 style="${cssPreviewKeyword(63 keywordData[keyword],64 keywordData.Normal,65 )}"66 >67 ${keyword}68 </div>69 <div class="keyword-enable-status">70 <i71 title="Copy attributes from ${keyword} to selected keywords"72 onclick="${() => copyFromKeywordToKeyword(keyword)}"73 class="fas fa-copy actionable"74 ></i>75 ${showEnableKeywordToggle76 ? ToggleEnable({77 enabled: keywordData[keyword].enabled,78 toggle: () => toggleEnableKeyword(keyword),79 })80 : null}81 </div>82 </li>83 `,84 )}85 </ol>86 `87 : html``}88 </nav>89 `;90}91function ToggleEnable({ enabled, toggle }) {92 return html`93 ${enabled94 ? html`95 <i96 title="Enable language keywords"97 onclick="${toggle}"98 class="fas fa-eye actionable"99 ></i>100 `101 : html`102 <i103 title="Disable language keywords"104 onclick="${toggle}"105 class="fas fa-eye-slash actionable"106 ></i>107 `}108 `;109}110function ToggleSelectAll({ allSelected, toggle }) {111 return html`112 ${allSelected113 ? html`114 <i115 title="Unselect all"116 onclick="${toggle}"117 class="far fa-check-square actionable"118 ></i>119 `120 : html`121 <i122 title="Select all"123 onclick="${toggle}"124 class="far fa-square actionable"125 ></i>126 `}127 `;128}129function ToggleDisplay({ minimized, toggle }) {130 return html`131 ${minimized132 ? html`133 <i134 title="Maximize"135 onclick="${toggle}"136 class="fas fa-window-maximize actionable"137 ></i>138 `139 : html`140 <i141 title="Minimize"142 onclick="${toggle}"143 class="fas fa-window-minimize actionable"144 ></i>145 `}146 `;...
postTemplate.js
Source:postTemplate.js
1import baseHttpProvider from '../base/baseHttpProvider'2import AppConfig from "../../config/app.config.js";3import {4 getNowDate5} from "../../utils/dateUtil.js";6import {7 getCacheOpenId8} from "../../api/localStorage/login.js";9import {10 shiftCacheFormId,11 getCacheFormId12} from "../../api/localStorage/formIds.js";13// è·åWx token14const getAccessToken = () => {15 let appid = AppConfig.appId;16 let secret = AppConfig.aps;17 return baseHttpProvider.GET('https://api.weixin.qq.com/cgi-bin/token', {18 grant_type: "client_credential",19 appid,20 secret21 })22}23const postTemplateMsg = (options) => {24 let openid = getCacheOpenId();25 if (!openid || !options || !options.length == 0) {26 return Promise.reject();27 }28 let baseUrl = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=';29 return getAccessToken().then(resToken => {30 31 if (!resToken.access_token) {32 return Promise.reject();33 }34 let form_id = getCacheFormId() || Date.now();35 36 if (!options.form_id && !form_id) {37 return Promise.reject();38 }39 let url = baseUrl + encodeURIComponent(resToken.access_token);40 let params = {41 "touser": openid, //ç¨æ·çopenid42 "template_id": "eijn5zLrZA7Qu1xWKOqbO8MYrHojeSrLuYPOt-CLtyo", //模æ¿id43 // "page": "",44 "form_id": form_id, //表åid45 "data": _getTemplateData(options.keywordData)46 }47 48 return baseHttpProvider.POST(url, params).then(() => {49 shiftCacheFormId();50 return Promise.resolve();51 });52 })53}54const _getTemplateData = (keywordData, color) => {55 if (!keywordData || keywordData.length == 0) {56 return57 }58 let result = {};59 color = color || "#173177";60 keywordData.forEach((item, index) => {61 let keyName = "keyword" + parseInt(index + 1);62 result[keyName] = {63 "value": item,64 "color": color65 }66 })67 return result;68}69module.exports = {70 getAccessToken,71 postTemplateMsg...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const keywordData = await page._internal_api_keywordData('goto');7 console.log(keywordData);8 await browser.close();9})();10{11 {12 },13 {14 {15 },16 {17 }18 }19 'const { chromium } = require(\'playwright\');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await browser.close();25})();'26}27const { chromium } = require('playwright');28(async () => {29 const browser = await chromium.launch();30 const context = await browser.newContext();31 const page = await context.newPage();
Using AI Code Generation
1const { keywordData } = require('@playwright/test');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click('"Get started"');8 const data = await keywordData(page, 'Get started');9 console.log(data);10 await browser.close();11})();12{13 element: ElementHandle {14 _context: BrowserContext {15 _browser: Browser {16 _timeoutSettings: TimeoutSettings { _defaultTimeout: 30000 },17 },18 _timeoutSettings: TimeoutSettings { _defaultTimeout: 30000 },19 },20 _channel: ElementHandleChannel {21 },22 _page: Page {
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.webkit.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const { keywordData } = page;7 console.log(keywordData);8 await browser.close();9})();10const playwright = require('playwright');11(async () => {12 const browser = await playwright.webkit.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 const { keywordData } = page;16 console.log(keywordData);17 await browser.close();18})();19const playwright = require('playwright');20(async () => {21 const browser = await playwright.webkit.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 const { keywordData } = page;25 console.log(keywordData);26 await browser.close();27})();28const playwright = require('playwright');29(async () => {30 const browser = await playwright.webkit.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 const { keywordData } = page;34 console.log(keywordData);35 await browser.close();36})();37const playwright = require('playwright');38(async () => {39 const browser = await playwright.webkit.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 const { keywordData } = page;43 console.log(keywordData);44 await browser.close();45})();46const playwright = require('playwright');47(async () => {48 const browser = await playwright.webkit.launch();49 const context = await browser.newContext();50 const page = await context.newPage();51 const { keywordData } = page;52 console.log(keywordData);53 await browser.close();54})();55const playwright = require('playwright');56(async () => {57 const browser = await playwright.webkit.launch();
Using AI Code Generation
1const { keywordData } = require('playwright');2const { chromium } = require('playwright-chromium');3const { firefox } = require('playwright-firefox');4const { webkit } = require('playwright-webkit');5(async () => {6 const browser = await chromium.launch();7 const page = await browser.newPage();8 const keywordDataObject = await page.keywordData();9 console.log(keywordDataObject);10 await browser.close();11})();12{13}
Using AI Code Generation
1const { keywordData } = require('playwright');2const { chromium } = require('playwright-chromium');3const { firefox } = require('playwright-firefox');4const { webkit } = require('playwright-webkit');5(async () => {6 const browser = await chromium.launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 console.log(await keywordData(page, 'playwright'));10 await browser.close();11})();12{13 'playwright': {14 }15}16keywordData(page: Page, query: string): Promise<Record<string, KeywordData>>
Using AI Code Generation
1const { keywordData } = require('playwright/internal/protocol/protocol.yml');2console.log(keywordData);3const { keywordData } = require('playwright/internal/protocol/protocol.yml');4console.log(keywordData);5const { keywordData } = require('playwright/internal/protocol/protocol.yml');6console.log(keywordData);7const { keywordData } = require('playwright/internal/protocol/protocol.yml');8console.log(keywordData);9const { keywordData } = require('playwright/internal/protocol/protocol.yml');10console.log(keywordData);11const { keywordData } = require('playwright/internal/protocol/protocol.yml');12console.log(keywordData);13const { keywordData } = require('playwright/internal/protocol/protocol.yml');14console.log(keywordData);15const { keywordData } = require('playwright/internal/protocol/protocol.yml');16console.log(keywordData);17const { keywordData } = require('playwright/internal/protocol/protocol.yml');18console.log(keywordData);19const { keywordData } = require('playwright/internal/protocol/protocol.yml');20console.log(keywordData);21const { keywordData } = require('playwright/internal/protocol/protocol.yml');22console.log(keywordData);23const { keywordData } = require('playwright/internal/protocol/protocol.yml');24console.log(keywordData);25const { keywordData } = require('playwright/internal/protocol/protocol.yml');26console.log(keywordData);27const { keywordData } = require('playwright/internal/protocol/protocol.yml');28console.log(keywordData);29const { keywordData } = require
Using AI Code Generation
1const { keywordData } = require('playwright/lib/internal/keyboardLayouts');2const { keyboardLayouts } = require('playwright/lib/internal/keyboardLayouts');3const { getKeyboardLayout } = require('playwright/lib/internal/keyboardLayouts');4const { setKeyboardLayout } = require('playwright/lib/internal/keyboardLayouts');5const { isModifierKey } = require('playwright/lib/internal/keyboardLayouts');6const { KeyboardImpl } = require('playwright/lib/internal/keyboardLayouts');7const { KeyboardDispatcher } = require('playwright/lib/internal/keyboardLayouts');8const { Keyboard } = require('playwright/lib/internal/keyboardLayouts');9const { KeyboardLayouts } = require('playwright/lib/internal/keyboardLayouts');10const { Keyboard } = require('playwright/lib/internal/keyboard');11const { KeyboardLayouts } = require('playwright/lib/internal/keyboardLayouts');12const { Keyboard } = require('playwright/lib/internal/keyboard');13const { KeyboardLayouts } = require('playwright/lib/internal/keyboardLayouts');14const { Keyboard } = require('playwright/lib/internal/keyboard');15const { KeyboardLayouts } = require('playwright/lib/internal/keyboardLayouts');16const { Keyboard } = require('playwright/lib/internal/keyboard');17const { KeyboardLayouts } = require('playwright/lib/internal/keyboardLayouts');18const { Keyboard } = require('playwright/lib/internal/keyboard');19const { KeyboardLayouts } =
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const text = await page.evaluate(() => {7 return window.playwright.internal.keywordData('button');8 });9 console.log(text);10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 const text = await page.evaluate(() => {18 return window.playwright.internal.keywordData('button');19 });20 console.log(text);21 await browser.close();22})();23const { chromium } = require('playwright');24(async () => {25 const browser = await chromium.launch();26 const context = await browser.newContext();27 const page = await context.newPage();28 const text = await page.evaluate(() => {29 return window.playwright.internal.keywordData('button');30 });31 console.log(text);32 await browser.close();33})();34const { chromium } = require('playwright');35(async () => {36 const browser = await chromium.launch();37 const context = await browser.newContext();38 const page = await context.newPage();39 const text = await page.evaluate(() => {40 return window.playwright.internal.keywordData('button');41 });42 console.log(text);43 await browser.close();44})();45const { chromium } = require('playwright');46(async () => {
Using AI Code Generation
1const { keywordData } = require('@playwright/test');2const data = keywordData('My Keyword');3console.log(data);4const { test } = require('@playwright/test');5test.use({ /* ... */ });6test('My test', async ({ page }) => {7 const data = keywordData('My Keyword');8 console.log(data);9});10const { test } = require('@playwright/test');11test.use({ /* ... */ });12test('My test', async ({ page }) => {13 const data = keywordData('My Keyword', { param1: 'value1', param2: 'value2' });14 console.log(data);15});16const { test } = require('@playwright/test');17test.use({ /* ... */ });18test('My test', async ({ page }) => {19 const data = keywordData('My Keyword', { param1: 'value1', param2: 'value2' });20 console.log(data);21});22const { test } = require('@playwright/test');23test.use({ /* ... */ });24test('My test', async ({ page }) => {25 const data = keywordData('My Keyword', { param1: 'value1', param2: 'value2' });26 console.log(data);27});28const { test } = require('@playwright/test');29test.use({ /* ... */ });30test('My test', async ({ page }) => {31 const data = keywordData('My Keyword', { param1: 'value1', param2: 'value2' });32 console.log(data);33});34const { test } = require('@playwright/test');35test.use({ /* ... */ });36test('My test', async ({ page }) => {
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!