How to use driver.sendSms method in Appium

Best JavaScript code snippet using appium

dispatch.js

Source:dispatch.js Github

copy

Full Screen

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};...

Full Screen

Full Screen

actions-specs.js

Source:actions-specs.js Github

copy

Full Screen

1import chai from 'chai';2import chaiAsPromised from 'chai-as-promised';3import sinon from 'sinon';4import Bootstrap from '../../../lib/bootstrap';5import path from 'path';6import AndroidDriver from '../../../lib/driver';7import * as support from '@appium/support';8import ADB from 'appium-adb';9import jimp from 'jimp';10import helpers from '../../../lib/commands/actions';11import * as teen_process from 'teen_process';12let driver;13let sandbox = sinon.createSandbox();14chai.should();15chai.use(chaiAsPromised);16describe('Actions', function () {17  beforeEach(function () {18    driver = new AndroidDriver();19    driver.adb = new ADB();20    driver.bootstrap = new Bootstrap();21    sandbox.stub(driver.bootstrap, 'sendAction');22  });23  afterEach(function () {24    sandbox.restore();25  });26  describe('keyevent', function () {27    it('shoudle be able to execute keyevent via pressKeyCode', async function () {28      sandbox.stub(driver, 'pressKeyCode');29      await driver.keyevent('66', 'meta');30      driver.pressKeyCode.calledWithExactly('66', 'meta').should.be.true;31    });32    it('should set metastate to null by default', async function () {33      sandbox.stub(driver, 'pressKeyCode');34      await driver.keyevent('66');35      driver.pressKeyCode.calledWithExactly('66', null).should.be.true;36    });37  });38  describe('pressKeyCode', function () {39    it('shoudle be able to press key code', async function () {40      await driver.pressKeyCode('66', 'meta');41      driver.bootstrap.sendAction42        .calledWithExactly('pressKeyCode', {keycode: '66', metastate: 'meta'})43        .should.be.true;44    });45    it('should set metastate to null by default', async function () {46      await driver.pressKeyCode('66');47      driver.bootstrap.sendAction48        .calledWithExactly('pressKeyCode', {keycode: '66', metastate: null})49        .should.be.true;50    });51  });52  describe('longPressKeyCode', function () {53    it('shoudle be able to press key code', async function () {54      await driver.longPressKeyCode('66', 'meta');55      driver.bootstrap.sendAction56        .calledWithExactly('longPressKeyCode', {keycode: '66', metastate: 'meta'})57        .should.be.true;58    });59    it('should set metastate to null by default', async function () {60      await driver.longPressKeyCode('66');61      driver.bootstrap.sendAction62        .calledWithExactly('longPressKeyCode', {keycode: '66', metastate: null})63        .should.be.true;64    });65  });66  describe('getOrientation', function () {67    it('shoudle be able to get orientation', async function () {68      driver.bootstrap.sendAction.withArgs('orientation', {naturalOrientation: false})69        .returns('landscape');70      await driver.getOrientation().should.become('LANDSCAPE');71      driver.bootstrap.sendAction72        .calledWithExactly('orientation', {naturalOrientation: false})73        .should.be.true;74    });75  });76  describe('setOrientation', function () {77    it('shoudle be able to set orientation', async function () {78      let opts = {orientation: 'SOMESCAPE', naturalOrientation: false};79      await driver.setOrientation('somescape');80      driver.bootstrap.sendAction.calledWithExactly('orientation', opts)81        .should.be.true;82    });83  });84  describe('fakeFlick', function () {85    it('shoudle be able to do fake flick', async function () {86      await driver.fakeFlick(12, 34);87      driver.bootstrap.sendAction88        .calledWithExactly('flick', {xSpeed: 12, ySpeed: 34}).should.be.true;89    });90  });91  describe('fakeFlickElement', function () {92    it('shoudle be able to do fake flick on element', async function () {93      await driver.fakeFlickElement(5000, 56, 78, 1.32);94      driver.bootstrap.sendAction95        .calledWithExactly('element:flick',96          {xoffset: 56, yoffset: 78, speed: 1.32, elementId: 5000})97        .should.be.true;98    });99  });100  describe('swipe', function () {101    it('should swipe an element', function () {102      let swipeOpts = {startX: 10, startY: 11, endX: 20, endY: 22,103                       steps: 3, elementId: 'someElementId'};104      driver.swipe(10, 11, 20, 22, 0.1, null, 'someElementId');105      driver.bootstrap.sendAction.calledWithExactly('element:swipe', swipeOpts)106        .should.be.true;107    });108    it('should swipe without an element', function () {109      driver.swipe(0, 0, 1, 1, 0, 1);110      driver.bootstrap.sendAction.calledWith('swipe').should.be.true;111    });112    it('should set start point to (0.5;0.5) if startX and startY are "null"', function () {113      let swipeOpts = {startX: 0.5, startY: 0.5, endX: 0, endY: 0, steps: 0};114      sandbox.stub(driver, 'doSwipe');115      driver.swipe('null', 'null', 0, 0, 0);116      driver.doSwipe.calledWithExactly(swipeOpts).should.be.true;117    });118  });119  describe('pinchClose', function () {120    it('should be able to pinch in element', async function () {121      let pinchOpts = {direction: 'in', elementId: 'el01', percent: 0.5, steps: 5};122      await driver.pinchClose(null, null, null, null, null, 0.5, 5, 'el01');123      driver.bootstrap.sendAction.calledWithExactly('element:pinch', pinchOpts)124        .should.be.true;125    });126  });127  describe('pinchOpen', function () {128    it('should be able to pinch out element', async function () {129      let pinchOpts = {direction: 'out', elementId: 'el01', percent: 0.5, steps: 5};130      await driver.pinchOpen(null, null, null, null, null, 0.5, 5, 'el01');131      driver.bootstrap.sendAction.calledWithExactly('element:pinch', pinchOpts)132        .should.be.true;133    });134  });135  describe('flick', function () {136    it('should call fakeFlickElement if element is passed', async function () {137      sandbox.stub(driver, 'fakeFlickElement');138      await driver.flick('elem', null, null, 1, 2, 3);139      driver.fakeFlickElement.calledWith('elem', 1, 2, 3).should.be.true;140    });141    it('should call fakeFlick if element is not passed', async function () {142      sandbox.stub(driver, 'fakeFlick');143      await driver.flick(null, 1, 2);144      driver.fakeFlick.calledWith(1, 2).should.be.true;145    });146  });147  describe('drag', function () {148    let dragOpts = {149      elementId: 'elem1', destElId: 'elem2',150      startX: 1, startY: 2, endX: 3, endY: 4, steps: 1151    };152    it('should drag an element', function () {153      driver.drag(1, 2, 3, 4, 0.02, null, 'elem1', 'elem2');154      driver.bootstrap.sendAction.calledWithExactly('element:drag', dragOpts)155        .should.be.true;156    });157    it('should drag without an element', function () {158      dragOpts.elementId = null;159      driver.drag(1, 2, 3, 4, 0.02, null, null, 'elem2');160      driver.bootstrap.sendAction.calledWithExactly('drag', dragOpts)161        .should.be.true;162    });163  });164  describe('lock', function () {165    it('should call adb.lock()', async function () {166      sandbox.stub(driver.adb, 'lock');167      await driver.lock();168      driver.adb.lock.calledOnce.should.be.true;169    });170  });171  describe('isLocked', function () {172    it('should call adb.isScreenLocked()', async function () {173      sandbox.stub(driver.adb, 'isScreenLocked').returns('lock_status');174      await driver.isLocked().should.become('lock_status');175      driver.adb.isScreenLocked.calledOnce.should.be.true;176    });177  });178  describe('openNotifications', function () {179    it('should be able to open notifications', async function () {180      await driver.openNotifications();181      driver.bootstrap.sendAction.calledWithExactly('openNotification')182        .should.be.true;183    });184  });185  describe('setLocation', function () {186    it('should be able to set location', async function () {187      sandbox.stub(driver.adb, 'sendTelnetCommand');188      await driver.setLocation('lat', 'long');189      driver.adb.sendTelnetCommand.calledWithExactly('geo fix long lat')190        .should.be.true;191    });192  });193  describe('fingerprint', function () {194    it('should call fingerprint adb command for emulator', async function () {195      sandbox.stub(driver.adb, 'fingerprint');196      sandbox.stub(driver, 'isEmulator').returns(true);197      await driver.fingerprint(1111);198      driver.adb.fingerprint.calledWithExactly(1111).should.be.true;199    });200    it('should throw exception for real device', async function () {201      sandbox.stub(driver.adb, 'fingerprint');202      sandbox.stub(driver, 'isEmulator').returns(false);203      await driver.fingerprint(1111).should.be204        .rejectedWith('fingerprint method is only available for emulators');205      driver.adb.fingerprint.notCalled.should.be.true;206    });207  });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');234      sandbox.stub(driver, 'isEmulator').returns(false);235      await driver.sensorSet({sensorType: 'light', value: 0})236        .should.be.rejectedWith('sensorSet method is only available for emulators');237      driver.adb.sensorSet.notCalled.should.be.true;238    });239  });240  describe('gsmCall', function () {241    it('should call gsmCall adb command for emulator', async function () {242      sandbox.stub(driver.adb, 'gsmCall');243      sandbox.stub(driver, 'isEmulator').returns(true);244      await driver.gsmCall(4509, 'call');245      driver.adb.gsmCall.calledWithExactly(4509, 'call').should.be.true;246    });247    it('should throw exception for real device', async function () {248      sandbox.stub(driver.adb, 'gsmCall');249      sandbox.stub(driver, 'isEmulator').returns(false);250      await driver.gsmCall(4509, 'call')251        .should.be.rejectedWith('gsmCall method is only available for emulators');252      driver.adb.gsmCall.notCalled.should.be.true;253    });254  });255  describe('gsmSignal', function () {256    it('should call gsmSignal adb command for emulator', async function () {257      sandbox.stub(driver.adb, 'gsmSignal');258      sandbox.stub(driver, 'isEmulator').returns(true);259      await driver.gsmSignal(3);260      driver.adb.gsmSignal.calledWithExactly(3)261        .should.be.true;262    });263    it('should throw exception for real device', async function () {264      sandbox.stub(driver.adb, 'gsmSignal');265      sandbox.stub(driver, 'isEmulator').returns(false);266      await driver.gsmSignal(3)267        .should.be.rejectedWith('gsmSignal method is only available for emulators');268      driver.adb.gsmSignal.notCalled.should.be.true;269    });270  });271  describe('gsmVoice', function () {272    it('should call gsmVoice adb command for emulator', async function () {273      sandbox.stub(driver.adb, 'gsmVoice');274      sandbox.stub(driver, 'isEmulator').returns(true);275      await driver.gsmVoice('roaming');276      driver.adb.gsmVoice.calledWithExactly('roaming')277        .should.be.true;278    });279    it('should throw exception for real device', async function () {280      sandbox.stub(driver.adb, 'gsmVoice');281      sandbox.stub(driver, 'isEmulator').returns(false);282      await driver.gsmVoice('roaming')283        .should.be.rejectedWith('gsmVoice method is only available for emulators');284      driver.adb.gsmVoice.notCalled.should.be.true;285    });286  });287  describe('powerAC', function () {288    it('should call powerAC adb command for emulator', async function () {289      sandbox.stub(driver.adb, 'powerAC');290      sandbox.stub(driver, 'isEmulator').returns(true);291      await driver.powerAC('off');292      driver.adb.powerAC.calledWithExactly('off')293        .should.be.true;294    });295    it('should throw exception for real device', async function () {296      sandbox.stub(driver.adb, 'powerAC');297      sandbox.stub(driver, 'isEmulator').returns(false);298      await driver.powerAC('roaming')299        .should.be.rejectedWith('powerAC method is only available for emulators');300      driver.adb.powerAC.notCalled.should.be.true;301    });302  });303  describe('powerCapacity', function () {304    it('should call powerCapacity adb command for emulator', async function () {305      sandbox.stub(driver.adb, 'powerCapacity');306      sandbox.stub(driver, 'isEmulator').returns(true);307      await driver.powerCapacity(5);308      driver.adb.powerCapacity.calledWithExactly(5)309        .should.be.true;310    });311    it('should throw exception for real device', async function () {312      sandbox.stub(driver.adb, 'powerCapacity');313      sandbox.stub(driver, 'isEmulator').returns(false);314      await driver.powerCapacity(5)315        .should.be.rejectedWith('powerCapacity method is only available for emulators');316      driver.adb.powerCapacity.notCalled.should.be.true;317    });318  });319  describe('networkSpeed', function () {320    it('should call networkSpeed adb command for emulator', async function () {321      sandbox.stub(driver.adb, 'networkSpeed');322      sandbox.stub(driver, 'isEmulator').returns(true);323      await driver.networkSpeed('gsm');324      driver.adb.networkSpeed.calledWithExactly('gsm')325        .should.be.true;326    });327    it('should throw exception for real device', async function () {328      sandbox.stub(driver.adb, 'networkSpeed');329      sandbox.stub(driver, 'isEmulator').returns(false);330      await driver.networkSpeed('gsm')331        .should.be.rejectedWith('networkSpeed method is only available for emulators');332      driver.adb.networkSpeed.notCalled.should.be.true;333    });334  });335  describe('getScreenshotDataWithAdbShell', function () {336    const defaultDir = '/data/local/tmp/';337    const png = '/path/sc.png';338    const localFile = 'local_file';339    beforeEach(function () {340      sandbox.stub(support.tempDir, 'path');341      sandbox.stub(support.fs, 'exists');342      sandbox.stub(support.fs, 'unlink');343      sandbox.stub(driver.adb, 'shell');344      sandbox.stub(driver.adb, 'pull');345      sandbox.stub(path.posix, 'resolve');346      sandbox.stub(jimp, 'read');347      sandbox.stub(driver.adb, 'fileSize');348      support.tempDir.path.returns(localFile);349      support.fs.exists.withArgs(localFile).returns(true);350      support.fs.unlink.withArgs(localFile).returns(true);351      path.posix.resolve.withArgs(defaultDir, 'screenshot.png').returns(png);352      driver.adb.fileSize.withArgs(png).returns(1);353      jimp.read.withArgs(localFile).returns('screenshoot_context');354    });355    it('should be able to get screenshot via adb shell', async function () {356      await helpers.getScreenshotDataWithAdbShell(driver.adb, {})357        .should.become('screenshoot_context');358      driver.adb.shell.calledWithExactly(['/system/bin/rm', `${png};`359        , '/system/bin/screencap', '-p', png]).should.be.true;360      driver.adb.pull.calledWithExactly(png, localFile).should.be.true;361      jimp.read.calledWithExactly(localFile).should.be.true;362      support.fs.exists.calledTwice.should.be.true;363      support.fs.unlink.calledTwice.should.be.true;364    });365    it('should be possible to change default png dir', async function () {366      path.posix.resolve.withArgs('/custom/path/tmp/', 'screenshot.png').returns(png);367      await helpers.getScreenshotDataWithAdbShell(driver.adb368        , {androidScreenshotPath: '/custom/path/tmp/'})369        .should.become('screenshoot_context');370    });371    it('should throw error if size of the screenshot is zero', async function () {372      driver.adb.fileSize.withArgs(png).returns(0);373      await helpers.getScreenshotDataWithAdbShell(driver.adb, {})374        .should.be.rejectedWith('equals to zero');375    });376  });377  describe('getScreenshotDataWithAdbExecOut', function () {378    it('should be able to take screenshot via exec-out', async function () {379      sandbox.stub(teen_process, 'exec');380      sandbox.stub(jimp, 'read');381      teen_process.exec.returns({stdout: 'stdout', stderr: ''});382      driver.adb.executable.path = 'path/to/adb';383      await helpers.getScreenshotDataWithAdbExecOut(driver.adb);384      teen_process.exec.calledWithExactly(driver.adb.executable.path,385        driver.adb.executable.defaultArgs386          .concat(['exec-out', '/system/bin/screencap', '-p']),387        {encoding: 'binary', isBuffer: true}).should.be.true;388      jimp.read.calledWithExactly('stdout').should.be.true;389    });390    it('should throw error if size of the screenshot is zero', async function () {391      sandbox.stub(teen_process, 'exec');392      teen_process.exec.returns({stdout: '', stderr: ''});393      await helpers.getScreenshotDataWithAdbExecOut(driver.adb)394        .should.be.rejectedWith('Screenshot returned no data');395    });396    it('should throw error if code is not 0', async function () {397      sandbox.stub(teen_process, 'exec');398      teen_process.exec.returns({code: 1, stdout: '', stderr: ''});399      await helpers.getScreenshotDataWithAdbExecOut(driver.adb)400        .should.be.rejectedWith(`Screenshot returned error, code: '1', stderr: ''`);401    });402    it('should throw error if stderr is not empty', async function () {403      sandbox.stub(teen_process, 'exec');404      teen_process.exec.returns({code: 0, stdout: '', stderr: 'Oops'});405      await helpers.getScreenshotDataWithAdbExecOut(driver.adb)406        .should.be.rejectedWith(`Screenshot returned error, code: '0', stderr: 'Oops'`);407    });408  });409  describe('getScreenshot', function () {410    let image;411    beforeEach(function () {412      image = new jimp(1, 1);413      sandbox.stub(driver.adb, 'getApiLevel');414      sandbox.stub(driver.adb, 'getScreenOrientation');415      sandbox.stub(driver, 'getScreenshotDataWithAdbExecOut');416      sandbox.stub(driver, 'getScreenshotDataWithAdbShell');417      sandbox.stub(image, 'getBuffer').callsFake(function (mime, cb) { // eslint-disable-line promise/prefer-await-to-callbacks418        return cb.call(this, null, Buffer.from('appium'));419      });420      sandbox.stub(image, 'rotate');421      driver.adb.getScreenOrientation.returns(2);422      image.rotate.withArgs(-180).returns(image);423    });424    it('should be able to take screenshot via exec-out (API level > 20)', async function () {425      driver.adb.getApiLevel.returns(24);426      driver.getScreenshotDataWithAdbExecOut.withArgs(driver.adb).returns(image);427      await driver.getScreenshot().should.become('YXBwaXVt');428      driver.getScreenshotDataWithAdbExecOut.calledOnce.should.be.true;429      driver.getScreenshotDataWithAdbShell.notCalled.should.be.true;430      image.getBuffer.calledWith(jimp.MIME_PNG).should.be.true;431    });432    it('should be able to take screenshot via adb shell (API level <= 20)', async function () {433      driver.adb.getApiLevel.returns(20);434      driver.getScreenshotDataWithAdbShell.withArgs(driver.adb, driver.opts).returns(image);435      await driver.getScreenshot().should.become('YXBwaXVt');436      driver.getScreenshotDataWithAdbShell.calledOnce.should.be.true;437      driver.getScreenshotDataWithAdbExecOut.notCalled.should.be.true;438      image.getBuffer.calledWith(jimp.MIME_PNG).should.be.true;439    });440    it('should tries to take screenshot via adb shell if exec-out failed (API level > 20)', async function () {441      driver.adb.getApiLevel.returns(24);442      driver.getScreenshotDataWithAdbExecOut.throws();443      driver.getScreenshotDataWithAdbShell.withArgs(driver.adb, driver.opts).returns(image);444      await driver.getScreenshot().should.become('YXBwaXVt');445      driver.getScreenshotDataWithAdbShell.calledOnce.should.be.true;446      driver.getScreenshotDataWithAdbShell.calledOnce.should.be.true;447    });448    it('should throw error if adb shell failed', async function () {449      driver.adb.getApiLevel.returns(20);450      driver.getScreenshotDataWithAdbShell.throws();451      await driver.getScreenshot().should.be.rejectedWith('Cannot get screenshot');452    });453    it('should rotate image if API level < 23', async function () {454      driver.adb.getApiLevel.returns(22);455      driver.getScreenshotDataWithAdbExecOut.withArgs(driver.adb).returns(image);456      await driver.getScreenshot();457      driver.adb.getScreenOrientation.calledOnce.should.be.true;458      image.rotate.calledOnce.should.be.true;459    });460    it('should not rotate image if API level >= 23', async function () {461      driver.adb.getApiLevel.returns(23);462      driver.getScreenshotDataWithAdbExecOut.withArgs(driver.adb).returns(image);463      await driver.getScreenshot();464      driver.adb.getScreenOrientation.notCalled.should.be.true;465      image.rotate.notCalled.should.be.true;466    });467    it('should not throws error if rotate image failed', async function () {468      image.rotate.resetBehavior();469      image.rotate.throws();470      driver.adb.getApiLevel.returns(22);471      driver.getScreenshotDataWithAdbExecOut.withArgs(driver.adb).returns(image);472      await driver.getScreenshot().should.be.fulfilled;473      image.rotate.threw().should.be.true;474    });475  });...

Full Screen

Full Screen

start-trip.js

Source:start-trip.js Github

copy

Full Screen

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}...

Full Screen

Full Screen

java.js

Source:java.js Github

copy

Full Screen

1import Framework from './framework';2import _ from 'lodash';3class JavaFramework extends Framework {4  get language () {5    return 'java';6  }7  wrapWithBoilerplate (code) {8    let [pkg, cls] = (() => {9      if (this.caps.platformName) {10        switch (this.caps.platformName.toLowerCase()) {11          case 'ios': return ['ios', 'IOSDriver'];12          case 'android': return ['android', 'AndroidDriver'];13          default: return ['unknownPlatform', 'UnknownDriver'];14        }15      } else {16        return ['unknownPlatform', 'UnknownDriver'];17      }18    })();19    let capStr = this.indent(Object.keys(this.caps).map((k) => {20      return `desiredCapabilities.setCapability(${JSON.stringify(k)}, ${JSON.stringify(this.caps[k])});`;21    }).join('\n'), 4);22    return `import io.appium.java_client.MobileElement;23import io.appium.java_client.${pkg}.${cls};24import junit.framework.TestCase;25import org.junit.After;26import org.junit.Before;27import org.junit.Test;28import java.net.MalformedURLException;29import java.net.URL;30import org.openqa.selenium.remote.DesiredCapabilities;31public class SampleTest {32  private ${cls} driver;33  @Before34  public void setUp() throws MalformedURLException {35    DesiredCapabilities desiredCapabilities = new DesiredCapabilities();36${capStr}37    URL remoteUrl = new URL("${this.serverUrl}");38    driver = new ${cls}(remoteUrl, desiredCapabilities);39  }40  @Test41  public void sampleTest() {42${this.indent(code, 4)}43  }44  @After45  public void tearDown() {46    driver.quit();47  }48}49`;50  }51  codeFor_findAndAssign (strategy, locator, localVar, isArray) {52    let suffixMap = {53      xpath: 'XPath',54      'accessibility id': 'AccessibilityId',55      'id': 'Id',56      'class name': 'ClassName',57      'name': 'Name',58      '-android uiautomator': 'AndroidUIAutomator',59      '-android datamatcher': 'AndroidDataMatcher',60      '-android viewtag': 'AndroidViewTag',61      '-ios predicate string': 'IosNsPredicate',62      '-ios class chain': 'IosClassChain',63    };64    if (!suffixMap[strategy]) {65      throw new Error(`Strategy ${strategy} can't be code-gened`);66    }67    if (isArray) {68      return `List<MobileElement> ${localVar} = (MobileElement) driver.findElementsBy${suffixMap[strategy]}(${JSON.stringify(locator)});`;69    } else {70      return `MobileElement ${localVar} = (MobileElement) driver.findElementBy${suffixMap[strategy]}(${JSON.stringify(locator)});`;71    }72  }73  getVarName (varName, varIndex) {74    if (varIndex || varIndex === 0) {75      return `${varName}.get(${varIndex})`;76    }77    return varName;78  }79  codeFor_click (varName, varIndex) {80    return `${this.getVarName(varName, varIndex)}.click();`;81  }82  codeFor_clear (varName, varIndex) {83    return `${this.getVarName(varName, varIndex)}.clear();`;84  }85  codeFor_sendKeys (varName, varIndex, text) {86    return `${this.getVarName(varName, varIndex)}.sendKeys(${JSON.stringify(text)});`;87  }88  codeFor_back () {89    return `driver.navigate().back();`;90  }91  codeFor_tap (varNameIgnore, varIndexIgnore, x, y) {92    return `(new TouchAction(driver)).tap(${x}, ${y}).perform()`;93  }94  codeFor_swipe (varNameIgnore, varIndexIgnore, x1, y1, x2, y2) {95    return `(new TouchAction(driver))96  .press({x: ${x1}, y: ${y1}})97  .moveTo({x: ${x2}: y: ${y2}})98  .release()99  .perform()100  `;101  }102  codeFor_getCurrentActivity () {103    return `String activityName = driver.currentActivity()`;104  }105  codeFor_getCurrentPackage () {106    return `String packageName = driver.currentPackage()`;107  }108  codeFor_startActivity () {109    return `driver.`;110  }111  codeFor_installAppOnDevice (varNameIgnore, varIndexIgnore, app) {112    return `driver.installApp("${app}");`;113  }114  codeFor_isAppInstalledOnDevice (varNameIgnore, varIndexIgnore, app) {115    return `boolean isAppInstalled = driver.isAppInstalled("${app}");`;116  }117  codeFor_launchApp () {118    return `driver.launchApp();`;119  }120  codeFor_backgroundApp (varNameIgnore, varIndexIgnore, timeout) {121    return `driver.runAppInBackground(Duration.ofSeconds(${timeout}));`;122  }123  codeFor_closeApp () {124    return `driver.closeApp();`;125  }126  codeFor_resetApp () {127    return `driver.resetApp();`;128  }129  codeFor_removeAppFromDevice (varNameIgnore, varIndexIgnore, app) {130    return `driver.removeApp("${app}");`;131  }132  codeFor_getAppStrings (varNameIgnore, varIndexIgnore, language, stringFile) {133    return `Map<String, String> appStrings = driver.getAppStringMap(${language ? `${language}, ` : ''}${stringFile ? `"${stringFile}` : ''});`;134  }135  codeFor_getClipboard () {136    return `String clipboardText = driver.getClipboardText();`;137  }138  codeFor_setClipboard (varNameIgnore, varIndexIgnore, clipboardText) {139    return `driver.setClipboardText("${clipboardText}");`;140  }141  codeFor_pressKeycode (varNameIgnore, varIndexIgnore, keyCode, metaState, flags) {142    return `driver.pressKeyCode(${keyCode}, ${metaState}, ${flags});`;143  }144  codeFor_longPressKeycode (varNameIgnore, varIndexIgnore, keyCode, metaState, flags) {145    return `driver.longPressKeyCode(${keyCode}, ${metaState}, ${flags});`;146  }147  codeFor_hideDeviceKeyboard () {148    return `driver.hideKeyboard();`;149  }150  codeFor_isKeyboardShown () {151    return `boolean isKeyboardShown = driver.isKeyboardShown();`;152  }153  codeFor_pushFileToDevice (varNameIgnore, varIndexIgnore, pathToInstallTo, fileContentString) {154    return `driver.pushFile("${pathToInstallTo}", ${fileContentString})`;155  }156  codeFor_pullFile (varNameIgnore, varIndexIgnore, pathToPullFrom) {157    return `byte[] fileBase64 = driver.pullFile("${pathToPullFrom}");`;158  }159  codeFor_pullFolder (varNameIgnore, varIndexIgnore, folderToPullFrom) {160    return `byte[] fileBase64 = driver.pullFolder("${folderToPullFrom}");`;161  }162  codeFor_toggleAirplaneMode () {163    return `driver.toggleAirplaneMode();`;164  }165  codeFor_toggleData () {166    return `driver.toggleData();`;167  }168  codeFor_toggleWiFi () {169    return `driver.toggleWifi();`;170  }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) {190    return `driver.lockDevice(${seconds});`;191  }192  codeFor_unlock () {193    return `driver.unlockDevice()`;194  }195  codeFor_isLocked () {196    return `boolean isLocked = driver.isDeviceLocked();`;197  }198  codeFor_rotateDevice (varNameIgnore, varIndexIgnore, x, y, radius, rotation, touchCount, duration) {199    return `driver.rotate(new DeviceRotation(${x}, ${y}, ${radius}, ${rotation}, ${touchCount}, ${duration}));`;200  }201  codeFor_getPerformanceData (varNameIgnore, varIndexIgnore, packageName, dataType, dataReadTimeout) {202    return `List<List<Object>> performanceData = driver.getPerformanceData("${packageName}", "${dataType}", ${dataReadTimeout});`;203  }204  codeFor_getSupportedPerformanceDataTypes () {205    return `List<String> performanceTypes = driver.getSupportedPerformanceDataTypes();`;206  }207  codeFor_performTouchId (varNameIgnore, varIndexIgnore, match) {208    return `driver.performTouchID(${match});`;209  }210  codeFor_toggleTouchIdEnrollment (varNameIgnore, varIndexIgnore, enroll) {211    return `driver.toggleTouchIDEnrollment(${enroll});`;212  }213  codeFor_openNotifications () {214    return `driver.openNotifications();`;215  }216  codeFor_getDeviceTime () {217    return `String time = driver.getDeviceTime();`;218  }219  codeFor_fingerprint (varNameIgnore, varIndexIgnore, fingerprintId) {220    return `driver.fingerPrint(${fingerprintId});`;221  }222  codeFor_sessionCapabilities () {223    return `Map<String, Object> caps = driver.getSessionDetails();`;224  }225  codeFor_setPageLoadTimeout (varNameIgnore, varIndexIgnore, ms) {226    return `driver.manage().timeouts().pageLoadTimeout(${ms / 1000}, TimeUnit.SECONDS);`;227  }228  codeFor_setAsyncScriptTimeout (varNameIgnore, varIndexIgnore, ms) {229    return `driver.manage().timeouts().setScriptTimeout(${ms / 1000}, TimeUnit.SECONDS);`;230  }231  codeFor_setImplicitWaitTimeout (varNameIgnore, varIndexIgnore, ms) {232    return `driver.manage().timeouts().implicitlyWait(${ms / 1000}, TimeUnit.SECONDS);`;233  }234  codeFor_getOrientation () {235    return `ScreenOrientation orientation = driver.getOrientation();`;236  }237  codeFor_setOrientation (varNameIgnore, varIndexIgnore, orientation) {238    return `driver.rotate("${orientation}");`;239  }240  codeFor_getGeoLocation () {241    return `Location location = driver.location();`;242  }243  codeFor_setGeoLocation (varNameIgnore, varIndexIgnore, latitude, longitude, altitude) {244    return `driver.setLocation(new Location(${latitude}, ${longitude}, ${altitude}));`;245  }246  codeFor_logTypes () {247    return `Set<String> logTypes = driver.manage().logs().getAvailableLogTypes();`;248  }249  codeFor_log (varNameIgnore, varIndexIgnore, logType) {250    return `LogEntries logEntries = driver.manage().logs().get("${logType}");`;251  }252  codeFor_updateSettings (varNameIgnore, varIndexIgnore, settingsJson) {253    try {254      let settings = '';255      for (let [settingName, settingValue] of _.toPairs(JSON.parse(settingsJson))) {256        settings += `driver.setSetting("${settingName}", "${settingValue}");\n`;257      }258      return settings;259    } catch (e) {260      return `// Could not parse: ${settingsJson}`;261    }262  }263  codeFor_settings () {264    return `Map<String, Object> settings = driver.getSettings();`;265  }266  /*267  codeFor_ REPLACE_ME (varNameIgnore, varIndexIgnore) {268    return `REPLACE_ME`;269  }270  */271}272JavaFramework.readableName = 'Java - JUnit';...

Full Screen

Full Screen

ride.model.js

Source:ride.model.js Github

copy

Full Screen

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};...

Full Screen

Full Screen

js-wd.js

Source:js-wd.js Github

copy

Full Screen

...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) {...

Full Screen

Full Screen

SmsDevice.js

Source:SmsDevice.js Github

copy

Full Screen

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}...

Full Screen

Full Screen

sms.js

Source:sms.js Github

copy

Full Screen

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};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.sendSms(phoneNumber, message);2driver.getDeviceTime();3driver.toggleAirplaneMode();4driver.toggleData();5driver.toggleWiFi();6driver.toggleLocationServices();7driver.launchApp();8driver.closeApp();9driver.resetApp();10driver.isAppInstalled("com.example.myapp");11driver.installApp("path/to/my.apk");12driver.removeApp("com.example.myapp");13driver.activateApp("com.example.myapp");14driver.backgroundApp(5);15driver.startActivity("com.example.myapp", ".MainActivity");16driver.currentActivity();17driver.getDeviceStrings();18driver.getDeviceLogs("logcat");19driver.getPerformanceData("com.example.myapp", "memoryinfo", 5);20driver.getPerformanceDataTypes("com.example.myapp");

