Best JavaScript code snippet using appium-android-driver
dispatch.js
Source:dispatch.js
1const express = require('express');2const router = express.Router();3const dispatch = require('../modals/dispatch')4var log4js = require('log4js');5const bill = require('../modals/ftbill')6const activity = require('../modals/activity')7const ICDriver = require('../modals/ICdriver')8const accountSid = 'ACca12430647230407d512c639bf87853c';9const authToken = 'ca5991007bbe3a4db5ecbadb0ac35fd5';10const nodemailer = require("nodemailer");11const user = require('../modals/user')12const emp = require('../modals/employee')13const msg = require('../modals/messages')14const email = require('../modals/emails');15const client = require('twilio')(accountSid, authToken);16const moment = require('moment')17var logger = log4js.getLogger(), timestamp = new Date()18router.post('/newdispatch', (req, res) => {19 let newDispatch = new bill({20 customer_id: req.body.custId,21 customer_name: req.body.custName,22 job_id: req.body.jobId,23 job_name: req.body.jobName,24 job_location: req.body.jobLoc,25 job_type: req.body.jobType,26 status: req.body.status,27 notes: req.body.notes,28 date: req.body.DispDate,29 Fright_bill: req.body.Fright_Bill,30 Truck_id: req.body.Truck,31 Driver: req.body.Driver,32 material: req.body.dispMaterial,33 Time: req.body.Time,34 Rate: req.body.Rate,35 Truck_Type: req.body.Truck_Type,36 LocA: req.body.locA,37 LocB: req.body.locB,38 billRate: req.body.billRate,39 updated_by: req.body.updatedBy,40 updated_date: req.body.updatedDate41 });42 newDispatch.save((err, Driver) => {43 if (err) {44 logger.error('dispatch.js Line #31 /newdispatch' + err);45 res.json({ msg: 'fail' });46 } else {47 CreateTagID(req.body.Driver, Driver)48 sendSMS(req)49 var msg = 'Added new dispatch for ' + req.body.custName +50 ' for ' + req.body.DispDate + ' Driver ' + req.body.Driver51 logActivity(req.body.user, req.body.role, timestamp, 'New Dispatch', msg)52 logger.info(' dispatch.js Line #34 /newdispatch' + Driver);53 res.json({ msg: 'success' });54 }55 })56})57router.post('/newCustdispatch', (req, res) => {58 var time = req.body.Time, resp = ''59 for (var i = 0; i < time.length; i++) {60 let newDispatch = new bill({61 customer_id: req.body.custId,62 customer_name: req.body.custName,63 job_id: req.body.jobId,64 job_name: req.body.jobName,65 job_location: req.body.jobLoc,66 job_type: req.body.jobType,67 status: req.body.status,68 notes: req.body.notes,69 date: req.body.DispDate,70 Fright_bill: req.body.Fright_Bill,71 Truck_id: req.body.Truck,72 Driver: req.body.Driver,73 material: req.body.dispMaterial,74 Time: time[i],75 Rate: req.body.Rate,76 Truck_Type: req.body.Truck_Type,77 LocA: req.body.locA,78 LocB: req.body.locB,79 billRate: req.body.billRate,80 updated_by: req.body.updatedBy,81 updated_date: req.body.updatedDate82 });83 newDispatch.save((err) => {84 if (err) {85 logger.error('dispatch.js Line #66 /newCustdispatch' + err);86 resp = 'false'87 } else {88 if (req.body.Driver) {89 sendSMS(req)90 }91 var msg = 'Added new dispatch for ' + req.body.custName +92 ' for ' + req.body.DispDate + ' Driver ' + req.body.Driver93 logActivity(req.body.user, req.body.role, timestamp, 'New Dispatch', msg)94 logger.info(' dispatch.js Line #69 /newCustdispatch');95 resp = 'true'96 }97 })98 }99 if (resp == 'true') {100 logger.info(' dispatch.js Line #75 /newCustdispatch ');101 res.json({ msg: 'success' })102 } else {103 logger.error('dispatch.js Line #78 /newCustdispatch');104 res.json({ msg: 'fail' })105 }106})107//get waiting dispatch info 108router.post('/dispatchW', (req, res) => {109 bill.find({ job_id: req.body.job_id, customer_name: req.body.customer_name, date: req.body.dispDate }, function (err, result) {110 if (err) {111 logger.error('dispatch.js Line #89 /dispatchW' + err);112 res.json(err);113 } else {114 var msg = 'Viewed dispatch for ' + req.body.job_id +115 ' for ' + req.body.dispDate116 logActivity(req.body.user, req.body.role, timestamp, 'View Dispatch', msg)117 logger.info(' dispatch.js Line #92 /dispatchW ' + result);118 res.json(result);119 }120 })121})122//, 123router.post('/UpdateManyDispatch', (req, res) => {124 var dat = req.body, error125 for (var i = 0; i < dat.length; i++) {126 bill.updateOne({ job_id: req.body[i].job_id, DispDate: req.body[i].DispDate, Time: req.body[i].Time }, { $set: { Driver: req.body[i].Driver, Truck_id: req.body[i].Truck_id, status: req.body[i].status, notes: req.body[i].notes } }, function (err, result) {127 if (err) {128 logger.error('dispatch.js Line #103 /UpdateManyDispatch' + err);129 error = true130 } else {131 logger.info(' dispatch.js Line #106 /UpdateManyDispatch ' + result);132 }133 })134 }135 if (error) {136 logger.info(' dispatch.js Line #107 /signup ' + successMesg);137 res.json({ ok: 0 });138 } else {139 logger.error('dispatch.js Line #114 /customers' + result);140 res.json({ ok: 1 });141 }142})143//get waiting dispatch info 144router.get('/CurrDispatchW', (req, res) => {145 bill.find({ status: "wait" }, function (err, result) {146 if (err) {147 logger.error('dispatch.js Line #126 /CurrDispatchW' + err);148 res.json(err);149 } else {150 logger.info(' dispatch.js Line #129 /CurrDispatchW ' + result);151 res.json(result);152 }153 })154})155router.post('/dispid', (req, res) => {156 bill.find({ job_id: req.body.jId }, { '_id': 1, 'job_id': 1 }, function (err, result) {157 if (err) {158 logger.error('dispatch.js Line #138 /dispid' + err);159 res.json(err);160 } else {161 logger.info(' dispatch.js Line #141 /dispid ' + result);162 res.json(result);163 }164 })165})166//add FBill and status update167router.post('/dispUpdate', (req, res) => {168 bill.updateOne({ _id: req.body.id }, { $set: { status: req.body.status, Fright_Bill: req.body.Fbill, notes: req.body.notes, Driver: req.body.driver, Truck_id: req.body.truck_id } }, function (err, result) {169 if (err) {170 logger.error('dispatch.js Line #151 /dispUpdate' + err);171 res.json(err);172 } else {173 sendSMS(req)174 CreateTagID(req.body.driver, req)175 var msg = 'Updated dispatch for ' + req.body.job_id +176 ' for ' + req.body.dispDate + ' for Driver ' + req.body.driver177 logActivity(req.body.user, req.body.role, timestamp, 'Update Dispatch', msg)178 logger.info(' dispatch.js Line #154 /dispUpdate ' + result);179 res.json(result);180 }181 })182})183//add FBill and status update184router.post('/cdispUpdate', (req, res) => {185 bill.updateOne({ _id: req.body.id }, { $set: { status: 'Assigned', Driver: req.body.driver, driver_id: req.body.driver_id } }, function (err, result) {186 if (err) {187 logger.error('dispatch.js Line #164 /cdispUpdate' + err);188 res.json(err);189 } else {190 CreateTagID(req.body.driver, req)191 sendSMS(req)192 var msg = 'Updated dispatch for ' + req.body.id + ' for Driver ' + req.body.driver193 logActivity(req.body.user, req.body.role, timestamp, 'Update Dispatch', msg)194 logger.info(' dispatch.js Line #167 /cdispUpdate ' + result);195 res.json(result);196 }197 })198})199//get waiting dispatch info 200router.post('/getDispatch', async (req, res) => {201 var dateStr = req.body.date + 'T08:00:00.000Z',202 dateStr2 = req.body.date + 'T00:00:00.000Z',203 dateStr3 = req.body.date + 'T07:00:00.000Z'204 //new Date(req.body.date)205 const skip = (req.body.page - 1) * 20206 try {207 const [results, itemCount] = await Promise.all([208 bill.find({ '$or': [{ date: dateStr }, { date: dateStr2 }, { date: dateStr3 }] })209 .limit(20)210 .skip(skip),211 bill.countDocuments({ date: req.body.date })212 ])213 res.json({214 count: itemCount,215 pcount: pageCount,216 result: results217 })218 var msg = 'View dispatch for ' + req.body.date219 logActivity(req.body.user, req.body.role, timestamp, 'View Dispatch', msg)220 logger.info(' dispatch.js Line #180 /getDispatch ' + result);221 const pageCount = Math.ceil(itemCount / 20);222 //res.json(result);223 } catch (err) {224 }225})226router.post('/jobDateDisp', (req, res) => {227 bill.find({ date: req.body.dispDte, job_id: req.body.jobid }, function (err, result) {228 if (err) {229 logger.error('dispatch.js Line #189 /jobDateDisp' + err);230 res.json(err);231 } else {232 var msg = 'View dispatch for ' + req.body.dispDte + ' for Job ' + req.body.jobid233 logActivity(req.body.user, req.body.role, timestamp, 'View Dispatch', msg)234 logger.info(' dispatch.js Line #192 /jobDateDisp ' + result);235 res.json(result);236 }237 })238})239router.post('/updateDispStat', (req, res) => {240 bill.updateOne({ job_id: req.body.jid, job_type: req.body.jtype, Truck_Type: req.body.jtt, Time: req.body.jtime, Driver: req.body.dri, Truck_id: req.body.truId }, { $set: { status: req.body.dstatus, notes: req.body.dnotes } }, function (err, result) {241 if (err) {242 logger.error('dispatch.js Line #201 /updateDispStat' + err);243 res.json(err);244 } else {245 var msg = 'Updated dispatch for ' + req.body.jobid + ' Driver ' + req.body.dri246 logActivity(req.body.user, req.body.role, timestamp, 'Update Dispatch', msg)247 logger.info(' dispatch.js Line #204 /updateDispStat ' + result);248 res.json(result);249 }250 })251})252//delete contact253router.post('/dispDelete', async (req, res) => {254 if (req.body.freight_bill) {255 const [disp, Freight] = await Promise.all([256 dispatch.deleteOne({ _id: req.body.id }),257 bill.deleteOne({ Fright_Bill: req.body.freight_bill })258 ])259 res.json({ dispatch: disp, bill: Freight });260 var msg = 'Deleted dispatch for ' + req.body.id + " and Freight Bill for " + req.body.freight_bill261 logActivity(req.body.user, req.body.role, timestamp, 'Delete Dispatch', msg)262 logger.info(' dispatch.js Line #216 /dispDelete ' + result);263 } else {264 bill.deleteOne({ _id: req.body.id }, function (err, disp) {265 if (err) {266 logger.error('dispatch.js Line #213 /dispDelete' + err);267 res.json(err);268 } else {269 var msg = 'Deleted dispatch for ' + req.body.id270 logActivity(req.body.user, req.body.role, timestamp, 'Delete Dispatch', msg)271 logger.info(' dispatch.js Line #216 /dispDelete ' + disp);272 res.json({ dispatch: disp });273 }274 })275 }276})277function logActivity(user, role, timestamp, a, msg) {278 let log = new activity({279 user: user,280 role: role,281 timestamp: timestamp,282 activity: a,283 msg: msg,284 });285 log.save((err, log) => {286 if (err) {287 logger.error('dispatch.js Line #236 logging Activity' + err);288 }289 else {290 }291 })292}293function sendSMS(req) {294 var Driver = req.body.driver || req.body.Driver295 if (req.body.DispDate == undefined) {296 bill.findOne({ _id: req.body.id }, function (err, bill) {297 req.body = bill298 })299 }300 if (Driver || req.body.DispDate || req.body.jobLoc || req.body.Time || req.body.Truck_Type || req.body.Rate) {301 ICDriver.findOne({ ICdriver_name: Driver }, function (err, Drivers) {302 if (Drivers == null) {303 emp.findOne({ empName: Driver }, function (err, empDrivers) {304 empDriverNotification(empDrivers, req)305 })306 } else {307 DriverNotification(Drivers, req)308 }309 })310 } else {311 }312}313function DriverNotification(Drivers, req) {314 var msgs = '', body = ''315 if (req.body.DispDate == undefined) {316 msgs = 'New Dispatch! you have a dispatch on ' + moment(req.body.date).format('MM/DD/YYYY') + ' '317 + req.body.Time + ' for the job location ' + req.body.job_location318 body = 'Hi ' + req.body.Driver + ',<br><br> New Dispatch! you have a dispatch on <strong> ' + req.body.date + ' '319 + req.body.Time + ' </strong> for the job location <strong>' + req.body.job_location + ' </strong> '320 } else {321 msgs = 'New Dispatch! you have a dispatch on ' + req.body.DispDate + ' '322 + req.body.Time + ' for the job location ' + req.body.jobLoc323 body = 'Hi ' + req.body.Driver + ',<br><br> New Dispatch! you have a dispatch on <strong> ' + req.body.DispDate + ' '324 + req.body.Time + ' </strong> for the job location <strong>' + req.body.jobLoc + ' </strong> '325 }326 if (req.body.locA) {327 body = body + ' from <strong> ' + req.body.locA + ' </strong> '328 msgs = msgs + ' from ' + req.body.locA + ' '329 }330 if (req.body.locB) {331 msgs = msgs + ' to ' + req.body.locB + '. '332 body = body + ' to <strong> ' + req.body.locB + ',</strong> '333 } else {334 msgs = msgs + '. '335 body = body + '<strong>. </strong> '336 }337 if (req.body.notes != undefined) {338 if (req.body.notes.length > 0) {339 msgs = msgs + ' Truck Type : ' + req.body.Truck_Type + ', Rate - $' + req.body.Rate + ', Note: ' + req.body.notes[0].msg340 }341 } else {342 msgs = msgs + ' Truck Type : ' + req.body.Truck_Type + ', Rate - $' + req.body.Rate + ', Note: -'343 }344 body = body + ' Truck Type : <strong> ' + req.body.Truck_Type +345 '.</strong> Rate - <strong>$' + req.body.Rate + '.<br></strong> Note: <strong>' + req.body.notes + '</strong>' +346 '<br><br><br> Best,<br>Sunny Trucking Inc.<br>Ph: (510)715-8262<br> Email: sandeep_mann@live.com' +347 '<br><br><br><br><br><br> This is an autogenerated email by Meega Trucking Software.<br> Please <strong>DO NOT REPLY</strong> and Contact your dispatcher/broker for more information on this dispatch'348 saveMsg(msgs, Drivers, req)349 if (Drivers.phone) {350 client.messages.create({351 body: msgs,352 to: Drivers.phone, // Text this number353 from: '+16692134888' // From a valid Twilio number354 })355 .then((message) => console.log(message.status));356 }357 saveEmail(body, Drivers.email, Drivers.email || '')358 if (Drivers.email) {359 let transporter = nodemailer.createTransport({360 host: 'smtp.mail.us-west-2.awsapps.com',361 port: 465,362 secure: true,363 ssl: true, // upgrade later with STARTTLS364 auth: {365 user: "noreply@meegatrucnz.com",366 pass: "History@12"367 }368 });369 // send mail with defined transport object370 let info = transporter.sendMail({371 from: '"Meega Trucking Software" <noreply@meegatrucnz.com>', // sender address372 cc: '"Meega Trucking "<meegatruckings@gmail.com>', //"Sunny Trucking"<sandeep_mann@live.com>'373 to: Drivers.email, // list of receivers374 subject: 'Dispatch From Sunny Trucking Inc.', // Subject line375 html: body,376 });377 }378}379function empDriverNotification(Drivers, req) {380 var msgs = '', body = ''381 if (req.body.DispDate == undefined) {382 msgs = 'New Dispatch! you have a dispatch on ' + moment(req.body.date).format('MM/DD/YYYY') + ' '383 + req.body.Time + ' for the job location ' + req.body.job_location384 body = 'Hi ' + req.body.Driver + ',<br><br> New Dispatch! you have a dispatch on <strong> ' + req.body.date + ' '385 + req.body.Time + ' </strong> for the job location <strong>' + req.body.job_location + ' </strong> '386 } else {387 msgs = 'New Dispatch! you have a dispatch on ' + req.body.DispDate + ' '388 + req.body.Time + ' for the job location ' + req.body.jobLoc389 body = 'Hi ' + req.body.Driver + ',<br><br> New Dispatch! you have a dispatch on <strong> ' + req.body.DispDate + ' '390 + req.body.Time + ' </strong> for the job location <strong>' + req.body.jobLoc + ' </strong> '391 }392 if (req.body.locA) {393 body = body + ' from <strong> ' + req.body.locA + ' </strong> '394 msgs = msgs + ' from ' + req.body.locA + ' '395 }396 if (req.body.locB) {397 msgs = msgs + ' to ' + req.body.locB + '. '398 body = body + ' to <strong> ' + req.body.locB + ',</strong> '399 } else {400 msgs = msgs + '. '401 body = body + '<strong>. </strong> '402 }403 if (req.body.notes.length > 0) {404 msgs = msgs + ' Truck Type : ' + req.body.Truck_Type + ', Rate - $' + req.body.Rate + ', Note: ' + req.body.notes[0].msg405 } else {406 msgs = msgs + ' Truck Type : ' + req.body.Truck_Type + ', Rate - $' + req.body.Rate + ', Note: -'407 }408 body = body + ' Truck Type : <strong> ' + req.body.Truck_Type +409 '.</strong> Rate - <strong>$' + req.body.Rate + '.<br></strong> Note: <strong>' + req.body.notes + '</strong>' +410 '<br><br><br> Best,<br>Sunny Trucking Inc.<br>Ph: (510)715-8262<br> Email: sandeep_mann@live.com' +411 '<br><br><br><br><br><br> This is an autogenerated email by Meega Trucking Software.<br> Please <strong>DO NOT REPLY</strong> and Contact your dispatcher/broker for more information on this dispatch'412 saveEmpDriverMsg(msgs, Drivers, req)413 if (Drivers.empPhone) {414 /* client.messages.create({415 body: msgs,416 to: Drivers.empPhone, // Text this number417 from: '+16692134888' // From a valid Twilio number418 })419 .then((message) => console.log(message.status)); */420 }421 saveEmail(body, Drivers.empEmail, Drivers.empEmail || '')422 if (Drivers.empEmail) {423 let transporter = nodemailer.createTransport({424 host: 'smtp.mail.us-west-2.awsapps.com',425 port: 465,426 secure: true,427 ssl: true, // upgrade later with STARTTLS428 auth: {429 user: "noreply@meegatrucnz.com",430 pass: "History@12"431 }432 });433 // send mail with defined transport object434 let info = transporter.sendMail({435 from: '"Meega Trucking Software" <noreply@meegatrucnz.com>', // sender address436 cc: '"Meega Trucking "<meegatruckings@gmail.com>', //"Sunny Trucking"<sandeep_mann@live.com>'437 to: Drivers.empEmail, // list of receivers438 subject: 'Dispatch From Sunny Trucking Inc.', // Subject line439 html: body,440 });441 }442}443function saveMsg(msgs, Drivers, req) {444 var stat = 'Delivered'445 if (!Drivers.phone || Drivers.phone == '') {446 stat = 'ND'447 }448 let newMsg = new msg({449 to: Drivers.ICdriver_id,450 from: req.body.user,451 fromRole: req.body.role,452 body: msgs,453 timestamp: new Date(),454 status: stat,455 type: 'Dispatch'456 });457 newMsg.save((err, Driver) => {458 if (err) {459 logger.error('dispatch.js Line #31 /newdispatch' + err);460 } else {461 user.findOne({ drId: Drivers.ICdriver_id }, function (err, user) {462 console.log(user)463 var message = {464 app_id: "2aae6d0a-f0bc-4708-8e6c-6524928f9ef3",465 contents: { "en": msgs },466 include_player_ids: [user.userToken] //["d1398dc3-ac86-47c2-95db-f92c16e41136"] userToken467 };468 console.log(message)469 sendNotification(message);470 })471 }472 })473}474function saveEmpDriverMsg(msgs, Drivers, req) {475 var stat = 'Delivered'476 if (!Drivers.empPhone || Drivers.empPhone == '') {477 stat = 'ND'478 }479 let newMsg = new msg({480 to: Drivers.empId,481 from: req.body.user,482 fromRole: req.body.role,483 body: msgs,484 timestamp: new Date(),485 status: stat,486 type: 'Dispatch'487 });488 newMsg.save((err, Driver) => {489 if (err) {490 logger.error('dispatch.js Line #31 /newdispatch' + err);491 } else {492 user.findOne({ drId: Drivers.empId }, function (err, user) {493 var message = {494 app_id: "2aae6d0a-f0bc-4708-8e6c-6524928f9ef3",495 contents: { "en": msgs },496 include_player_ids: [user.userToken] //["d1398dc3-ac86-47c2-95db-f92c16e41136"] userToken497 };498 sendNotification(message);499 })500 }501 })502}503function saveEmail(body, Driver, mail) {504 var stat = 'Delivered'505 if (!mail || mail == '') {506 stat = 'ND'507 }508 let newEmail = new email({509 to: Driver,510 body: body,511 timestamp: new Date(),512 status: stat,513 type: 'Dispatch'514 });515 newEmail.save((err, Driver) => {516 if (err) {517 logger.error('dispatch.js Line #31 /newdispatch' + err);518 } else {519 }520 })521}522//create Tag for accepted Dispatch523router.post('/creatTagId', async (req, res) => {524 const dispatchId = parseInt(req.body.dispatchId.substr(req.body.dispatchId.length - 3), 16)525 const dispDate = req.body.dispDate.split('/')526 var TagId = dispDate[0] + dispDate[1] + dispatchId527 var oldTagID, stat528 await bill.findOne({ Fright_Bill: TagId }, { '_id': 0, 'Fright_Bill': 1 }, function (err, ftb) {529 if (!err) {530 oldTagID = ftb531 }532 })533 if (oldTagID != null && (oldTagID.Fright_Bill != '' || oldTagID.Fright_Bill != undefined)) {534 TagId = dispDate[0] + dispDate[1] + parseInt(req.body.dispatchId.substr(req.body.dispatchId.length - 5), 16)535 }536 bill.updateOne({ _id: req.body.dispatchId }, { $set: { Fright_Bill: TagId } }, function (err, result) {537 if (!err) {538 res.json({ tagId: TagId });539 }540 })541})542//find if company Driver to create TagId543function CreateTagID(Driver, dispDetials) {544 var dispatchId = dispDetials._id || dispDetials.body.id,545 dispDate = dispDetials.date || dispDetials.body.date || dispDetials.body.dispDate,546 dID = dispatchId.toString()547 dID = parseInt(dID.substr(dID.length - 3), 16)548 var dispDate = moment(dispDate, 'MM/DD/YYYY').format("MM/DD/YYYY").toString()549 dispDate = dispDate.split('/')550 var TagId = dispDate[0] + dispDate[1] + dID551 emp.findOne({ empName: Driver, Role: 'Driver' }, function (err, empDriver) {552 if (!err && empDriver != null) {553 bill.updateOne({ _id: dispatchId }, {554 $set: { Fright_Bill: TagId, status: 'Assigned' }555 }, function (err, res) {556 if (!err) {557 return true558 }559 })560 }561 })562 return false563}564var sendNotification = function (data) {565 var headers = {566 "Content-Type": "application/json; charset=utf-8"567 };568 var options = {569 host: "onesignal.com",570 port: 443,571 path: "/api/v1/notifications",572 method: "POST",573 headers: headers574 };575 var https = require('https');576 var req = https.request(options, function (res) {577 res.on('data', function (data) {578 });579 });580 req.on('error', function (e) {581 });582 req.write(JSON.stringify(data));583 req.end();584};...
actions-specs.js
Source:actions-specs.js
...208 describe('sendSMS', function () {209 it('should call sendSMS adb command for emulator', async function () {210 sandbox.stub(driver.adb, 'sendSMS');211 sandbox.stub(driver, 'isEmulator').returns(true);212 await driver.sendSMS(4509, 'Hello Appium');213 driver.adb.sendSMS.calledWithExactly(4509, 'Hello Appium')214 .should.be.true;215 });216 it('should throw exception for real device', async function () {217 sandbox.stub(driver.adb, 'sendSMS');218 sandbox.stub(driver, 'isEmulator').returns(false);219 await driver.sendSMS(4509, 'Hello Appium')220 .should.be.rejectedWith('sendSMS method is only available for emulators');221 driver.adb.sendSMS.notCalled.should.be.true;222 });223 });224 describe('sensorSet', function () {225 it('should call sensor adb command for emulator', async function () {226 sandbox.stub(driver.adb, 'sensorSet');227 sandbox.stub(driver, 'isEmulator').returns(true);228 await driver.sensorSet({sensorType: 'light', value: 0});229 driver.adb.sensorSet.calledWithExactly('light', 0)230 .should.be.true;231 });232 it('should throw exception for real device', async function () {233 sandbox.stub(driver.adb, 'sensorSet');...
start-trip.js
Source:start-trip.js
1/* eslint-disable */2import moment from "moment";3import "whatwg-fetch";4import gpsDistannce from "gps-distance";5import SocketStore from "../../service/socket-store.js"; //eslint-disable-line6import { fetchReturnObj } from "../../service/transform-response";7import AppConfig from "../../models/appConfig";8import paymentCtrl from "../../controllers/payment"; //eslint-disable-line9import sendEmail from "../../service/emailApi";10import sendNotification from "../../service/pushNotification";11import sendSms from "../../service/smsApi";12import TripRequest from "../../models/trip-request";13import TripSchema from "../../models/trip";14import UserSchema from "../../models/user.js"; //eslint-disable-line15/**16 * Get appConfig17 * @returns {appConfig}18 */19function getConfig() {20 return new Promise((resolve, reject) => {21 AppConfig.findOneAsync({ key: "sendConfig" })22 .then(foundDetails => {23 resolve(foundDetails.value);24 })25 .catch(err => {26 reject(err);27 });28 });29}30/**31 * startTriphandler function create a new trip object which stores the different details related to trip.32 * @param socket object33 * @returns {*}34 */35const startTripHandler = socket => {36 /**37 * startTrip event is emitted by driver when trip get started38 * @param tripRequest object39 * @param callback function40 * @return send tripUpdated event to the rider with all the information related to trip41 */42 socket.on("startTrip", (tripRequestObj, cb) => {43 console.log("start trip called in apiserver------------>");44 const riderID = tripRequestObj.riderId;45 const driverID = tripRequestObj.driverId;46 tripRequestObj.tripRequestStatus = "completed";47 const tripObj = new TripSchema({48 riderId: tripRequestObj.riderId,49 driverId: tripRequestObj.driverId,50 srcLoc: tripRequestObj.srcLoc,51 destLoc: tripRequestObj.destLoc,52 pickUpAddress: tripRequestObj.pickUpAddress,53 destAddress: tripRequestObj.destAddress,54 paymentMode: tripRequestObj.paymentMode55 });56 tripObj57 .saveAsync()58 .then(savedTrip => {59 tripRequestObj.tripId = savedTrip._id;60 TripRequest.findOneAndUpdateAsync(61 { _id: tripRequestObj._id },62 { $set: tripRequestObj }63 ).error(e => {64 SocketStore.emitByUserId(riderID, "socketError", e);65 SocketStore.emitByUserId(driverID, "socketError", e);66 });67 UserSchema.updateAsync(68 { $or: [{ _id: savedTrip.riderId }, { _id: savedTrip.driverId }] },69 { $set: { currTripId: savedTrip._id, currTripState: "trip" } },70 { new: true, multi: true }71 )72 .then(() => {73 fetchReturnObj(savedTrip).then(returnObj => {74 sendNotification(riderID, "Driver has started trip");75 SocketStore.emitByUserId(riderID, "tripUpdated", returnObj);76 cb(returnObj);77 });78 })79 .error(e => {80 SocketStore.emitByUserId(savedTrip.riderId, "socketError", {81 message: "error while updating currTripId of user to start Trip",82 data: e83 });84 SocketStore.emitByUserId(savedTrip.driverId, "socketError", {85 message: "error while updating currTripId of user to start Trip",86 data: e87 });88 });89 })90 .error(e => {91 cb(null);92 console.log("some error occured inside the socket Error");93 SocketStore.emitByUserId(riderID, "socketError", e);94 SocketStore.emitByUserId(driverID, "socketError", e);95 });96 });97 /**98 * tripUpdate emit is fired when rider or driver make any changes to trip Object99 * @param trip object100 * @return send tripUpdated event to the rider and driver with all the information related to trip101 */102 socket.on("tripUpdate", tripObj => {103 const riderID = tripObj.riderId;104 const driverID = tripObj.driverId;105 if (106 tripObj.tripStatus === "endTrip" &&107 tripObj.riderRatingByDriver === 0 &&108 tripObj.driverRatingByRider === 0109 ) {110 const then = moment(tripObj.bookingTime, "YYYY-MM-DD'T'HH:mm:ss:SSSZ");111 const now = moment(new Date());112 tripObj.travelTime = moment.duration(then.diff(now));113 tripObj.tripDist = gpsDistannce(114 tripObj.srcLoc[1],115 tripObj.srcLoc[0],116 tripObj.destLoc[1],117 tripObj.destLoc[0]118 );119 if (tripObj.travelTime < 0) {120 tripObj.travelTime = Math.abs(tripObj.travelTime);121 }122 UserSchema.updateAsync(123 { $or: [{ _id: tripObj.riderId }, { _id: tripObj.driverId }] },124 { $set: { currTripId: null, currTripState: null } },125 { new: true, multi: true }126 )127 .then(() => {128 // updated user records129 getConfig().then(data => {130 if (data.email.onEndTripRider) {131 sendEmail(tripObj.riderId, tripObj, "endTrip");132 }133 if (data.email.onEndTripDriver) {134 sendEmail(tripObj.driverId, tripObj, "endTrip");135 }136 if (data.sms.onEndTripRider) {137 sendSms(tripObj.riderId, "You have reached the Destination");138 }139 if (data.sms.onEndTripDriver) {140 sendSms(tripObj.driverId, "You have drop the Rider ");141 }142 });143 })144 .error(e => {145 SocketStore.emitByUserId(tripObj.riderId, "socketError", {146 message:147 "error while updating currTripId of user to null when Trip ends",148 data: e149 });150 SocketStore.emitByUserId(tripObj.driverId, "socketError", {151 message:152 "error while updating currTripId of user to null Trip ends",153 data: e154 });155 });156 }157 if (158 tripObj.riderRatingByDriver !== 0 ||159 tripObj.driverRatingByRider !== 0160 ) {161 updateUserRating(tripObj);162 } else if (tripObj.paymentMode === "CARD") {163 paymentCtrl.cardPayment(tripObj).then(status => {164 tripObj.paymentStatus = status;165 TripSchema.findOneAndUpdateAsync(166 { _id: tripObj._id },167 { $set: tripObj },168 { new: true }169 )170 .then(updatedTripObject => {171 fetchReturnObj(updatedTripObject).then(updatedTripObj => {172 SocketStore.emitByUserId(riderID, "tripUpdated", updatedTripObj);173 SocketStore.emitByUserId(driverID, "tripUpdated", updatedTripObj);174 });175 })176 .error(e => {177 SocketStore.emitByUserId(riderID, "socketError", e);178 SocketStore.emitByUserId(driverID, "socketError", e);179 });180 });181 } else {182 TripSchema.findOneAndUpdateAsync(183 { _id: tripObj._id },184 { $set: tripObj },185 { new: true }186 )187 .then(updatedTripObject => {188 fetchReturnObj(updatedTripObject).then(updatedTripObj => {189 SocketStore.emitByUserId(riderID, "tripUpdated", updatedTripObj);190 SocketStore.emitByUserId(driverID, "tripUpdated", updatedTripObj);191 });192 })193 .error(e => {194 SocketStore.emitByUserId(riderID, "socketError", e);195 SocketStore.emitByUserId(driverID, "socketError", e);196 });197 }198 });199};200function updateUserRating(tripObj) {201 if (tripObj.riderRatingByDriver !== 0) {202 TripSchema.findOneAndUpdateAsync(203 { _id: tripObj._id },204 { $set: { riderRatingByDriver: tripObj.riderRatingByDriver } },205 { new: true }206 )207 .then(updatedTripObj => {208 TripSchema.aggregateAsync([209 {210 $match: {211 riderId: updatedTripObj.riderId,212 tripStatus: "endTrip",213 riderRatingByDriver: { $gt: 0 }214 }215 },216 {217 $group: {218 _id: "$riderId",219 userRt: { $avg: "$riderRatingByDriver" }220 }221 }222 ])223 .then(res => {224 if (res.length !== 0) {225 UserSchema.findOneAndUpdateAsync(226 { _id: res[0]._id },227 { $set: { userRating: res[0].userRt.toFixed(2) } },228 { new: true }229 ).error(e => {230 SocketStore.emitByUserId(tripObj.riderId, "socketError", e);231 SocketStore.emitByUserId(tripObj.driverId, "socketError", e);232 });233 }234 })235 .error(e => {236 SocketStore.emitByUserId(tripObj.riderId, "socketError", e);237 SocketStore.emitByUserId(tripObj.driverId, "socketError", e);238 });239 })240 .error(e => {241 SocketStore.emitByUserId(tripObj.riderId, "socketError", e);242 SocketStore.emitByUserId(tripObj.driverId, "socketError", e);243 });244 }245 if (tripObj.driverRatingByRider !== 0) {246 TripSchema.findOneAndUpdateAsync(247 { _id: tripObj._id },248 {249 $set: {250 driverRatingByRider: tripObj.driverRatingByRider,251 driverReviewByRider: tripObj.driverReviewByRider252 }253 },254 { new: true }255 )256 .then(updatedTripObj => {257 TripSchema.aggregateAsync([258 {259 $match: {260 driverId: updatedTripObj.driverId,261 tripStatus: "endTrip",262 driverRatingByRider: { $gt: 0 }263 }264 },265 {266 $group: {267 _id: "$driverId",268 userRt: { $avg: "$driverRatingByRider" }269 }270 }271 ])272 .then(res => {273 if (res.length !== 0) {274 UserSchema.findOneAndUpdateAsync(275 { _id: res[0]._id },276 { $set: { userRating: res[0].userRt.toFixed(2) } },277 { new: true }278 ).error(e => {279 SocketStore.emitByUserId(tripObj.riderId, "socketError", e);280 SocketStore.emitByUserId(tripObj.driverId, "socketError", e);281 });282 }283 })284 .error(e => {285 SocketStore.emitByUserId(tripObj.riderId, "socketError", e);286 SocketStore.emitByUserId(tripObj.driverId, "socketError", e);287 });288 })289 .error(e => {290 SocketStore.emitByUserId(tripObj.riderId, "socketError", e);291 SocketStore.emitByUserId(tripObj.driverId, "socketError", e);292 });293 }294}...
java.js
Source:java.js
...171 codeFor_toggleLocationServices () {172 return `driver.toggleLocationServices();`;173 }174 codeFor_sendSMS (varNameIgnore, varIndexIgnore, phoneNumber, text) {175 return `driver.sendSMS("${phoneNumber}", "${text}");`;176 }177 codeFor_gsmCall (varNameIgnore, varIndexIgnore, phoneNumber, action) {178 return `driver.makeGsmCall("${phoneNumber}", "${action}");`;179 }180 codeFor_gsmSignal (varNameIgnore, varIndexIgnore, signalStrength) {181 return `driver.setGsmSignalStrength("${signalStrength}");`;182 }183 codeFor_gsmVoice (varNameIgnore, varIndexIgnore, state) {184 return `driver.setGsmVoice("${state}");`;185 }186 codeFor_shake () {187 return `driver.shake();`;188 }189 codeFor_lock (varNameIgnore, varIndexIgnore, seconds) {...
ride.model.js
Source:ride.model.js
1// Author & Email: sysqua@hotmail.com2// Purpose: Manage the customers model and its functionalities.3// Date: 15 Sep 20204const con = require("../helper/db.js");5const smsConfig = require("../config/sms.config");6var request = require("request");7// constructor8const Ride = function (objRide) {9 this.requested_datetime = objRide.requested_datetime;10 this.customer_id = objRide.customer_id;11 this.pickup_address = objRide.pickup_address;12 this.pickup_gps = objRide.pickup_gps;13 this.drop_address = objRide.drop_address;14 this.drop_gps = objRide.drop_gps;15 this.ride_start_time = objRide.ride_start_time;16 this.ride_end_time = objRide.ride_end_time;17 this.status_id = objRide.status_id;18 this.driver_id = objRide.driver_id;19 this.booking_number = objRide.booking_number;20 this.pickup_lat = objRide.pickup_lat;21 this.pickup_lng = objRide.pickup_lng;22 this.drop_lat = objRide.drop_lat;23 this.drop_lng = objRide.drop_lng;24 // this.confirm_otp = objRide.confirm_otp;25 this.otp = objRide.otp;26 this.tip = objRide.tip;27};28// Create a new request on the db when a users creates.29Ride.create = (newRide, result) => {30 con.query("INSERT INTO tbl_rides SET ?", newRide, (err, res) => {31 if (err) {32 console.log("error: ", err);33 result(err, null);34 return;35 }36 console.log("created new request : ", { id: res.insertId, ...newRide });37 result(null, { id: res.insertId, ...newRide });38 });39};40Ride.pasengerAccept = (req, result) => {41 con.query(42 "UPDATE tbl_rides SET passenger_accept = ?, driver_id =? WHERE ride_id = ?",43 [1, req.body.customer_id, req.body.ride_id],44 (err, res) => {45 if (err) {46 console.log("error: ", err);47 result(null, err);48 return;49 }50 if (res.affectedRows == 0) {51 // not found otp details with the id52 result({ kind: "not_found" }, null);53 return;54 }55 req.body.pasengerAccept = true;56 result(null, { ...req.body });57 }58 );59}60Ride.status_list = result => {61 con.query("SELECT * FROM tbl_status", (err, res) => {62 if (err) {63 console.log("error: ", err);64 result(null, err);65 return;66 }67 console.log("status: ", res);68 result(null, res);69 });70};71// Get all the requested rides with status id = 1 (Requested)72Ride.get_all_requests = result => {73 var sql = `SELECT r.ride_id, r.requested_datetime, r.customer_id, c.first_name, c.last_name, c.gender,c.mobile_number,c.city,r.pickup_address,r.pickup_gps,r.drop_address,r.drop_gps,r.status_id,s.status FROM tbl_rides r JOIN tbl_customers c USING (customer_id) INNER JOIN tbl_status s USING (status_id) where status_id = 1`74 con.query(sql, (err, res) => {75 if (err) {76 console.log("error: ", err);77 result(null, err);78 return;79 }80 console.log("open rides: ", res);81 result(null, res);82 });83};84// incomplete85Ride.get_all_rides = result => {86 var sql = `SELECT r.ride_id, r.requested_datetime, r.customer_id, c.first_name, c.last_name, c.gender,c.mobile_number,c.city,r.pickup_address,r.pickup_gps,r.drop_address,r.drop_gps, r.ride_start_time,r.ride_end_time, r.status_id,s.status, d.first_name ``driver_fname``, d.last_name ``driver_lname``, d.mobile_number ``driver_mobile``, d.gender ``driver_gender`` FROM tbl_rides r JOIN tbl_customers c USING (customer_id) INNER JOIN tbl_drivers d USING(driver_id) INNER JOIN tbl_status s USING (status_id)`87 con.query(sql, (err, res) => {88 if (err) {89 console.log("error: ", err);90 result(null, err);91 return;92 }93 console.log("open rides: ", res);94 result(null, res);95 });96};97Ride.rideById = (ride_id, result) => {98 var sql = `SELECT r.ride_id,r.otp, r.requested_datetime, r.customer_id, c.first_name, c.last_name, c.gender,c.mobile_number,c.city,r.pickup_address,r.pickup_gps,r.drop_address,r.drop_gps, r.ride_start_time,r.ride_end_time, r.status_id,s.status, d.first_name driver_fname, d.last_name driver_lname, d.mobile_number driver_mobile, d.gender driver_gender FROM tbl_rides r JOIN tbl_customers c USING (customer_id) INNER JOIN tbl_drivers d USING(driver_id) INNER JOIN tbl_status s USING (status_id) where r.ride_id = ${ride_id}`99 con.query(sql, (err, res) => {100 if (err) {101 console.log("error: ", err);102 result(err, null);103 return;104 }105 if (res.length) {106 console.log("found the ride: ", res[0]);107 result(null, res[0]);108 return;109 }110 // not found ride with the id111 result({ kind: "not_found" }, null);112 });113};114Ride.rideByGPS = (driver_lat, driver_lng, driver_radius, result) => {115 var sql = `SELECT r.ride_id, r.requested_datetime, r.customer_id, c.first_name, c.last_name, 116 c.gender,c.mobile_number,c.city, r.otp,117 r.pickup_address,r.pickup_gps,r.pickup_lat, r.pickup_lng, 118 r.drop_address,r.drop_gps, r.drop_lat, r.drop_lng,r.status_id,s.status, 119 lat_lng_distance(r.pickup_lat,r.pickup_lng, ${driver_lat}, ${driver_lng}) distance,120 r.driver_accept, r.passenger_accept121 FROM tbl_rides r JOIN tbl_customers c USING (customer_id) INNER JOIN tbl_status s USING (status_id) 122 where status_id = 1 and lat_lng_distance(pickup_lat,pickup_lng,${driver_lat}, ${driver_lng}) < ${driver_radius}/1000;`;123 con.query(sql, (err, res) => {124 if (err) {125 console.log("error: ", err);126 result(null, err);127 return;128 }129 console.log("open rides: ", res);130 result(null, res);131 });132};133Ride.getAll = result => {134 con.query("SELECT * FROM tbl_rides", (err, res) => {135 if (err) {136 console.log("error: ", err);137 result(null, err);138 return;139 }140 console.log("open rides: ", res);141 result(null, res);142 });143};144Ride.driver_accept = (id, objConfirm, result) => {145 con.query(146 "UPDATE tbl_rides SET driver_accept = ?, driver_id =? WHERE ride_id = ?",147 [objConfirm.driver_accept, objConfirm.driver_id, id],148 (err, res) => {149 if (err) {150 console.log("error: ", err);151 result(null, err);152 return;153 }154 if (res.affectedRows == 0) {155 // not found otp details with the id156 result({ kind: "not_found" }, null);157 return;158 }159 objConfirm.driver_accept = true;160 result(null, { id: id, ...objConfirm });161 }162 );163}164Ride.confirm_booking = (id, confirm_otp, objConfirm, result) => {165 var b_number = "BN-" + id;166 objConfirm.confirm_otp = confirm_otp;167 con.query(168 "UPDATE tbl_rides SET status_id = ?, driver_id =?, booking_number = ?, confirm_otp = ? WHERE ride_id = ?",169 [objConfirm.status_id, objConfirm.driver_id, b_number, confirm_otp, id],170 (err, res) => {171 if (err) {172 console.log("error: ", err);173 result(null, err);174 return;175 }176 if (res.affectedRows == 0) {177 // not found otp details with the id178 result({ kind: "not_found" }, null);179 return;180 }181 console.log("Your booking is confirmed: ", { id: id, confirm_otp, ...objConfirm });182 console.log(sendConfirmationSMS(id, confirm_otp));183 result(null, { id: id, confirm_otp, ...objConfirm });184 }185 );186};187sendConfirmationSMS = (ride_id, confirm_otp, result) => {188 var sql = `SELECT r.ride_id, r.booking_number, r.requested_datetime, r.customer_id, c.first_name, c.mobile_number, 189 d.first_name driver_fname, d.mobile_number driver_mobile FROM tbl_rides r 190 JOIN tbl_customers c USING (customer_id) INNER JOIN tbl_drivers d USING(driver_id) 191 INNER JOIN tbl_status s USING (status_id) where ride_id = ${ride_id}`192 con.query(sql, (err, res) => {193 if (err) {194 console.log("error: ", err);195 result(err, null);196 return;197 }198 if (res.length) {199 console.log("found the ride: ", res[0]);200 var booking_number = res[0].booking_number;201 var driver_mobile = res[0].driver_mobile;202 var customer_number = res[0].mobile_number;203 var first_name = '';204 var driver_name = '';205 if (res[0].first_name != '') {206 first_name = res[0].first_name;207 }208 if (res[0].first_name != '') {209 driver_name = res[0].driver_fname;210 }211 var customer_msg = "Dear Customer, " + confirm_otp + " is the PIN for your confirmed ride " + booking_number;212 var driver_msg = "Dear Driver, " + confirm_otp + " is the PIN for your confirmed ride " + booking_number;213 console.log("send otp to driver");214 sendSMS(customer_number, customer_msg);215 //console.log("send otp to customer");216 //sendSMS(driver_mobile,driver_msg);217 //result(null, res[0]);218 return;219 }220 // not found ride with the id221 result({ kind: "not_found" }, null);222 });223};224// Ride.sendSMS = (number, otp, result) => {225// var msg = otp + " is the otp for okChalo reigstration";226// var uri = smsConfig.URL + "uname="+ smsConfig.USERNAME + "&password="+ smsConfig.PASSWORD +"&sender=TRAKID&receiver="+ number + "&route=TA&msgtype=1&sms=" + msg227// console.log(uri);228// request(uri, function(error, response, body) {229// console.log(body);230// });231// };232sendSMS = (number, msg, result) => {233 var uri = smsConfig.URL + "uname=" + smsConfig.USERNAME + "&password=" + smsConfig.PASSWORD + "&sender=TRAKID&receiver=" + number + "&route=TA&msgtype=1&sms=" + msg234 console.log(uri);235 request(uri, function (error, response, body) {236 console.log(body);237 });238};...
js-wd.js
Source:js-wd.js
1import Framework from './framework';2class JsWdFramework extends Framework {3 get language () {4 return 'js';5 }6 wrapWithBoilerplate (code) {7 let caps = JSON.stringify(this.caps);8 return `// Requires the admc/wd client library9// (npm install wd)10// Then paste this into a .js file and run with Node 7.6+11const wd = require('wd');12const driver = wd.promiseChainRemote("${this.serverUrl}");13const caps = ${caps};14async function main () {15 await driver.init(caps);16${this.indent(code, 2)}17 await driver.quit();18}19main().catch(console.log);20`;21 }22 codeFor_findAndAssign (strategy, locator, localVar, isArray) {23 let suffixMap = {24 xpath: 'XPath',25 'accessibility id': 'AccessibilityId',26 'id': 'Id',27 'name': 'Name',28 'class name': 'ClassName',29 '-android uiautomator': 'AndroidUIAutomator',30 '-android datamatcher': 'AndroidDataMatcher',31 '-android viewtag': 'unsupported',32 '-ios predicate string': 'IosUIAutomation',33 '-ios class chain': 'IosClassChain',34 };35 if (!suffixMap[strategy]) {36 throw new Error(`Strategy ${strategy} can't be code-gened`);37 }38 if (isArray) {39 return `let ${localVar} = await driver.elementsBy${suffixMap[strategy]}(${JSON.stringify(locator)});`;40 } else {41 return `let ${localVar} = await driver.elementBy${suffixMap[strategy]}(${JSON.stringify(locator)});`;42 }43 }44 codeFor_click (varName, varIndex) {45 return `await ${this.getVarName(varName, varIndex)}.click();`;46 }47 codeFor_clear (varName, varIndex) {48 return `await ${this.getVarName(varName, varIndex)}.clear();`;49 }50 codeFor_sendKeys (varName, varIndex, text) {51 return `await ${this.getVarName(varName, varIndex)}.sendKeys(${JSON.stringify(text)});`;52 }53 codeFor_back () {54 return `await driver.back();`;55 }56 codeFor_tap (varNameIgnore, varIndexIgnore, x, y) {57 return `await (new wd.TouchAction(driver))58 .tap({x: ${x}, y: ${y}})59 .perform()60 `;61 }62 codeFor_swipe (varNameIgnore, varIndexIgnore, x1, y1, x2, y2) {63 return `await (new wd.TouchAction(driver))64 .press({x: ${x1}, y: ${y1}})65 .moveTo({x: ${x2}, y: ${y2}})66 .release()67 .perform()68 `;69 }70 codeFor_getCurrentActivity () {71 return `let activityName = await driver.getCurrentActivity()`;72 }73 codeFor_getCurrentPackage () {74 return `let packageName = await driver.getCurrentPackage()`;75 }76 codeFor_installAppOnDevice (varNameIgnore, varIndexIgnore, app) {77 return `let isAppInstalled = await driver.installAppOnDevice('${app}');`;78 }79 codeFor_isAppInstalledOnDevice (varNameIgnore, varIndexIgnore, app) {80 return `driver.isAppInstalled("${app}");`;81 }82 codeFor_launchApp () {83 return `await driver.launchApp();`;84 }85 codeFor_backgroundApp (varNameIgnore, varIndexIgnore, timeout) {86 return `await driver.backgroundApp(${timeout});`;87 }88 codeFor_closeApp () {89 return `await driver.closeApp();`;90 }91 codeFor_resetApp () {92 return `await driver.resetApp();`;93 }94 codeFor_removeAppFromDevice (varNameIgnore, varIndexIgnore, app) {95 return `await driver.removeAppFromDevice('${app}');`;96 }97 codeFor_getAppStrings (varNameIgnore, varIndexIgnore, language, stringFile) {98 return `let appStrings = await driver.getAppStrings(${language ? `${language}, ` : ''}${stringFile ? `"${stringFile}` : ''});`;99 }100 codeFor_getClipboard () {101 return `let clipboardText = await driver.getClipboard();`;102 }103 codeFor_setClipboard (varNameIgnore, varIndexIgnore, clipboardText) {104 return `await driver.setClipboard('${clipboardText}')`;105 }106 codeFor_pressKeycode (varNameIgnore, varIndexIgnore, keyCode, metaState, flags) {107 return `await driver.longPressKeyCode(${keyCode}, ${metaState}, ${flags});`;108 }109 codeFor_longPressKeycode (varNameIgnore, varIndexIgnore, keyCode, metaState, flags) {110 return `await driver.longPressKeyCode(${keyCode}, ${metaState}, ${flags});`;111 }112 codeFor_hideDeviceKeyboard () {113 return `await driver.hideDeviceKeyboard();`;114 }115 codeFor_isKeyboardShown () {116 return `await driver.isKeyboardShown();`;117 }118 codeFor_pushFileToDevice (varNameIgnore, varIndexIgnore, pathToInstallTo, fileContentString) {119 return `await driver.pushFileToDevice('${pathToInstallTo}', '${fileContentString}');`;120 }121 codeFor_pullFile (varNameIgnore, varIndexIgnore, pathToPullFrom) {122 return `let fileBase64 = await driver.pullFile('${pathToPullFrom}');`;123 }124 codeFor_pullFolder (varNameIgnore, varIndexIgnore, folderToPullFrom) {125 return `let fileBase64 = await driver.pullFolder('${folderToPullFrom}');`;126 }127 codeFor_toggleAirplaneMode () {128 return `await driver.toggleAirplaneMode();`;129 }130 codeFor_toggleData () {131 return `await driver.toggleData();`;132 }133 codeFor_toggleWiFi () {134 return `await driver.toggleWiFi();`;135 }136 codeFor_toggleLocationServices () {137 return `await driver.toggleLocationServices();`;138 }139 codeFor_sendSMS (varNameIgnore, varIndexIgnore, phoneNumber, text) {140 return `await driver.sendSms('${phoneNumber}', '${text}');`;141 }142 codeFor_gsmCall (varNameIgnore, varIndexIgnore, phoneNumber, action) {143 return `await driver.gsmCall('${phoneNumber}', '${action}');`;144 }145 codeFor_gsmSignal (varNameIgnore, varIndexIgnore, signalStrength) {146 return `await driver.gsmSignal(${signalStrength});`;147 }148 codeFor_gsmVoice (varNameIgnore, varIndexIgnore, state) {149 return `await driver.gsmVoice('${state}');`;150 }151 codeFor_shake () {152 return `await driver.shake();`;153 }154 codeFor_lock (varNameIgnore, varIndexIgnore, seconds) {155 return `await driver.lock(${seconds})`;156 }157 codeFor_unlock () {158 return `await driver.unlock()`;159 }160 codeFor_isLocked () {161 return `let isLocked = await driver.isLocked();`;162 }163 codeFor_rotateDevice (varNameIgnore, varIndexIgnore, x, y, radius, rotation, touchCount, duration) {164 return `driver.rotateDevice({x: ${x}, y: ${y}, duration: ${duration}, radius: ${radius}, rotation: ${rotation}, touchCount: ${touchCount}});`;165 }166 codeFor_getPerformanceData (varNameIgnore, varIndexIgnore, packageName, dataType, dataReadTimeout) {167 return `let performanceData = await driver.getPerformanceData('${packageName}', '${dataType}', ${dataReadTimeout});`;168 }169 codeFor_getSupportedPerformanceDataTypes () {170 return `let supportedPerformanceDataTypes = await driver.getSupportedPerformanceDataTypes();`;171 }172 codeFor_performTouchId (varNameIgnore, varIndexIgnore, match) {173 return `await driver.touchId(${match});`;174 }175 codeFor_toggleTouchIdEnrollment (varNameIgnore, varIndexIgnore, enroll) {176 return `await driver.toggleTouchIdEnrollment(${enroll});`;177 }178 codeFor_openNotifications () {179 return `await driver.openNotifications();`;180 }181 codeFor_getDeviceTime () {182 return `let time = await driver.getDeviceTime();`;183 }184 codeFor_fingerprint (varNameIgnore, varIndexIgnore, fingerprintId) {185 return `await driver.fingerprint(${fingerprintId});`;186 }187 codeFor_sessionCapabilities () {188 return `let caps = await driver.sessionCapabilities();`;189 }190 codeFor_setPageLoadTimeout (varNameIgnore, varIndexIgnore, ms) {191 return `await setPageLoadTimeout(${ms})`;192 }193 codeFor_setAsyncScriptTimeout (varNameIgnore, varIndexIgnore, ms) {194 return `await setAsyncScriptTimeout(${ms})`;195 }196 codeFor_setImplicitWaitTimeout (varNameIgnore, varIndexIgnore, ms) {197 return `await setImplicitWaitTimeout(${ms})`;198 }199 codeFor_getOrientation () {200 return `let orientation = await driver.getOrientation();`;201 }202 codeFor_setOrientation (varNameIgnore, varIndexIgnore, orientation) {203 return `await driver.setOrientation('${orientation}');`;204 }205 codeFor_getGeoLocation () {206 return `let location = await driver.getGeoLocation();`;207 }208 codeFor_setGeoLocation (varNameIgnore, varIndexIgnore, latitude, longitude, altitude) {209 return `await driver.setGeoLocation(${latitude}, ${longitude}, ${altitude});`;210 }211 codeFor_logTypes () {212 return `let logTypes = await driver.logTypes();`;213 }214 codeFor_log (varNameIgnore, varIndexIgnore, logType) {215 return `let logs = await driver.log('${logType}');`;216 }217 codeFor_updateSettings (varNameIgnore, varIndexIgnore, settingsJson) {218 return `await driver.updateSettings(${settingsJson});`;219 }220 codeFor_settings () {221 return `let settings = await driver.settings();`;222 }223}224JsWdFramework.readableName = 'JS - WD (Promise)';...
SmsDevice.js
Source:SmsDevice.js
1"use strict";2const Rx = require('rxjs/Rx');3const WavecomSmsMetadataParser_1 = require('./wavecom/WavecomSmsMetadataParser');4const GammuIdentifyMetadataParser_1 = require('./gammu/GammuIdentifyMetadataParser');5const WavecomModemDriver_1 = require('./wavecom/WavecomModemDriver');6const WavecomUSSDResponseParser_1 = require('./wavecom/WavecomUSSDResponseParser');7/**8 * Provide a default implementation for ISmsDevice9 */10class SmsDevice {11 constructor(fileManager, modemDriver, identifyMetadataParser, smsMetadataParser, ussdResponseParser) {12 this.fileManager = fileManager;13 this.modemDriver = modemDriver;14 this.identifyMetadataParser = identifyMetadataParser;15 this.smsMetadataParser = smsMetadataParser;16 this.ussdResponseParser = ussdResponseParser;17 this._configFilePath = '';18 }19 static create() {20 return new SmsDevice({21 isExists: function (path) {22 return Rx.Observable.create(s => {23 s.next(true);24 s.complete();25 });26 }27 }, new WavecomModemDriver_1.WavecomModemDriver(), new GammuIdentifyMetadataParser_1.GammuIdentifyMetadataParser(), new WavecomSmsMetadataParser_1.WavecomSmsMetadataParser(), new WavecomUSSDResponseParser_1.WavecomUSSDResponseParser());28 }29 setConfigFile(configFilePath) {30 return Rx.Observable.create(s => {31 this.fileManager.isExists(configFilePath).subscribe(r => {32 if (r) {33 this._configFilePath = configFilePath;34 }35 else {36 s.error(new Error('Config file not found: ' + configFilePath));37 }38 s.next(r);39 s.complete();40 }, err => {41 s.error(err);42 });43 });44 }45 getConfigFile() {46 return this._configFilePath;47 }48 identify() {49 return Rx.Observable.create(s => {50 if (this._configFilePath.length <= 0) {51 s.error(new Error('Identify failed. No config file specified.'));52 }53 else {54 this.modemDriver.identify(this._configFilePath)55 .flatMap(identifyMetadata => {56 return this.identifyMetadataParser.parse(identifyMetadata);57 })58 .subscribe(smsDeviceInfo => {59 s.next(smsDeviceInfo);60 }, err => {61 s.error(err);62 }, () => {63 s.complete();64 });65 }66 });67 }68 readAllSms() {69 return Rx.Observable.create(s => {70 if (this._configFilePath.length <= 0) {71 s.error(new Error('readAllSms failed. No config file specified.'));72 }73 else {74 this.modemDriver.readAllSms(this._configFilePath)75 .flatMap(smsMetadata => {76 return this.smsMetadataParser.parse(smsMetadata);77 })78 .subscribe(smsInfos => {79 s.next(smsInfos);80 }, err => {81 s.error(err);82 }, () => {83 s.complete();84 });85 }86 });87 }88 deleteAllSms(startLocation, endLocation) {89 return Rx.Observable.create(s => {90 if (this._configFilePath.length <= 0) {91 s.error(new Error('deleteAllSms failed. No config file specified.'));92 }93 else {94 this.modemDriver.deleteAllSms(this._configFilePath, startLocation, endLocation)95 .subscribe(r => {96 s.next();97 }, err => {98 s.error(err);99 }, () => {100 s.complete();101 });102 }103 });104 }105 sendSms(destinationPhone, message) {106 return Rx.Observable.create(s => {107 if (this._configFilePath.length <= 0) {108 s.error(new Error('sendSms failed. No config file specified.'));109 }110 else {111 this.modemDriver.sendSms(this._configFilePath, destinationPhone, message)112 .subscribe(r => {113 s.next();114 }, err => {115 s.error(err);116 }, () => {117 s.complete();118 });119 }120 });121 }122 getUSSD(ussdCode) {123 return Rx.Observable.create(s => {124 if (this._configFilePath.length <= 0) {125 s.error(new Error('getUSSD failed. No config file specified.'));126 }127 else {128 this.modemDriver.getUSSD(this._configFilePath, ussdCode)129 .flatMap(responseString => {130 return this.ussdResponseParser.parse(responseString);131 })132 .subscribe(r => {133 s.next(r);134 }, err => {135 s.error(err);136 }, () => {137 s.complete();138 });139 }140 });141 }142 getUSSDWithCallback(ussdCode, callback) {143 return Rx.Observable.create(s => {144 if (this._configFilePath.length <= 0) {145 s.error(new Error('getUSSD failed. No config file specified.'));146 }147 else {148 this.modemDriver.getUSSDWithCallback(this._configFilePath, ussdCode, callback)149 .subscribe(r => {150 s.next(r);151 }, err => {152 s.error(err);153 }, () => {154 s.complete();155 });156 }157 });158 }159}...
sms.js
Source:sms.js
1'use strict';2const Base = require('../base.js');3const driver = new Base();4driver.sendSms = function (countryCode, mobileNumber, content, remote, token, callback) {5 return driver.postMethod(6 remote + '/v1/publish/publish_sms',7 token,8 callback,9 {country_code: countryCode, mobile_number: mobileNumber, content: content}10 );11};12/*** Promise ***/13driver.sendSmsAsync = function (countryCode, mobileNumber, content, remote, token) {14 return driver.postMethodAsync(15 remote + '/v1/publish/publish_sms',16 token,17 {18 country_code: countryCode,19 mobile_number: mobileNumber,20 content: content21 }22 );23};...
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3 .forBrowser('chrome')4 .build();5driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');6driver.findElement(webdriver.By.name('btnG')).click();7driver.wait(function() {8 return driver.getTitle().then(function(title) {9 return title === 'webdriver - Google Search';10 });11}, 1000);12driver.quit();13.forBrowser('chrome')14.forBrowser('firefox')
Using AI Code Generation
1driver.sendSMS(phoneNumber, message);2driver.sendSMS(phoneNumber, message);3driver.sendSMS(phoneNumber, message);4driver.sendSMS(phoneNumber, message);5driver.sendSMS(phoneNumber, message);6driver.sendSMS(phoneNumber, message);7driver.sendSMS(phoneNumber, message);8driver.sendSMS(phoneNumber, message);9driver.sendSMS(phoneNumber, message);10driver.sendSMS(phoneNumber, message);11driver.sendSMS(phoneNumber, message);12driver.sendSMS(phoneNumber, message);
Using AI Code Generation
1driver.sendSMS("555-555-5555", "Hello World!");2driver.deleteSMS("555-555-5555");3driver.getClipboard();4driver.setClipboard("Hello World!");5driver.hideKeyboard();6driver.pressKeyCode(3);7driver.longPressKeyCode(3);8driver.isKeyboardShown();9driver.openNotifications();10driver.startActivity("com.example", ".ExampleActivity");11driver.currentActivity();12driver.installApp("path/to/app.apk");13driver.removeApp("com.example");14driver.isAppInstalled("com.example");15driver.launchApp();16driver.closeApp();17driver.resetApp();18driver.backgroundApp(1);19driver.endTestCoverage("intent", "path/to/file");
Using AI Code Generation
1driver.sendSMS(phoneNumber, message)2 .then(function() {3 console.log("SMS sent");4 })5 .catch(function(err) {6 console.log("Error sending SMS");7 });8driver.quit();9org.openqa.selenium.WebDriverException: Method has not yet been implemented (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 1.01 seconds Build info: version: '3.4.0', revision: 'unknown', time: 'unknown' System info: host: 'user-PC', ip: '
Using AI Code Generation
1var driver = new AndroidDriver();2driver.sendSMS("555-123-4567", "Hello World!");3var driver = new iOSDriver();4driver.sendSMS("555-123-4567", "Hello World!");5var driver = new WindowsDriver();6driver.sendSMS("555-123-4567", "Hello World!");7sendSMS(phoneNumber, message)8var driver = new AndroidDriver();9driver.sendSMS("555-123-4567", "Hello World!");10var driver = new iOSDriver();11driver.sendSMS("555-123-4567", "Hello World!");12var driver = new WindowsDriver();13driver.sendSMS("555-123-4567", "Hello World!");14sendSMS(phoneNumber, message)15var driver = new AndroidDriver();16driver.sendSMS("555-123-4567", "Hello World!");17var driver = new iOSDriver();18driver.sendSMS("555-123-4567", "Hello World!");19var driver = new WindowsDriver();20driver.sendSMS("555-123-4567", "Hello World!");21sendSMS(phoneNumber, message)
Using AI Code Generation
1var webdriver = require('webdriverio');2var opts = {3 desiredCapabilities: {4 }5};6 .remote(opts)7 .init()8 .elementByName('Views').click()
Using AI Code Generation
1describe('Appium Android Driver', function() {2 it('should send an SMS', function(done) {3 driver.sendSMS('555-555-5555', 'Hello World!').then(function() {4 done();5 });6 });7});8describe('Appium Android Driver', function() {9 it('should send an SMS', function(done) {10 driver.sendSMS('555-555-5555', 'Hello World!').then(function() {11 done();12 });13 });14});15describe('Appium Android Driver', function() {16 it('should send an SMS', function(done) {17 driver.sendSMS('555-555-5555', 'Hello World!').then(function() {18 done();19 });20 });21});22describe('Appium Android Driver', function() {23 it('should send an SMS', function(done) {24 driver.sendSMS('555-555-5555', 'Hello World!').then(function() {25 done();26 });27 });28});29describe('Appium Android Driver', function() {30 it('should send an SMS', function(done) {31 driver.sendSMS('555-555-5555', 'Hello World!').then(function() {32 done();33 });34 });35});36describe('Appium Android Driver', function() {37 it('should send an SMS', function(done) {38 driver.sendSMS('555-555-5555', 'Hello World!').then(function() {39 done();40 });41 });42});43describe('Appium Android Driver', function() {44 it('should send an SMS', function(done) {45 driver.sendSMS('555-555-5555', 'Hello World!').then(function() {46 done();47 });48 });49});
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!