Best JavaScript code snippet using devicefarmer-stf
api.js
Source:api.js
1/**2* Copyright © 2019 contains code contributed by Orange SA, authors: Denis Barbaron - Licensed under the Apache license 2.03**/4var r = require('rethinkdb')5var util = require('util')6var db = require('./')7var wireutil = require('../wire/util')8var dbapi = Object.create(null)9const uuid = require('uuid')10const apiutil = require('../util/apiutil')11const Promise = require('bluebird')12const _ = require('lodash')13dbapi.DuplicateSecondaryIndexError = function DuplicateSecondaryIndexError() {14 Error.call(this)15 this.name = 'DuplicateSecondaryIndexError'16 Error.captureStackTrace(this, DuplicateSecondaryIndexError)17}18util.inherits(dbapi.DuplicateSecondaryIndexError, Error)19dbapi.close = function(options) {20 return db.close(options)21}22dbapi.unlockBookingObjects = function() {23 return Promise.all([24 db.run(r.table('users').update({groups: {lock: false}}))25 , db.run(r.table('devices').update({group: {lock: false}}))26 , db.run(r.table('groups').update({lock: {admin: false, user: false}}))27 ])28}29dbapi.createBootStrap = function(env) {30 const now = Date.now()31 function updateUsersForMigration(group) {32 return dbapi.getUsers().then(function(users) {33 return Promise.map(users, function(user) {34 return db.run(r.table('users').get(user.email).update({35 privilege: user.email !== group.owner.email ? apiutil.USER : apiutil.ADMIN36 , groups: {37 subscribed: []38 , lock: false39 , quotas: {40 allocated: {41 number: group.envUserGroupsNumber42 , duration: group.envUserGroupsDuration43 }44 , consumed: {45 number: 046 , duration: 047 }48 , defaultGroupsNumber: user.email !== group.owner.email ?49 0 :50 group.envUserGroupsNumber51 , defaultGroupsDuration: user.email !== group.owner.email ?52 0 :53 group.envUserGroupsDuration54 , defaultGroupsRepetitions: user.email !== group.owner.email ?55 0 :56 group.envUserGroupsRepetitions57 , repetitions: group.envUserGroupsRepetitions58 }59 }60 }))61 .then(function(stats) {62 if (stats.replaced) {63 return dbapi.addGroupUser(group.id, user.email)64 }65 return stats66 })67 })68 })69 }70 function getDevices() {71 return db.run(r.table('devices'))72 .then(function(cursor) {73 return cursor.toArray()74 })75 }76 77 function updateDevicesForMigration(group) {78 return getDevices().then(function(devices) {79 return Promise.map(devices, function(device) {80 return db.run(r.table('devices').get(device.serial).update({81 group: {82 id: group.id83 , name: group.name84 , lifeTime: group.dates[0]85 , owner: group.owner86 , origin: group.id87 , class: group.class88 , repetitions: group.repetitions89 , originName: group.name90 , lock: false91 }}92 ))93 .then(function(stats) {94 if (stats.replaced) {95 return dbapi.addOriginGroupDevice(group, device.serial)96 }97 return stats98 })99 })100 })101 }102 return dbapi.createGroup({103 name: env.STF_ROOT_GROUP_NAME104 , owner: {105 email: env.STF_ADMIN_EMAIL106 , name: env.STF_ADMIN_NAME107 }108 , users: [env.STF_ADMIN_EMAIL]109 , privilege: apiutil.ROOT110 , class: apiutil.STANDARD111 , repetitions: 0112 , duration: 0113 , isActive: true114 , state: apiutil.READY115 , dates: [{116 start: new Date(now)117 , stop: new Date(now + apiutil.ONE_YEAR)118 }]119 , envUserGroupsNumber: apiutil.MAX_USER_GROUPS_NUMBER120 , envUserGroupsDuration: apiutil.MAX_USER_GROUPS_DURATION121 , envUserGroupsRepetitions: apiutil.MAX_USER_GROUPS_REPETITIONS122 })123 .then(function(group) {124 return dbapi.saveUserAfterLogin({125 name: group.owner.name126 , email: group.owner.email127 , ip: '127.0.0.1'128 })129 .then(function() {130 return updateUsersForMigration(group)131 })132 .then(function() {133 return updateDevicesForMigration(group)134 })135 .then(function() {136 return dbapi.reserveUserGroupInstance(group.owner.email)137 })138 })139}140dbapi.deleteDevice = function(serial) {141 return db.run(r.table('devices').get(serial).delete())142}143dbapi.deleteUser = function(email) {144 return db.run(r.table('users').get(email).delete())145}146dbapi.getReadyGroupsOrderByIndex = function(index) {147 return db148 .run(r.table('groups')149 .orderBy({index: index})150 .filter(function(group) {151 return group('state').ne(apiutil.PENDING)152 }))153 .then(function(cursor) {154 return cursor.toArray()155 })156}157dbapi.getGroupsByIndex = function(value, index) {158 return db.run(r.table('groups').getAll(value, {index: index}))159 .then(function(cursor) {160 return cursor.toArray()161 })162}163dbapi.getGroupByIndex = function(value, index) {164 return dbapi.getGroupsByIndex(value, index)165 .then(function(array) {166 return array[0]167 })168}169dbapi.getGroupsByUser = function(email) {170 return db171 .run(r.table('groups')172 .filter(function(group) {173 return group('users').contains(email)174 }))175 .then(function(cursor) {176 return cursor.toArray()177 })178}179dbapi.getGroup = function(id) {180 return db.run(r.table('groups').get(id))181}182dbapi.getGroups = function() {183 return db.run(r.table('groups'))184 .then(function(cursor) {185 return cursor.toArray()186 })187}188dbapi.getUsers = function() {189 return db.run(r.table('users'))190 .then(function(cursor) {191 return cursor.toArray()192 })193}194dbapi.getEmails = function() {195 return db.run(r.table('users').filter(function(user) {196 return user('privilege').ne(apiutil.ADMIN)197 })198 .getField('email'))199 .then(function(cursor) {200 return cursor.toArray()201 })202}203dbapi.addGroupUser = function(id, email) {204 return Promise.all([205 db.run(r.table('groups')206 .get(id)207 .update({users: r.row('users').setInsert(email)}))208 , db.run(r.table('users')209 .get(email)210 .update({groups: {subscribed: r.row('groups')('subscribed').setInsert(id)}}))211 ])212 .then(function(statss) {213 return statss[0].unchanged ? 'unchanged' : 'added'214 })215}216dbapi.removeGroupUser = function(id, email) {217 return Promise.all([218 db.run(r.table('groups')219 .get(id)220 .update({users: r.row('users').setDifference([email])}))221 , db.run(r.table('users')222 .get(email)223 .update({groups: {subscribed: r.row('groups')('subscribed').setDifference([id])}}))224 ])225 .then(function() {226 return 'deleted'227 })228}229dbapi.lockBookableDevice = function(groups, serial) {230 function wrappedlockBookableDevice() {231 return db.run(r.table('devices').get(serial).update({group: {lock:232 r.branch(233 r.row('group')('lock')234 .eq(false)235 .and(r.row('group')('class')236 .ne(apiutil.STANDARD))237 .and(r.expr(groups)238 .setIntersection([r.row('group')('origin')])239 .isEmpty()240 .not())241 , true242 , r.row('group')('lock'))243 }}, {returnChanges: true}))244 .then(function(stats) {245 return apiutil.lockDeviceResult(stats, dbapi.loadBookableDevice, groups, serial)246 })247 }248 return apiutil.setIntervalWrapper(249 wrappedlockBookableDevice250 , 10251 , Math.random() * 500 + 50)252}253dbapi.lockDeviceByOrigin = function(groups, serial) {254 function wrappedlockDeviceByOrigin() {255 return db.run(r.table('devices').get(serial).update({group: {lock:256 r.branch(257 r.row('group')('lock')258 .eq(false)259 .and(r.expr(groups)260 .setIntersection([r.row('group')('origin')])261 .isEmpty()262 .not())263 , true264 , r.row('group')('lock'))265 }}, {returnChanges: true}))266 .then(function(stats) {267 return apiutil.lockDeviceResult(stats, dbapi.loadDeviceByOrigin, groups, serial)268 })269 }270 return apiutil.setIntervalWrapper(271 wrappedlockDeviceByOrigin272 , 10273 , Math.random() * 500 + 50)274}275dbapi.addOriginGroupDevice = function(group, serial) {276 return db277 .run(r.table('groups')278 .get(group.id)279 .update({devices: r.row('devices').setInsert(serial)}))280 .then(function() {281 return dbapi.getGroup(group.id)282 })283}284dbapi.removeOriginGroupDevice = function(group, serial) {285 return db286 .run(r.table('groups')287 .get(group.id)288 .update({devices: r.row('devices').setDifference([serial])}))289 .then(function() {290 return dbapi.getGroup(group.id)291 })292}293dbapi.addGroupDevices = function(group, serials) {294 const duration = apiutil.computeDuration(group, serials.length)295 return dbapi.updateUserGroupDuration(group.owner.email, group.duration, duration)296 .then(function(stats) {297 if (stats.replaced) {298 return dbapi.updateGroup(299 group.id300 , {301 duration: duration302 , devices: _.union(group.devices, serials)303 })304 }305 return Promise.reject('quota is reached')306 })307}308dbapi.removeGroupDevices = function(group, serials) {309 const duration = apiutil.computeDuration(group, -serials.length)310 return dbapi.updateUserGroupDuration(group.owner.email, group.duration, duration)311 .then(function() {312 return dbapi.updateGroup(313 group.id314 , {315 duration: duration316 , devices: _.difference(group.devices, serials)317 })318 })319}320function setLockOnDevice(serial, state) {321 return db.run(r.table('devices').get(serial).update({group: {lock:322 r.branch(323 r.row('group')('lock').eq(!state)324 , state325 , r.row('group')('lock'))326 }}))327}328dbapi.lockDevice = function(serial) {329 return setLockOnDevice(serial, true)330}331dbapi.unlockDevice = function(serial) {332 return setLockOnDevice(serial, false)333}334function setLockOnUser(email, state) {335 return db.run(r.table('users').get(email).update({groups: {lock:336 r.branch(337 r.row('groups')('lock').eq(!state)338 , state339 , r.row('groups')('lock'))340 }}, {returnChanges: true}))341}342dbapi.lockUser = function(email) {343 function wrappedlockUser() {344 return setLockOnUser(email, true)345 .then(function(stats) {346 return apiutil.lockResult(stats)347 })348 }349 return apiutil.setIntervalWrapper(350 wrappedlockUser351 , 10352 , Math.random() * 500 + 50)353}354dbapi.unlockUser = function(email) {355 return setLockOnUser(email, false)356}357dbapi.lockGroupByOwner = function(email, id) {358 function wrappedlockGroupByOwner() {359 return dbapi.getRootGroup().then(function(group) {360 return db.run(r.table('groups').get(id).update({lock: {user:361 r.branch(362 r.row('lock')('admin')363 .eq(false)364 .and(r.row('lock')('user').eq(false))365 .and(r.row('owner')('email')366 .eq(email)367 .or(r.expr(email)368 .eq(group.owner.email)))369 , true370 , r.row('lock')('user'))371 }}, {returnChanges: true}))372 })373 .then(function(stats) {374 const result = apiutil.lockResult(stats)375 if (!result.status) {376 return dbapi.getGroupAsOwnerOrAdmin(email, id).then(function(group) {377 if (!group) {378 result.data.locked = false379 result.status = true380 }381 return result382 })383 }384 return result385 })386 }387 return apiutil.setIntervalWrapper(388 wrappedlockGroupByOwner389 , 10390 , Math.random() * 500 + 50)391}392dbapi.lockGroup = function(id) {393 function wrappedlockGroup() {394 return db.run(r.table('groups').get(id).update({lock: {user:395 r.branch(396 r.row('lock')('admin')397 .eq(false)398 .and(r.row('lock')('user')399 .eq(false))400 , true401 , r.row('lock')('user'))402 }}))403 .then(function(stats) {404 return apiutil.lockResult(stats)405 })406 }407 return apiutil.setIntervalWrapper(408 wrappedlockGroup409 , 10410 , Math.random() * 500 + 50)411}412dbapi.unlockGroup = function(id) {413 return db.run(r.table('groups').get(id).update({lock: {user: false}}))414}415dbapi.adminLockGroup = function(id, lock) {416 function wrappedAdminLockGroup() {417 return db418 .run(r.table('groups')419 .get(id)420 .update({lock: {user: true, admin: true}}, {returnChanges: true}))421 .then(function(stats) {422 const result = {}423 if (stats.replaced) {424 result.status =425 stats.changes[0].new_val.lock.admin && !stats.changes[0].old_val.lock.user426 if (result.status) {427 result.data = true428 lock.group = stats.changes[0].new_val429 }430 }431 else if (stats.skipped) {432 result.status = true433 }434 return result435 })436 }437 return apiutil.setIntervalWrapper(438 wrappedAdminLockGroup439 , 10440 , Math.random() * 500 + 50)441}442dbapi.adminUnlockGroup = function(lock) {443 if (lock.group) {444 return db445 .run(r.table('groups')446 .get(lock.group.id)447 .update({lock: {user: false, admin: false}}))448 }449 return true450}451dbapi.getRootGroup = function() {452 return dbapi.getGroupByIndex(apiutil.ROOT, 'privilege').then(function(group) {453 if (!group) {454 throw new Error('Root group not found')455 }456 return group457 })458}459dbapi.getUserGroup = function(email, id) {460 return db.run(r.table('groups').getAll(id).filter(function(group) {461 return group('users').contains(email)462 }))463 .then(function(cursor) {464 return cursor.toArray()465 })466 .then(function(groups) {467 return groups[0]468 })469}470dbapi.getUserGroups = function(email) {471 return db472 .run(r.table('groups')473 .filter(function(group) {474 return group('users').contains(email)475 }))476 .then(function(cursor) {477 return cursor.toArray()478 })479}480dbapi.getOnlyUserGroups = function(email) {481 return db482 .run(r.table('groups')483 .filter(function(group) {484 return group('owner')('email')485 .ne(email)486 .and(group('users').contains(email))487 }))488 .then(function(cursor) {489 return cursor.toArray()490 })491}492dbapi.getTransientGroups = function() {493 return db494 .run(r.table('groups')495 .filter(function(group) {496 return group('class')497 .ne(apiutil.BOOKABLE)498 .and(group('class').ne(apiutil.STANDARD))499 }))500 .then(function(cursor) {501 return cursor.toArray()502 })503}504dbapi.getDeviceTransientGroups = function(serial) {505 return db506 .run(r.table('groups')507 .filter(function(group) {508 return group('class')509 .ne(apiutil.BOOKABLE)510 .and(group('class').ne(apiutil.STANDARD))511 .and(group('devices').contains(serial))512 }))513 .then(function(cursor) {514 return cursor.toArray()515 })516}517dbapi.isDeviceBooked = function(serial) {518 return dbapi.getDeviceTransientGroups(serial)519 .then(function(groups) {520 return groups.length > 0521 })522}523dbapi.isRemoveGroupUserAllowed = function(email, targetGroup) {524 if (targetGroup.class !== apiutil.BOOKABLE) {525 return Promise.resolve(true)526 }527 return db.run(528 r.table('groups')529 .getAll(email, {index: 'owner'})530 .filter(function(group) {531 return group('class')532 .ne(apiutil.BOOKABLE)533 .and(group('class').ne(apiutil.STANDARD))534 .and(r.expr(targetGroup.devices)535 .setIntersection(group('devices'))536 .isEmpty()537 .not())538 }))539 .then(function(cursor) {540 return cursor.toArray()541 })542 .then(function(groups) {543 return groups.length === 0544 })545}546dbapi.isUpdateDeviceOriginGroupAllowed = function(serial, targetGroup) {547 return dbapi.getDeviceTransientGroups(serial)548 .then(function(groups) {549 if (groups.length) {550 if (targetGroup.class === apiutil.STANDARD) {551 return false552 }553 for (const group of groups) {554 if (targetGroup.users.indexOf(group.owner.email) < 0) {555 return false556 }557 }558 }559 return true560 })561}562dbapi.getDeviceGroups = function(serial) {563 return db564 .run(r.table('groups')565 .filter(function(group) {566 return group('devices').contains(serial)567 }))568 .then(function(cursor) {569 return cursor.toArray()570 })571}572dbapi.getGroupAsOwnerOrAdmin = function(email, id) {573 return dbapi.getGroup(id).then(function(group) {574 if (group) {575 if (email === group.owner.email) {576 return group577 }578 return dbapi.loadUser(email).then(function(user) {579 if (user && user.privilege === apiutil.ADMIN) {580 return group581 }582 return false583 })584 }585 return false586 })587}588dbapi.getOwnerGroups = function(email) {589 return dbapi.getRootGroup().then(function(group) {590 if (email === group.owner.email) {591 return dbapi.getGroups()592 }593 return dbapi.getGroupsByIndex(email, 'owner')594 })595}596dbapi.createGroup = function(data) {597 const id = util.format('%s', uuid.v4()).replace(/-/g, '')598 return db.run(r.table('groups').insert(599 Object.assign(data, {600 id: id601 , users: _.union(data.users, [data.owner.email])602 , devices: []603 , createdAt: r.now()604 , lock: {605 user: false606 , admin: false607 }608 , ticket: null609 })))610 .then(function() {611 return dbapi.getGroup(id)612 })613}614dbapi.createUserGroup = function(data) {615 return dbapi.reserveUserGroupInstance(data.owner.email).then(function(stats) {616 if (stats.replaced) {617 return dbapi.getRootGroup().then(function(rootGroup) {618 data.users = [rootGroup.owner.email]619 return dbapi.createGroup(data).then(function(group) {620 return Promise.all([621 dbapi.addGroupUser(group.id, group.owner.email)622 , dbapi.addGroupUser(group.id, rootGroup.owner.email)623 ])624 .then(function() {625 return dbapi.getGroup(group.id)626 })627 })628 })629 }630 return false631 })632}633dbapi.updateGroup = function(id, data) {634 return db.run(r.table('groups').get(id).update(data))635 .then(function() {636 return dbapi.getGroup(id)637 })638}639dbapi.reserveUserGroupInstance = function(email) {640 return db.run(r.table('users').get(email)641 .update({groups: {quotas: {consumed: {number:642 r.branch(643 r.row('groups')('quotas')('consumed')('number')644 .add(1)645 .le(r.row('groups')('quotas')('allocated')('number'))646 , r.row('groups')('quotas')('consumed')('number')647 .add(1)648 , r.row('groups')('quotas')('consumed')('number'))649 }}}})650 )651}652dbapi.releaseUserGroupInstance = function(email) {653 return db.run(r.table('users').get(email)654 .update({groups: {quotas: {consumed: {number:655 r.branch(656 r.row('groups')('quotas')('consumed')('number').ge(1)657 , r.row('groups')('quotas')('consumed')('number').sub(1)658 , r.row('groups')('quotas')('consumed')('number'))659 }}}})660 )661}662dbapi.updateUserGroupDuration = function(email, oldDuration, newDuration) {663 return db.run(r.table('users').get(email)664 .update({groups: {quotas: {consumed: {duration:665 r.branch(666 r.row('groups')('quotas')('consumed')('duration')667 .sub(oldDuration).add(newDuration)668 .le(r.row('groups')('quotas')('allocated')('duration'))669 , r.row('groups')('quotas')('consumed')('duration')670 .sub(oldDuration).add(newDuration)671 , r.row('groups')('quotas')('consumed')('duration'))672 }}}})673 )674}675dbapi.updateUserGroupsQuotas = function(email, duration, number, repetitions) {676 return db677 .run(r.table('users').get(email)678 .update({groups: {quotas: {allocated: {679 duration:680 r.branch(681 r.expr(duration)682 .ne(null)683 .and(r.row('groups')('quotas')('consumed')('duration')684 .le(duration))685 .and(r.expr(number)686 .eq(null)687 .or(r.row('groups')('quotas')('consumed')('number')688 .le(number)))689 , duration690 , r.row('groups')('quotas')('allocated')('duration'))691 , number:692 r.branch(693 r.expr(number)694 .ne(null)695 .and(r.row('groups')('quotas')('consumed')('number')696 .le(number))697 .and(r.expr(duration)698 .eq(null)699 .or(r.row('groups')('quotas')('consumed')('duration')700 .le(duration)))701 , number702 , r.row('groups')('quotas')('allocated')('number'))703 }704 , repetitions:705 r.branch(706 r.expr(repetitions).ne(null)707 , repetitions708 , r.row('groups')('quotas')('repetitions'))709 }}}, {returnChanges: true}))710}711dbapi.updateDefaultUserGroupsQuotas = function(email, duration, number, repetitions) {712 return db.run(r.table('users').get(email)713 .update({groups: {quotas: {714 defaultGroupsDuration:715 r.branch(716 r.expr(duration).ne(null)717 , duration718 , r.row('groups')('quotas')('defaultGroupsDuration'))719 , defaultGroupsNumber:720 r.branch(721 r.expr(number).ne(null)722 , number723 , r.row('groups')('quotas')('defaultGroupsNumber'))724 , defaultGroupsRepetitions:725 r.branch(726 r.expr(repetitions).ne(null)727 , repetitions728 , r.row('groups')('quotas')('defaultGroupsRepetitions'))729 }}}, {returnChanges: true}))730}731dbapi.updateDeviceCurrentGroupFromOrigin = function(serial) {732 return db.run(r.table('devices').get(serial)).then(function(device) {733 return db.run(r.table('groups').get(device.group.origin)).then(function(group) {734 return db.run(r.table('devices').get(serial).update({group: {735 id: r.row('group')('origin')736 , name: r.row('group')('originName')737 , owner: group.owner738 , lifeTime: group.dates[0]739 , class: group.class740 , repetitions: group.repetitions741 }}))742 })743 })744}745dbapi.askUpdateDeviceOriginGroup = function(serial, group, signature) {746 return db.run(r.table('groups').get(group.id)747 .update({ticket: {748 serial: serial749 , signature: signature750 }})751 )752}753dbapi.updateDeviceOriginGroup = function(serial, group) {754 return db.run(r.table('devices').get(serial)755 .update({group: {756 origin: group.id757 , originName: group.name758 , id: r.branch(759 r.row('group')('id').eq(r.row('group')('origin'))760 , group.id761 , r.row('group')('id'))762 , name: r.branch(763 r.row('group')('id').eq(r.row('group')('origin'))764 , group.name765 , r.row('group')('name'))766 , owner: r.branch(767 r.row('group')('id').eq(r.row('group')('origin'))768 , group.owner769 , r.row('group')('owner'))770 , lifeTime: r.branch(771 r.row('group')('id').eq(r.row('group')('origin'))772 , group.dates[0]773 , r.row('group')('lifeTime'))774 , class: r.branch(775 r.row('group')('id').eq(r.row('group')('origin'))776 , group.class777 , r.row('group')('class'))778 , repetitions: r.branch(779 r.row('group')('id').eq(r.row('group')('origin'))780 , group.repetitions781 , r.row('group')('repetitions'))782 }})783 )784 .then(function() {785 return db.run(r.table('devices').get(serial))786 })787}788dbapi.updateDeviceCurrentGroup = function(serial, group) {789 return db.run(r.table('devices').get(serial)790 .update({group: {791 id: group.id792 , name: group.name793 , owner: group.owner794 , lifeTime: group.dates[0]795 , class: group.class796 , repetitions: group.repetitions797 }})798 )799}800dbapi.updateUserGroup = function(group, data) {801 return dbapi.updateUserGroupDuration(group.owner.email, group.duration, data.duration)802 .then(function(stats) {803 if (stats.replaced || stats.unchanged && group.duration === data.duration) {804 return dbapi.updateGroup(group.id, data)805 }806 return false807 })808}809dbapi.deleteGroup = function(id) {810 return db.run(r.table('groups').get(id).delete())811}812dbapi.deleteUserGroup = function(id) {813 function deleteUserGroup(group) {814 return dbapi.deleteGroup(group.id)815 .then(function() {816 return Promise.map(group.users, function(email) {817 return dbapi.removeGroupUser(group.id, email)818 })819 })820 .then(function() {821 return dbapi.releaseUserGroupInstance(group.owner.email)822 })823 .then(function() {824 return dbapi.updateUserGroupDuration(group.owner.email, group.duration, 0)825 })826 .then(function() {827 return 'deleted'828 })829 }830 return dbapi.getGroup(id).then(function(group) {831 if (group.privilege !== apiutil.ROOT) {832 return deleteUserGroup(group)833 }834 return 'forbidden'835 })836}837dbapi.createUser = function(email, name, ip) {838 return dbapi.getRootGroup().then(function(group) {839 return dbapi.loadUser(group.owner.email).then(function(adminUser) {840 return db.run(r.table('users').insert({841 email: email842 , name: name843 , ip: ip844 , group: wireutil.makePrivateChannel()845 , lastLoggedInAt: r.now()846 , createdAt: r.now()847 , forwards: []848 , settings: {}849 , privilege: adminUser ? apiutil.USER : apiutil.ADMIN850 , groups: {851 subscribed: []852 , lock: false853 , quotas: {854 allocated: {855 number: adminUser ?856 adminUser.groups.quotas.defaultGroupsNumber :857 group.envUserGroupsNumber858 , duration: adminUser ?859 adminUser.groups.quotas.defaultGroupsDuration :860 group.envUserGroupsDuration861 }862 , consumed: {863 number: 0864 , duration: 0865 }866 , defaultGroupsNumber: adminUser ? 0 : group.envUserGroupsNumber867 , defaultGroupsDuration: adminUser ? 0 : group.envUserGroupsDuration868 , defaultGroupsRepetitions: adminUser ? 0 : group.envUserGroupsRepetitions869 , repetitions: adminUser ?870 adminUser.groups.quotas.defaultGroupsRepetitions :871 group.envUserGroupsRepetitions872 }873 }874 }, {returnChanges: true}))875 .then(function(stats) {876 if (stats.inserted) {877 return dbapi.addGroupUser(group.id, email).then(function() {878 return dbapi.loadUser(email).then(function(user) {879 stats.changes[0].new_val = user880 return stats881 })882 })883 }884 return stats885 })886 })887 })888}889dbapi.saveUserAfterLogin = function(user) {890 return db.run(r.table('users').get(user.email).update({891 name: user.name892 , ip: user.ip893 , lastLoggedInAt: r.now()894 }))895 .then(function(stats) {896 if (stats.skipped) {897 return dbapi.createUser(user.email, user.name, user.ip)898 }899 return stats900 })901}902dbapi.loadUser = function(email) {903 return db.run(r.table('users').get(email))904}905dbapi.updateUserSettings = function(email, changes) {906 return db.run(r.table('users').get(email).update({907 settings: changes908 }))909}910dbapi.resetUserSettings = function(email) {911 return db.run(r.table('users').get(email).update({912 settings: r.literal({})913 }))914}915dbapi.insertUserAdbKey = function(email, key) {916 return db.run(r.table('users').get(email).update({917 adbKeys: r.row('adbKeys').default([]).append({918 title: key.title919 , fingerprint: key.fingerprint920 })921 }))922}923dbapi.deleteUserAdbKey = function(email, fingerprint) {924 return db.run(r.table('users').get(email).update({925 adbKeys: r.row('adbKeys').default([]).filter(function(key) {926 return key('fingerprint').ne(fingerprint)927 })928 }))929}930dbapi.lookupUsersByAdbKey = function(fingerprint) {931 return db.run(r.table('users').getAll(fingerprint, {932 index: 'adbKeys'933 }))934}935dbapi.lookupUserByAdbFingerprint = function(fingerprint) {936 return db.run(r.table('users').getAll(fingerprint, {937 index: 'adbKeys'938 })939 .pluck('email', 'name', 'group'))940 .then(function(cursor) {941 return cursor.toArray()942 })943 .then(function(groups) {944 switch (groups.length) {945 case 1:946 return groups[0]947 case 0:948 return null949 default:950 throw new Error('Found multiple users for same ADB fingerprint')951 }952 })953}954dbapi.lookupUserByVncAuthResponse = function(response, serial) {955 return db.run(r.table('vncauth').getAll([response, serial], {956 index: 'responsePerDevice'957 })958 .eqJoin('userId', r.table('users'))('right')959 .pluck('email', 'name', 'group'))960 .then(function(cursor) {961 return cursor.toArray()962 })963 .then(function(groups) {964 switch (groups.length) {965 case 1:966 return groups[0]967 case 0:968 return null969 default:970 throw new Error('Found multiple users with the same VNC response')971 }972 })973}974dbapi.loadUserDevices = function(email) {975 return db.run(r.table('users').get(email).getField('groups'))976 .then(function(groups) {977 return db.run(r.table('devices').filter(function(device) {978 return r.expr(groups.subscribed)979 .contains(device('group')('id'))980 .and(device('owner')('email').eq(email))981 .and(device('present').eq(true))982 }))983 })984}985dbapi.saveDeviceLog = function(serial, entry) {986 return db.run(r.table('logs').insert({987 serial: serial988 , timestamp: r.epochTime(entry.timestamp)989 , priority: entry.priority990 , tag: entry.tag991 , pid: entry.pid992 , message: entry.message993 }994 , {995 durability: 'soft'996 }))997}998dbapi.saveDeviceInitialState = function(serial, device) {999 var data = {1000 present: true1001 , presenceChangedAt: r.now()1002 , provider: device.provider1003 , owner: null1004 , status: device.status1005 , statusChangedAt: r.now()1006 , ready: false1007 , reverseForwards: []1008 , remoteConnect: false1009 , remoteConnectUrl: null1010 , usage: null1011 , logs_enabled: false1012 }1013 return db.run(r.table('devices').get(serial).update(data)).then(function(stats) {1014 if (stats.skipped) {1015 return dbapi.getRootGroup().then(function(group) {1016 data.serial = serial1017 data.createdAt = r.now()1018 data.group = {1019 id: group.id1020 , name: group.name1021 , lifeTime: group.dates[0]1022 , owner: group.owner1023 , origin: group.id1024 , class: group.class1025 , repetitions: group.repetitions1026 , originName: group.name1027 , lock: false1028 }1029 return db.run(r.table('devices').insert(data)).then(function() {1030 dbapi.addOriginGroupDevice(group, serial)1031 })1032 })1033 }1034 return true1035 })1036 .then(function() {1037 return db.run(r.table('devices').get(serial))1038 })1039}1040dbapi.setDeviceConnectUrl = function(serial, url) {1041 return db.run(r.table('devices').get(serial).update({1042 remoteConnectUrl: url1043 , remoteConnect: true1044 }))1045}1046dbapi.unsetDeviceConnectUrl = function(serial) {1047 return db.run(r.table('devices').get(serial).update({1048 remoteConnectUrl: null1049 , remoteConnect: false1050 }))1051}1052dbapi.saveDeviceStatus = function(serial, status) {1053 return db.run(r.table('devices').get(serial).update({1054 status: status1055 , statusChangedAt: r.now()1056 }))1057}1058dbapi.setDeviceOwner = function(serial, owner) {1059 return db.run(r.table('devices').get(serial).update({1060 owner: owner1061 }))1062}1063dbapi.unsetDeviceOwner = function(serial) {1064 return db.run(r.table('devices').get(serial).update({1065 owner: null1066 }))1067}1068dbapi.setDevicePresent = function(serial) {1069 return db.run(r.table('devices').get(serial).update({1070 present: true1071 , presenceChangedAt: r.now()1072 }))1073}1074dbapi.setDeviceAbsent = function(serial) {1075 return db.run(r.table('devices').get(serial).update({1076 present: false1077 , presenceChangedAt: r.now()1078 }))1079}1080dbapi.setDeviceUsage = function(serial, usage) {1081 return db.run(r.table('devices').get(serial).update({1082 usage: usage1083 , usageChangedAt: r.now()1084 }))1085}1086dbapi.unsetDeviceUsage = function(serial) {1087 return db.run(r.table('devices').get(serial).update({1088 usage: null1089 , usageChangedAt: r.now()1090 , logs_enabled: false1091 }))1092}1093dbapi.setDeviceAirplaneMode = function(serial, enabled) {1094 return db.run(r.table('devices').get(serial).update({1095 airplaneMode: enabled1096 }))1097}1098dbapi.setDeviceBattery = function(serial, battery) {1099 return db.run(r.table('devices').get(serial).update({1100 battery: {1101 status: battery.status1102 , health: battery.health1103 , source: battery.source1104 , level: battery.level1105 , scale: battery.scale1106 , temp: battery.temp1107 , voltage: battery.voltage1108 }1109 }1110 , {1111 durability: 'soft'1112 }))1113}1114dbapi.setDeviceBrowser = function(serial, browser) {1115 return db.run(r.table('devices').get(serial).update({1116 browser: {1117 selected: browser.selected1118 , apps: browser.apps1119 }1120 }))1121}1122dbapi.setDeviceConnectivity = function(serial, connectivity) {1123 return db.run(r.table('devices').get(serial).update({1124 network: {1125 connected: connectivity.connected1126 , type: connectivity.type1127 , subtype: connectivity.subtype1128 , failover: !!connectivity.failover1129 , roaming: !!connectivity.roaming1130 }1131 }))1132}1133dbapi.setDevicePhoneState = function(serial, state) {1134 return db.run(r.table('devices').get(serial).update({1135 network: {1136 state: state.state1137 , manual: state.manual1138 , operator: state.operator1139 }1140 }))1141}1142dbapi.setDeviceRotation = function(serial, rotation) {1143 return db.run(r.table('devices').get(serial).update({1144 display: {1145 rotation: rotation1146 }1147 }))1148}1149dbapi.setDeviceNote = function(serial, note) {1150 return db.run(r.table('devices').get(serial).update({1151 notes: note1152 }))1153}1154dbapi.setDeviceReverseForwards = function(serial, forwards) {1155 return db.run(r.table('devices').get(serial).update({1156 reverseForwards: forwards1157 }))1158}1159dbapi.setDeviceReady = function(serial, channel) {1160 return db.run(r.table('devices').get(serial).update({1161 channel: channel1162 , ready: true1163 , owner: null1164 , reverseForwards: []1165 }))1166}1167dbapi.saveDeviceIdentity = function(serial, identity) {1168 return db.run(r.table('devices').get(serial).update({1169 platform: identity.platform1170 , manufacturer: identity.manufacturer1171 , operator: identity.operator1172 , model: identity.model1173 , version: identity.version1174 , abi: identity.abi1175 , sdk: identity.sdk1176 , display: identity.display1177 , phone: identity.phone1178 , product: identity.product1179 , cpuPlatform: identity.cpuPlatform1180 , openGLESVersion: identity.openGLESVersion1181 , marketName: identity.marketName1182 }))1183}1184dbapi.loadDevices = function(groups) {1185 return db.run(r.table('devices').filter(function(device) {1186 return r.expr(groups).contains(device('group')('id'))1187 }))1188 .then(function(cursor) {1189 return cursor.toArray()1190 })1191}1192dbapi.loadDevicesByOrigin = function(groups) {1193 return db.run(r.table('devices').filter(function(device) {1194 return r.expr(groups).contains(device('group')('origin'))1195 }))1196 .then(function(cursor) {1197 return cursor.toArray()1198 })1199}1200dbapi.loadBookableDevices = function(groups) {1201 return db.run(r.table('devices').filter(function(device) {1202 return r.expr(groups)1203 .contains(device('group')('origin'))1204 .and(device('group')('class').ne(apiutil.STANDARD))1205 }))1206 .then(function(cursor) {1207 return cursor.toArray()1208 })1209}1210dbapi.loadStandardDevices = function(groups) {1211 return db.run(r.table('devices').filter(function(device) {1212 return r.expr(groups)1213 .contains(device('group')('origin'))1214 .and(device('group')('class').eq(apiutil.STANDARD))1215 }))1216 .then(function(cursor) {1217 return cursor.toArray()1218 })1219}1220dbapi.loadPresentDevices = function() {1221 return db.run(r.table('devices').getAll(true, {1222 index: 'present'1223 }))1224}1225dbapi.loadDeviceBySerial = function(serial) {1226 return db.run(r.table('devices').get(serial))1227}1228dbapi.loadDevice = function(groups, serial) {1229 return db.run(r.table('devices').getAll(serial).filter(function(device) {1230 return r.expr(groups).contains(device('group')('id'))1231 }))1232}1233dbapi.loadBookableDevice = function(groups, serial) {1234 return db.run(r.table('devices').getAll(serial).filter(function(device) {1235 return r.expr(groups)1236 .contains(device('group')('origin'))1237 .and(device('group')('class').ne(apiutil.STANDARD))1238 }))1239 .then(function(cursor) {1240 return cursor.toArray()1241 })1242}1243dbapi.loadDeviceByOrigin = function(groups, serial) {1244 return db.run(r.table('devices').getAll(serial).filter(function(device) {1245 return r.expr(groups).contains(device('group')('origin'))1246 }))1247 .then(function(cursor) {1248 return cursor.toArray()1249 })1250}1251dbapi.saveUserAccessToken = function(email, token) {1252 return db.run(r.table('accessTokens').insert({1253 email: email1254 , id: token.id1255 , title: token.title1256 , jwt: token.jwt1257 }, {returnChanges: true}))1258}1259dbapi.removeUserAccessTokens = function(email) {1260 return db.run(r.table('accessTokens').getAll(email, {1261 index: 'email'1262 }).delete())1263}1264dbapi.removeUserAccessToken = function(email, title) {1265 return db.run(r.table('accessTokens').getAll(email, {1266 index: 'email'1267 }).filter({title: title}).delete())1268}1269dbapi.removeAccessToken = function(id) {1270 return db.run(r.table('accessTokens').get(id).delete())1271}1272dbapi.loadAccessTokens = function(email) {1273 return db.run(r.table('accessTokens').getAll(email, {1274 index: 'email'1275 }))1276}1277dbapi.loadAccessToken = function(id) {1278 return db.run(r.table('accessTokens').get(id))1279}...
Using AI Code Generation
1var dbapi = require('devicefarmer-stf').dbapi;2var logger = require('devicefarmer-stf').logger;3var Promise = require('bluebird');4var util = require('util');5var _ = require('lodash');6var db = require('devicefarmer-stf').db;7var dbConnection = db.connect(dburl);8var ObjectId = require('mongodb').ObjectID;9var data = {10 _id: new ObjectId("5a6b2f6d2b6f7b0001b0b7f4"),
Using AI Code Generation
1var dbapi = require('devicefarmer-stf/lib/db/api');2.then(function() {3 return dbapi.getDevices();4})5.then(function(devices) {6 console.log(devices);7})8.catch(function(err) {9 console.error('ERR', err.stack);10})11.finally(function() {12 dbapi.disconnect();13});14var dbapi = require('devicefarmer-stf/lib/db/api');15.then(function() {16 return dbapi.getDevices({present: true});17})18.then(function(devices) {19 console.log(devices);20})21.catch(function(err) {22 console.error('ERR', err.stack);23})24.finally(function() {25 dbapi.disconnect();26});27var dbapi = require('devicefarmer-stf/lib/db/api');28.then(function() {29 return dbapi.getDevices({present: true, ready: true});30})31.then(function(devices) {32 console.log(devices);33})34.catch(function(err) {35 console.error('ERR', err.stack);36})37.finally(function() {38 dbapi.disconnect();39});40 at tryCatcher (/home/sagar/stf/node_modules/bluebird/js/release/util.js:16:23)41 at Promise._settlePromiseFromHandler (/home/sagar/stf/node_modules/bluebird/js/release/promise.js:512:31)42 at Promise._settlePromise (/home/sagar/stf/node_modules/bluebird/js/release/promise.js:569:18)
Using AI Code Generation
1var dbapi = require('devicefarmer-stf').dbapi;2dbapi.getDevices(db).then(function (devices) {3 console.log(devices);4});5var dbapi = require('devicefarmer-stf').dbapi;6dbapi.getDevices(db).then(function (devices) {7 console.log(devices);8});9var dbapi = require('devicefarmer-stf').dbapi;10dbapi.getDevices(db).then(function (devices) {11 console.log(devices);12});13var dbapi = require('devicefarmer-stf').dbapi;14dbapi.getDevices(db).then(function (devices) {15 console.log(devices);16});17var dbapi = require('devicefarmer-stf').dbapi;18dbapi.getDevices(db).then(function (devices) {19 console.log(devices);20});21var dbapi = require('devicefarmer-stf').dbapi;22dbapi.getDevices(db).then(function (devices) {23 console.log(devices);24});25var dbapi = require('devicefarmer-stf').dbapi;26dbapi.getDevices(db).then(function (devices) {27 console.log(devices);28});29var dbapi = require('devicefar
Using AI Code Generation
1var dbapi = require('devicefarmer-stf').dbapi;2var db = dbapi.connect({3});4db.loadDevices().then(function (devices) {5 console.log(devices);6});7var dbapi = require('stf').dbapi;8var db = dbapi.connect({9});10db.loadDevices().then(function (devices) {11 console.log(devices);12});
Using AI Code Generation
1var dbapi = require('devicefarmer-stf').dbapi;2var connect = require('devicefarmer-stf').connect;3var Promise = require('bluebird');4var util = require('util');5var MongoClient = require('mongodb').MongoClient;6var assert = require('assert');7var db = null;8var dbPromise = null;9function connectToMongo() {10 dbPromise = new Promise(function(resolve, reject) {11 MongoClient.connect(url, function(err, db) {12 if (err) {13 reject(err);14 } else {15 resolve(db);16 }17 });18 });19 return dbPromise;20}21function getDB() {22 return dbPromise;23}24function getDevices() {25 var devices = dbapi.loadDevices(db);26 return devices;27}28connectToMongo().then(function(db) {29 console.log("Connected to DB");30 return getDevices();31}).then(function(devices) {32 console.log(devices);33 console.log("Devices loaded");34});35var dbapi = require('devicefarmer-stf').dbapi;36var connect = require('devicefarmer-stf').connect;37var Promise = require('bluebird');38var util = require('util');39var MongoClient = require('mongodb').MongoClient;40var assert = require('assert');41var db = null;42var dbPromise = null;43function connectToMongo() {44 dbPromise = new Promise(function(resolve, reject) {45 MongoClient.connect(url, function(err, db) {46 if (err) {47 reject(err);48 } else {49 resolve(db);50 }51 });52 });53 return dbPromise;54}55function getDB() {56 return dbPromise;57}58function getDevices() {59 var devices = dbapi.loadDevices(db);60 return devices;61}62connectToMongo().then(function(db) {63 console.log("Connected to DB");64 return getDevices();65}).then(function(devices) {66 console.log(devices);67 console.log("Devices loaded");68});69var dbapi = require('devicefarmer-stf').dbapi;
Using AI Code Generation
1var dbapi = require('devicefarmer-stf/lib/db/api');2dbapi.connect(function(err) {3 if (err) {4 console.log('Error connecting to database: ' + err);5 process.exit(1);6 }7 dbapi.getDevices(function(err, devices) {8 if (err) {9 console.log('Error getting devices: ' + err);10 process.exit(1);11 }12 console.log('Devices: ' + devices);13 });14});15Devices: [ { serial: '0123456789ABCDEF',
Using AI Code Generation
1var dbapi = require('stf').dbapi;2 if (err) {3 console.log('Unable to connect to database: %s', err)4 process.exit(1)5 }6 console.log('Connected to database')7})
Using AI Code Generation
1var dbapi = require('devicefarmer-stf/lib/db/api');2dbapi.getDevices().then(function (devices) {3 console.log("Devices: ", devices);4});5 at Object. (/home/rahul/Desktop/devicefarmer-stf-master/test.js:6:13)6 at Module._compile (module.js:570:32)7 at Object.Module._extensions..js (module.js:579:10)8 at Module.load (module.js:487:32)9 at tryModuleLoad (module.js:446:12)10 at Function.Module._load (module.js:438:3)11 at Function.Module.runMain (module.js:604:10)12 at startup (bootstrap_node.js:158:16)13var dbapi = require('devicefarmer-stf').dbapi;14var dbapi = require('devicefarmer-stf').dbapi;
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!!