Full Screen

Using AI Code Generation

copy

Full Screen

1var driver = new AndroidDriver();2driver.sendSms("+123456789", "Hello World!");3var driver = new IOSDriver();4driver.sendSms("+123456789", "Hello World!");5var driver = new WindowsDriver();6driver.sendSms("+123456789", "Hello World!");7var driver = new MacDriver();8driver.sendSms("+123456789", "Hello World!");9var driver = new TizenDriver();10driver.sendSms("+123456789", "Hello World!");11var driver = new FirefoxOSDriver();12driver.sendSms("+123456789", "Hello World!");13var driver = new YouiEngineDriver();14driver.sendSms("+123456789", "Hello World!");15var driver = new EspressoDriver();16driver.sendSms("+123456789", "Hello World!");17var driver = new UiAutomator2Driver();18driver.sendSms("+123456789", "Hello World!");19var driver = new WindowsAppDriver();20driver.sendSms("+123456789", "Hello World!");21var driver = new AndroidUiAutomator2Driver();22driver.sendSms("+123456789", "Hello World!");23var driver = new AndroidEspressoDriver();24driver.sendSms("+123456789", "Hello World

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.sendSms("555-123-4567", "Hello World");2driver.executeScript("mobile:sendSms", {phoneNumber: "555-123-4567", messageText: "Hello World"});3[debug] [MJSONWP] Calling AppiumDriver.execute() with args: ["mobile:sendSms",[{"phoneNumber":"555-123-4567","messageText":"Hello World"}],"9b5f5b5e-3b0f-4a5b-8eaf-1d1f7c0d0e9c"]4[debug] [AndroidBootstrap] Sending command to android: {"cmd":"action","action":"element:setText","params":{"elementId":"23","text":"555-123-4567","replace":false,"unicodeKeyboard":false}}5[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"action","action":"element:setText","params":{"elementId":"23","text":"555-123-4567","replace":false,"unicodeKeyboard":false}}6[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Returning result: {"status":13,"value":"Unknown error"}7[debug] [AndroidBootstrap] Sending command to android: {"cmd":"action","action":"element:setText","params":{"elementId":"24","text":"Hello World","replace":false,"unicodeKeyboard":

Full Screen

Using AI Code Generation

copy

Full Screen

1onPrepare: function (config, capabilities) {2    const wdio = require("webdriverio");3    const { remote } = require("webdriverio");4    const { execSync } = require("child_process");5    const { exec } = require("child_process");6    const { androidConfig, iosConfig } = require("./appiumConfig");7    const driver = remote({8        capabilities: {9        },10    });11    driver.addCommand("sendSms", async function (phoneNumber, message) {12        try {13            await execSync(14                `adb -s emulator-5554 shell am start -a android.intent.action.SENDTO -d sms:${phoneNumber} --es sms_body "${message}" --ez exit_on_sent true`15            );16            await execSync(17            );18            await execSync(19            );20            await execSync(21            );22        } catch (error) {23            console.log(error);24        }25    });26},

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Appium automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful