How to use serverAddr method in Playwright Internal

Best JavaScript code snippet using playwright-internal

pipe.js

Source:pipe.js Github

copy

Full Screen

1const crypto = require('crypto')2const stream = require('stream')3const fs = require('fs')4const path = require('path')5const http = require('http')6const request = require('superagent')7const uuid = require('uuid')8const debug = require('debug')('station')9const Promise = require('bluebird')10const mkdirp = require('mkdirp')11const mkdirpAsync = Promise.promisify(mkdirp)12const rimraf = require('rimraf')13const rimrafAsync = Promise.promisify(rimraf)14const sanitize = require('sanitize-filename')15const btrfs = require('../../lib/btrfs')16const requestAsync = require('./request').requestHelperAsync17const broadcast = require('../../common/broadcast')18const Fingerprint = require('../../lib/fingerprint2')19// const boxData = require('../../box/boxData')20const getFruit = require('../../fruitmix')21const { createIpcMain, getIpcMain, destroyIpcMain } = require('../../webtorrent/ipcMain')22const { isUUID } = require('../../common/assertion')23// const Config = require('./const').CONFIG24const Transform = stream.Transform25Promise.promisifyAll(fs)26let asCallback = (fn) => {27 return (props, callback) => {28 fn(props)29 .then(data => callback(null, data))30 .catch(e => callback(e))31 }32}33class HashTransform extends Transform {34 constructor() {35 super()36 this.hashStream = crypto.createHash('sha256')37 this.length = 038 }39 _transform(buf, enc, next) {40 this.length += buf.length41 this.hashStream.update(buf, enc)42 this.push(buf)43 next()44 }45 getHash() {46 return this.hashStream.digest('hex')47 }48}49class StoreFile {50 //TODO: miniprogram no sha25651 constructor(tmp, size, sha256) {52 this.tmp = tmp53 this.size = size54 this.sha256 = sha25655 }56 async storeFileAsync(cloudAddr, sessionId, saId, token) {57 return Promise.promisify(this.storeFile).bind(this)(cloudAddr, sessionId, saId, token)58 }59 storeFile(cloudAddr, sessionId, saId, token, callback) {60 let transform = new HashTransform()61 let url = cloudAddr + '/s/v1/stations/' + saId + '/response/' + sessionId62 let fpath = path.join(this.tmp, uuid.v4())63 let finished = false64 debug('start store')65 let error = (err) => {66 debug(err)67 if (finished) return68 finished = true69 debug('store file coming error')70 return callback(err)71 }72 let finish = (fpath) => {73 if (finished) return74 debug('store file checking')75 let bytesWritten = ws.bytesWritten76 let sha256 = transform.getHash()77 debug('Bytes Written -->', bytesWritten)78 if (bytesWritten !== this.size)79 return error(Object.assign(new Error('size mismatch'), { code: 'EMISMATCH' }))80 if (sha256 !== this.sha256)81 return error(Object.assign(new Error('sha256 mismatch'), { code: 'EMISMATCH' }))82 debug('store file bytesWritten')83 finished = true84 callback(null, fpath)85 }86 let abort = () => {87 if (finished) return88 finished = true89 callback(new Error('EABORT'))90 }91 let req = request.get(url).set({ 'Authorization': token }).buffer(false)92 let ws = fs.createWriteStream(fpath)93 debug('store req created')94 req.on('response', res => {95 debug('response', fpath)96 if (res.status !== 200) {97 debug('response error', fpath)98 error(res.error)99 ws.end()100 }101 })102 req.on('error', err => error(err))103 req.on('abort', () => error(new Error('EABORT')))104 ws.on('finish', () => finish(fpath))105 ws.on('error', err => error(err))106 req.pipe(transform).pipe(ws)107 }108}109/* data: {110 type: 'pipe', // socket communication multiplexing111 112 sessionId: // client-cloud-station pipe session id (uuid)113 user: { // valid user data format114 userId: 'xxx',115 nickName: 'xxx',116 avator: 'xxx', 117 },118 method: 'GET', 'POST', 'PUT', 'DELETE', 'PATCH',119 resource: 'path string', // req.params must base64 encode120 body: { // req.body, req.query121 122 },123 serverAddr: // valid ip address, whitelist124 }*/125/**126 * service for connect message 'pipe'127 * ctx : stationh128 */129class Pipe {130 constructor(ctx) {131 this.tmp = path.join(ctx.froot, 'tmp')132 // this.connect = ctx133 // this.connect.register('pipe', this.handle.bind(this))134 this.ctx = ctx135 this.token = ctx.token136 this.stationId = ctx.station.id137 this.handlers = new Map()138 this.register()139 }140 /**141 * @param {object} data -- from socket142 * 143 * {144 * resource,145 * method,146 * user:{147 * id,148 * nickName,149 * unionId,150 * avatarUrl151 * },152 * others...153 * }154 */155 handle(data) {156 debug(data)157 if (!data.serverAddr || !data.sessionId) return debug('Invaild pipe request')158 let fruit = getFruit()159 if (!fruit) return this.errorResponseAsync(data.serverAddr, data.sessionId, Object.assign(new Error('fruitmix not start'), { code: 500 }))160 .then(() => { }).catch(debug)161 if (!data.resource || !data.method) {162 debug('resource or method error')163 return this.errorResponseAsync(data.serverAddr, data.sessionId, Object.assign(new Error('resource or method not found'), { code: 400 }))164 .then(() => { }).catch(debug)165 }166 let localUser = fruit.findUserByGUID(data.user.id)167 if(localUser)168 data.user = Object.assign({}, data.user, localUser)169 else 170 data.user.global = {171 id: data.user.id172 }173 174 // debug('fruit pipe user: ', data.user)175 let messageType = this.decodeType(data)176 if (data.needLocalUser && !localUser)177 return this.errorResponseAsync(data.serverAddr, data.sessionId, Object.assign(new Error('user not found'), { code: 400 }))178 .then(() => { }).catch(debug)179 if (!messageType) {180 debug('resource error')181 return this.errorResponseAsync(data.serverAddr, data.sessionId, Object.assign(new Error('resource error'), { code: 400 }))182 .then(() => { }).catch(debug)183 }184 debug('pipe messageType:', messageType)185 if (this.handlers.has(messageType))186 this.handlers.get(messageType)(data)187 .then(() => { debug('success for request') })188 .catch(e => {189 debug('pipe catch exception:', e)190 debug('pipe error messageType:', messageType)191 debug('pipe error subType: ', data.subType)192 if (['GetMediaThumbnail', 'GetMediaFile'].includes(data.subType))193 return this.errorFetchResponseAsync(data.serverAddr, data.sessionId, Object.assign(e, { code: 400 }))194 .then(() => { }).catch(debug)195 else if (['WriteDirNewFile', 'WriteDirAppendFile', 'CreateTweet'].includes(data.subType)) {196 let code = 400197 if (e.code === 'EEXIST') code = 403198 return this.errorStoreResponseAsync(data.serverAddr, data.sessionId, Object.assign(e, { code }))199 .then(() => { }).catch(debug)200 }201 else202 return this.errorResponseAsync(data.serverAddr, data.sessionId, Object.assign(e, { code: 400 }))203 .then(() => { }).catch(debug)204 })205 else206 debug('NOT FOUND EVENT HANDLER', messageType, data)207 }208 /**209 * 210 * @param {object} data211 * 212 * return type - this.handlers`s key 213 */214 decodeType(data) {215 let resource = new Buffer(data.resource, 'base64').toString('utf8')216 let method = data.method217 let paths = resource.split('/').filter(p => p.length)218 data.paths = [...paths] // record paths219 data.needLocalUser = true // middleware for check user220 if (!paths.length) return undefined221 let r1 = paths.shift()222 switch (r1) {223 case 'drives':224 return paths.length === 0 ? (method === 'GET' ? 'GetDrives' : (method === 'POST' ? 'CreateDrive' : undefined))225 : paths.length === 1 ? (method === 'GET' ? 'GetDrive' : (method === 'PATCH' ? 'UpdateDrive' : (method === 'DELETE' ? 'DeleteDrive' : undefined)))226 : paths.length === 2 && method === 'GET' ? 'GetDirectories'227 : paths.length === 3 && method === 'GET' ? 'GetDirectory'228 : paths.length === 4 && method === 'POST' ? 'WriteDir'229 : paths.length === 5 && method === 'GET' ? 'DownloadFile' : undefined230 break231 case 'media':232 return paths.length === 0 && method === 'GET' ? 'GetMetadatas'233 : paths.length === 1 && method === 'GET' ? 'GetMetadata'234 : undefined235 break236 case 'users':237 return paths.length === 0 ? (method === 'GET' ? 'GetUsers' : (method === 'POST' ? 'CreateUser' : undefined))238 : paths.length === 1 ? (method === 'GET' ? 'GetUser' : (method === 'PATCH' ? 'UpdateUserInfo' : undefined))239 : paths.length === 2 ? (method === 'GET' ? (paths[1] === 'media-blacklist' ? 'GetMediaBlackList' : undefined)240 : (method === 'PUT' ? (paths[1] === 'password' ? 'UpdateUserPasswd' : (paths[1] === 'media-blacklist' ? 'SetMediaBlackList' : undefined))241 : (method === 'POST' ? 'AddMediaBlackList'242 : (method === 'DELETE' ? 'SubtractUserMediaBlackList' : undefined))))243 : undefined244 break245 case 'token':246 return paths.length === 0 && method === 'GET' ? 'GetToken' : undefined247 break248 case 'station':249 return paths.length === 1 ? (method === 'GET' ? (paths[0] === 'info' ? 'GetStationInfo' 250 : (paths[0] === 'tickets' ? 'GetTickets' : undefined)) : (method === 'PATCH' ? 'UpdateStationInfo' : (method === 'POST' ? 'CreateTicket' : undefined)))251 : paths.length === 2 ? (method === 'GET' ? 'GetTicket' : undefined) 252 : paths.length === 3 ? 'ConfirmTicket'253 : undefined254 break255 case 'download':256 if (paths.length === 1 && method === 'GET' && paths[0] === 'switch') return 'getTorrentSwitch'257 if (paths.length === 1 && method === 'PATCH' && paths[0] === 'switch') return 'patchTorrentSwitch'258 if (paths[0] == 'ppg1') return 'ppg1'259 if (paths[0] == 'ppg2') return 'addTorrent'260 if (paths[0] == 'ppg3') return 'ppg3'261 if (paths[0] == 'http') return 'addHttp'262 if (paths[0] == 'version') return 'checkVersion'263 return paths.length === 0 && method === 'GET' ? 'getSummary' 264 : paths.length === 1 ? (method === 'PATCH' ? 'patchTorrent' : (paths[0] === 'magnet' ? 'addMagnet' : 'addTorrent'))265 : undefined266 break267 case 'boxes': {268 data.needLocalUser = false269 return paths.length === 0 ? (method === 'GET' ? 'GetBoxes' : 'CreateBox') 270 : (paths.length === 1 ? (method === 'GET' ? 'GetBox' : (method === 'PATCH' ? 'UpdateBox' : (method === 'DELETE' ? 'DeleteBox': undefined))) 271 : (paths.length === 2 ? (paths[1] === 'tweets' ? (method === 'GET' ? 'GetTweets' : (method === 'DELETE' ? 'DeleteTweets' : (method === 'POST' ? 'CreateTweet' : undefined))) : undefined)272 : (paths.length === 3 && paths[1] === 'files' ? 'GetBoxFile' 273 : undefined)))274 }275 break276 case 'tasks' :277 return paths.length === 0 ? (method === 'GET' ? 'GetTasks' : 'CreateTask')278 : paths.length === 1 ? (method === 'GET' ? 'GetTask' : 'DeleteTask')279 : paths.length === 3 ? (method === 'PATCH' ? 'UpdateSubTask' : 'DeleteSubTask')280 : undefined 281 break282 default:283 return undefined284 break285 }286 }287 /*****************************STATION*************************/288 async getStationInfoAsync(data) {289 let { serverAddr, sessionId, user, body, paths } = data290 let info = this.ctx.info()291 if(!info) return await this.errorResponseAsync(serverAddr, sessionId, new Error('station not start'))292 return await this.successResponseJsonAsync(serverAddr, sessionId, info)293 }294 async updateStationInfoAsync(data) {295 let { serverAddr, sessionId, user, body, paths } = data296 if(!this.ctx.initialized) return await this.errorResponseAsync(serverAddr, sessionId, new Error('station not start'))297 let info = await this.ctx.updateInfoAsync({ name:body.name })298 return await this.successResponseJsonAsync(serverAddr, sessionId, info) 299 }300 async getTicketsAsync(data) {301 let { serverAddr, sessionId, user, body, paths } = data302 if(!this.ctx.initialized) return await this.errorResponseAsync(serverAddr, sessionId, new Error('station not start'))303 let Tickets = this.ctx.tickets304 let ticketArr = await Tickets.getTicketsAsync(user.uuid)305 return await this.successResponseJsonAsync(serverAddr, sessionId, ticketArr)306 }307 async createTicketAsync(data) {308 let { serverAddr, sessionId, user, body, paths } = data309 if(!this.ctx.initialized) return await this.errorResponseAsync(serverAddr, sessionId, new Error('station not start'))310 let Tickets = this.ctx.tickets311 let ticket = await Tickets.createTicketAsync(user.uuid, body.type)312 return await this.successResponseJsonAsync(serverAddr, sessionId, ticket)313 }314 async getTicketAsync(data) {315 let { serverAddr, sessionId, user, body, paths } = data316 if(!this.ctx.initialized) return await this.errorResponseAsync(serverAddr, sessionId, new Error('station not start'))317 let Tickets = this.ctx.tickets318 let ticketId = paths[2]319 let t = await Tickets.getTicketAsync(ticketId)320 return await this.successResponseJsonAsync(serverAddr, sessionId, t)321 }322 async confirmTicketAsync(data) {323 let { serverAddr, sessionId, user, body, paths } = data324 if(!this.ctx.initialized) return await this.errorResponseAsync(serverAddr, sessionId, new Error('station not start'))325 let Tickets = this.ctx.tickets326 let guid = body.guid327 let state = body.state328 let ticketId = paths[3]329 let d = await Tickets.consumeTicket(user.uuid, guid, ticketId, state)330 return await this.successResponseJsonAsync(serverAddr, sessionId, d)331 }332 /*****************************TOKEN***************************/333 async getTokenAsync(data) {334 let { serverAddr, sessionId, user } = data335 let fruit = getFruit()336 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))337 let token = fruit.getToken(user)338 return await this.successResponseJsonAsync(serverAddr, sessionId, token)339 }340 /***********************************Dirves**************************/341 //get drives342 async getDrivesAsync(data) {343 let { serverAddr, sessionId, user } = data344 let fruit = getFruit()345 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))346 let drives = fruit.getDriveList(user)347 return await this.successResponseJsonAsync(serverAddr, sessionId, drives)348 }349 //create drive350 async createDriveAsync(data) {351 let { serverAddr, sessionId, user, body } = data352 let fruit = getFruit()353 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))354 let drives = await fruit.createPublicDriveAsync(user, body)355 return await this.successResponseJsonAsync(serverAddr, sessionId, drives)356 }357 //get drive358 async getDriveAsync(data) {359 let { serverAddr, sessionId, user, paths } = data360 let fruit = getFruit()361 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))362 if (paths.length !== 2 || !isUUID(paths[1])) return await this.errorResponseAsync(serverAddr, sessionId, new Error('resource error'))363 let driveUUID = paths[1]364 let drive = fruit.getDrive(user, driveUUID)365 return await this.successResponseJsonAsync(serverAddr, sessionId, drive)366 }367 async updateDriveAsync(data) {368 let { serverAddr, sessionId, user, body, paths } = data369 let fruit = getFruit()370 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))371 if (paths.length !== 2 || !isUUID(paths[1])) return await this.errorResponseAsync(serverAddr, sessionId, new Error('resource error'))372 let driveUUID = paths[1]373 let drive = await fruit.updatePublicDriveAsync(user, driveUUID, body)374 return await this.successResponseJsonAsync(serverAddr, sessionId, drive)375 }376 async deleteDriveAsync(data) {377 // not implemented yet378 }379 //fetch380 async getDirectoriesAsync(data) {381 let { serverAddr, sessionId, user, paths } = data382 let fruit = getFruit()383 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))384 if (paths.length !== 3 || paths[2] !== 'dirs' || !isUUID(paths[1])) return await this.errorResponseAsync(serverAddr, sessionId, new Error('resource error'))385 let driveUUID = paths[1]386 let dirs = fruit.getDriveDirs(user, driveUUID)387 return await this.successResponseJsonAsync(serverAddr, sessionId, dirs)388 }389 async getDirectoryAsync(data) {390 let { serverAddr, sessionId, user, body, paths } = data391 let fruit = getFruit()392 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))393 if (paths.length !== 4 || paths[2] !== 'dirs' || !isUUID(paths[1] || !isUUID(paths[3]))) return await this.errorResponseAsync(serverAddr, sessionId, new Error('resource error'))394 let driveUUID = paths[1]395 let dirUUID = paths[3]396 let metadata = body.metadata === 'true' ? true : false397 let counter = body.counter === 'true' ? true : false398 let dirs = await fruit.getDriveDirAsync(user, driveUUID, dirUUID, metadata, counter)399 return await this.successResponseJsonAsync(serverAddr, sessionId, dirs)400 }401 /**402 * 403 * @param {object} data 404 * 405 * {406 * version: 1,407 * name: fromPath|toPath, or 'name'408 * op: enum STRING ['mkdir', 'rename', 'dup', 'remove', 'newfile']409 * overwrite: optional(UUID)410 * size: 0 <= size <= 1G, INTEGER411 * sha256: (neglected when size === 0),412 * }413 */414 async writeDirAsync(data) {415 let { serverAddr, sessionId, user, body, paths } = data416 let fruit = getFruit()417 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))418 if (paths.length !== 5 || paths[2] !== 'dirs' || !isUUID(paths[1] || !isUUID(paths[3] || paths[4] !== 'entries')))419 return await this.errorResponseAsync(serverAddr, sessionId, new Error('resource error'))420 let driveUUID = paths[1]421 let dirUUID = paths[3]422 let ops = ['mkdir', 'rename', 'dup', 'remove', 'newfile', 'appendfile']423 if (!ops.includes(body.op))424 return await this.errorResponseAsync(serverAddr, sessionId, new Error('op error'))425 let da = Object.assign({}, body)426 da.driveUUID = driveUUID427 da.dirUUID = dirUUID428 data.body = da429 switch (da.op) {430 case 'mkdir':431 return await this.mkdirpAsync2(data)432 break433 case 'rename':434 return await this.renameAsync(data)435 break436 case 'dup':437 return await this.dupAsync(data)438 break439 case 'remove':440 return await this.removeAsync(data)441 break442 case 'newfile':443 return await this.newFileAsync(data)444 break445 case 'appendfile':446 return await this.appendFileAsync(data)447 break448 default:449 debug('unhandle writedir event')450 break451 }452 }453 /********************************************************************************************/454 /**455 * {456 * version: 1,457 * name: fromName|toName, or 'name'458 * op: enum STRING ['mkdir', 'rename', 'dup', 'remove', 'newfile']459 * overwrite: optional(UUID)460 * size: 0 <= size <= 1G, INTEGER461 * sha256: (neglected when size === 0),462 * dirUUID,463 * driveUUID,464 * fromName,465 * toName466 * }467 */468 async mkdirpAsync(data) {469 let { serverAddr, sessionId, user, body, paths } = data470 let fruit = getFruit()471 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))472 let asyncMkdir = Promise.promisify(fruit.mkdirp).bind(fruit)473 let xstat = await asyncMkdir(user, body.driveUUID, body.dirUUID, body.toName)474 debug('mkdirp success', xstat)475 return await this.successResponseJsonAsync(serverAddr, sessionId, xstat)476 }477 async mkdirpAsync2 (data) {478 let { serverAddr, sessionId, user, body, paths } = data479 let fruit = getFruit()480 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))481 let dst = {482 drive: body.driveUUID,483 dir: body.dirUUID,484 name: body.toName485 }486 let asyncMkdir = Promise.promisify(fruit.driveList.mkdir).bind(fruit.driveList)487 let xstat = await asyncMkdir(dst, ['skip', null])488 debug('mkdirp success', xstat)489 return await this.successResponseJsonAsync(serverAddr, sessionId, xstat)490 }491 async renameAsync(data) {492 let { serverAddr, sessionId, user, body, paths } = data493 let fruit = getFruit()494 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))495 let asyncRename = Promise.promisify(fruit.rename).bind(fruit)496 let xstat = await asyncRename(user, body.driveUUID, body.dirUUID, body.fromName, body.toName, body.overwrite)497 debug('renameAsync success', xstat)498 return await this.successResponseJsonAsync(serverAddr, sessionId, xstat)499 }500 async dupAsync(data) {501 let { serverAddr, sessionId, user, body, paths } = data502 let fruit = getFruit()503 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))504 let asyncDup = Promise.promisify(fruit.dup).bind(fruit)505 let xstat = await asyncDup(user, body.driveUUID, body.dirUUID, body.fromName, body.toName, body.overwrite)506 debug('dupAsync success', xstat)507 return await this.successResponseJsonAsync(serverAddr, sessionId, xstat)508 }509 async removeAsync(data) {510 let { serverAddr, sessionId, user, body, paths } = data511 let fruit = getFruit()512 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))513 let asyncRemove = Promise.promisify(fruit.rimraf).bind(fruit)514 await asyncRemove(user, body.driveUUID, body.dirUUID, body.toName, body.uuid)515 debug('removeAsync success')516 return await this.successResponseJsonAsync(serverAddr, sessionId, {})517 }518 async newFileAsync(data) {519 let { serverAddr, sessionId, user, body, paths } = data520 let fruit = getFruit()521 if (!fruit) return await this.errorStoreResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))522 data.subType = 'WriteDirNewFile'523 let store = new StoreFile(this.tmp, body.size, body.sha256)524 let fpath = await store.storeFileAsync(serverAddr, sessionId, this.stationId, this.token)525 let asyncNewFile = Promise.promisify(fruit.createNewFile).bind(fruit)526 let xstat = await asyncNewFile(user, body.driveUUID, body.dirUUID, body.toName, fpath, body.sha256, body.overwrite)527 debug('newFileAsync success', xstat)528 await this.successStoreResponseAsync(serverAddr, sessionId, xstat)529 }530 async appendFileAsync(data) {531 let { serverAddr, sessionId, user, body, paths } = data532 let fruit = getFruit()533 if (!fruit) return await this.errorStoreResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))534 data.subType = 'WriteDirAppendFile'535 let store = new StoreFile(this.tmp, body.size, body.sha256)536 let fpath = await store.storeFileAsync(serverAddr, sessionId, this.stationId, this.token)537 let asyncAppendFile = Promise.promisify(fruit.appendFile).bind(fruit)538 let tmp = { path: fpath, size: body.size, sha256: body.sha256 }539 let xstat = await asyncAppendFile(user, body.driveUUID, body.dirUUID, body.toName, body.append, tmp)540 debug('appendFileAsync success', xstat)541 await this.successStoreResponseAsync(serverAddr, sessionId, xstat)542 }543 async downloadFileAsync(data) {544 let { serverAddr, sessionId, user, body, paths } = data545 let fruit = getFruit()546 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))547 if (paths.length !== 6 || paths[2] !== 'dirs' || paths[4] !== 'entries' || !isUUID(paths[1]) || !isUUID(paths[3]) || !isUUID(paths[5])) return await this.errorResponseAsync(serverAddr, sessionId, new Error('resource error'))548 let driveUUID = paths[1]549 let dirUUID = paths[3]550 let entryUUID = paths[5]551 let name = body.name552 let dirPath = fruit.getDriveDirPath(user, driveUUID, dirUUID)553 let filePath = path.join(dirPath, name)554 return await this.fetchFileResponseAsync(filePath, serverAddr, sessionId)555 }556 /****************************************Media Api**************************************/557 // return metadata list558 async getMetadatasAsync(data) {559 let { serverAddr, sessionId, user, body } = data560 let fruit = getFruit()561 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))562 let metadata = fruit.getMetaList(user)563 debug('getMetaList success', metadata)564 return await this.successResponseJsonAsync(serverAddr, sessionId, metadata)565 }566 /**567 * body.alt568 * if alt === metadata return metadata569 * if alt === data return file570 * if alt === thumbnail return thumbnail571 */572 async getMetadataAsync(data) {573 let { serverAddr, sessionId, user, body, paths } = data574 let fruit = getFruit()575 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))576 const fingerprint = paths[1]577 if (body.alt === undefined || body.alt === 'metadata') {578 data.subType = 'GetMediaMetadata'579 let metadata = fruit.getMetadata(null, fingerprint)580 if (metadata) {581 return await this.successResponseJsonAsync(serverAddr, sessionId, metadata)582 } else {583 return await this.errorResponseAsync(serverAddr, sessionId, new Error('metadata not found'))584 }585 }586 else if (body.alt === 'data') {587 data.subType = 'GetMediaFile'588 let file589 if(body.boxUUID) {590 file = getFruit().getBoxFilepath(user, body.boxUUID, fingerprint)591 if (!file) 592 return await this.errorFetchResponseAsync(serverAddr, sessionId, new Error('media not found'))593 } else {594 let files = fruit.getFilesByFingerprint(user, fingerprint)595 if (!files.length) 596 return await this.errorFetchResponseAsync(serverAddr, sessionId, new Error('media not found'))597 file = files[0]598 }599 return await this.fetchFileResponseAsync(file, serverAddr, sessionId)600 }601 else if (body.alt === 'thumbnail') {602 data.subType = 'GetMediaThumbnail'603 let thumb = await this.getMediaThumbnailAsync(user, fingerprint, body)604 if (thumb) {605 return await this.fetchFileResponseAsync(thumb, serverAddr, sessionId)606 } else {607 return await this.errorFetchResponseAsync(serverAddr, sessionId, new Error('thumbnail not found'))608 }609 } else {610 return await this.errorResponseAsync(serverAddr, sessionId, new Error('operation not found'))611 }612 }613 getMediaThumbnail(user, fingerprint, query, callback) {614 //getMediaThumbnail615 let fruit = getFruit()616 if (!fruit) return callback(new Error('fruitmix not start'))617 if(query.boxUUID) {618 try{619 let fp = fruit.getBlobMediaThumbnail(user, fingerprint, query, (err, thumb) => {620 if (err) return callback(err)621 if (typeof thumb === 'string') {622 callback(null, thumb)623 } else if (typeof thumb === 'function') {624 let cancel = thumb((err, th) => {625 if (err) return callback(err)626 callback(null, th)627 })628 // TODO cancel629 } else {630 callback(new Error(`unexpected thumb type ${typeof thumb}`))631 }632 })633 }634 catch(e) { return callback(e) }635 }636 else {637 fruit.getThumbnail(user, fingerprint, query, (err, thumb) => {638 if (err) return callback(err)639 if (typeof thumb === 'string') {640 return callback(null, thumb)641 } else if (typeof thumb === 'function') {642 let cancel = thumb((err, th) => {643 if (err) return callback(err)644 return callback(null, th)645 })646 }647 })648 }649 }650 async getMediaThumbnailAsync(user, fingerprint, query) {651 return Promise.promisify(this.getMediaThumbnail).bind(this)(user, fingerprint, query)652 }653 /*************************************** Station *****************************************/654 655 /*************************************** User *********************************************/656 // get user list657 async getUsersAsync(data) {658 let { serverAddr, sessionId, user } = data659 let fruit = getFruit()660 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))661 // let userList = user.isAdmin ? fruit.getUsers() : fruit.displayUsers()662 let userList = fruit.getUsers()663 return await this.successResponseJsonAsync(serverAddr, sessionId, userList)664 }665 // not first user666 // create new user667 async createUserAsync(data) {668 let { serverAddr, sessionId, user, body } = data669 let fruit = getFruit()670 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))671 let newUser = await fruit.createUserAsync(user, body)672 return await this.successResponseJsonAsync(serverAddr, sessionId, newUser)673 }674 /**675 * get single user info676 * @param { Object } data 677 */678 async getUserAsync(data) {679 let { serverAddr, sessionId, user, body, paths } = data680 let fruit = getFruit()681 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))682 let err = {}, userUUID = paths[1]683 if (user.uuid === userUUID || user.isAdmin) {684 let u = fruit.findUserByUUID(userUUID)685 if (u) return await this.successResponseJsonAsync(serverAddr, sessionId, u)686 err = new Error('user not find')687 err.code = 404688 return await this.errorResponseAsync(serverAddr, sessionId, err)689 }690 err.message = 'auth error'691 err.code = 403692 return await this.errorResponseAsync(serverAddr, sessionId, err)693 }694 // update name, isAdmin, disabled 695 async updateUserInfoAsync(data) {696 let { serverAddr, sessionId, user, body, paths } = data697 let fruit = getFruit()698 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))699 let u, userUUID = paths[1]700 u = await fruit.updateUserAsync(user, userUUID, body)701 return await this.successResponseJsonAsync(serverAddr, sessionId, u)702 }703 async updateUserPasswdAsync(data) {704 let { serverAddr, sessionId, user, body, paths } = data705 let fruit = getFruit()706 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))707 let userUUID = paths[1]708 if (user.uuid !== userUUID) return await this.errorResponseAsync(serverAddr, sessionId, new Error('user uuid mismatch'))709 await fruit.updateUserPasswordAsync(user, userUUID, body)710 return await this.successResponseJsonAsync(serverAddr, sessionId, {})711 }712 async getUserMediaBlackListAsync(data) {713 let { serverAddr, sessionId, user, body, paths } = data714 let fruit = getFruit()715 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))716 let userUUID = paths[1]717 if (user.uuid !== userUUID) return await this.errorResponseAsync(serverAddr, sessionId, new Error('user uuid mismatch'))718 let list = await fruit.getMediaBlacklistAsync(user)719 return await this.successResponseJsonAsync(serverAddr, sessionId, list)720 }721 /**722 * FIXME: mediablacklist array ->> add key blacklist 723 */724 async setUserMediaBlackListAsync(data) {725 let { serverAddr, sessionId, user, body, paths } = data726 let fruit = getFruit()727 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))728 let userUUID = paths[1]729 let list = await fruit.setMediaBlacklistAsync(user, body.blacklist)730 return await this.successResponseJsonAsync(serverAddr, sessionId, list)731 }732 /**733 * FIXME: mediablacklist array ->> add key blacklist 734 */735 async addUserMediaBlackListAsync(data) {736 let { serverAddr, sessionId, user, body, paths } = data737 let fruit = getFruit()738 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))739 let userUUID = paths[1]740 if (user.uuid !== userUUID) return await this.errorResponseAsync(serverAddr, sessionId, new Error('user uuid mismatch'))741 let list = await fruit.addMediaBlacklistAsync(user, body.blacklist)742 return await this.successResponseJsonAsync(serverAddr, sessionId, list)743 }744 /**745 * FIXME: mediablacklist array ->> add key blacklist 746 */747 async subtractUserMediaBlackListAsync(data) {748 let { serverAddr, sessionId, user, body, paths } = data749 let fruit = getFruit()750 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))751 let userUUID = paths[1]752 if (user.uuid !== userUUID) return await this.errorResponseAsync(serverAddr, sessionId, new Error('user uuid mismatch'))753 let list = await fruit.subtractMediaBlacklistAsync(user, body.blacklist)754 return await this.successResponseJsonAsync(serverAddr, sessionId, list)755 }756 // download api757 // download (get summary)758 async getSummaryAsync(data) {759 let { serverAddr, sessionId, user, body, paths } = data760 let { torrentId, type } = body761 if (!getIpcMain()) return await this.errorResponseAsync(serverAddr, sessionId, new Error('webtorrent is not started'))762 getIpcMain().call('getSummary', { torrentId, type, user }, async (error, summary) => {763 if (error) await this.errorResponseAsync(serverAddr, sessionId, error)764 else await this.successResponseJsonAsync(serverAddr, sessionId, summary)765 })766 }767 async ppg3Async(data) {768 let { serverAddr, sessionId, user, body, paths } = data769 let { ppgId, type } = body770 if (!getIpcMain()) return await this.errorResponseAsync(serverAddr, sessionId, new Error('webtorrent is not started'))771 getIpcMain().call('getSummary', { torrentId: ppgId, type, user }, async (error, summary) => {772 if (error) await this.errorResponseAsync(serverAddr, sessionId, error)773 else {774 summary.ppgPath = summary.torrentPath775 summary.ppgURL = summary.magnetURL776 summary.torrentPath = undefined777 summary.magnetURL = undefined778 await this.successResponseJsonAsync(serverAddr, sessionId, summary)779 }780 })781 }782 // download (get version for ios)783 async checkVersionAsync() {784 await this.successResponseJsonAsync(serverAddr, sessionId, {version: false})785 }786 // download (operation in a task)787 async patchTorrentAsync(data) {788 let { serverAddr, sessionId, user, body, paths } = data789 let { op } = body790 let torrentId = paths[1]791 let ops = ['pause', 'resume', 'destroy']792 if (!getIpcMain()) return await this.errorResponseAsync(serverAddr, sessionId, new Error('webtorrent is not started'))793 if(!ops.includes(op)) return await this.errorResponseAsync(serverAddr, sessionId, new Error('unknow op'))794 let result = await getIpcMain().callAsync(op, { torrentId, user })795 this.successResponseJsonAsync(serverAddr, sessionId, result)796 }797 // download (create magnet task)798 async addMagnetAsync(data) {799 let { serverAddr, sessionId, user, body, paths } = data800 let { dirUUID, magnetURL } = body801 if (!getIpcMain()) return await this.errorResponseAsync(serverAddr, sessionId, new Error('webtorrent is not started'))802 let result = await getIpcMain().callAsync('addMagnet', { magnetURL, dirUUID, user})803 this.successResponseJsonAsync(serverAddr, sessionId, result)804 }805 async ppg1Async(data) {806 let { serverAddr, sessionId, user, body, paths } = data807 let { dirUUID, ppgURL } = body808 if (!getIpcMain()) return await this.errorResponseAsync(serverAddr, sessionId, new Error('webtorrent is not started'))809 let result = await getIpcMain().callAsync('addMagnet', { magnetURL:ppgURL, dirUUID, user})810 this.successResponseJsonAsync(serverAddr, sessionId, result)811 }812 // download (create torrent task)813 async addTorrentAsync(data) {814 let { serverAddr, sessionId, user, body, paths } = data815 if (!getIpcMain()) return await this.errorStoreResponseAsync(serverAddr, sessionId, new Error('webtorrent is not started'))816 let { dirUUID } = body817 data.subType = 'WriteDirNewFile'818 let store = new StoreFile(this.tmp, body.size, body.sha256)819 let fpath = await store.storeFileAsync(serverAddr, sessionId, this.stationId, this.token)820 let fname = path.basename(fpath)821 let torrentTmp = path.join(getFruit().fruitmixPath, 'torrentTmp')822 let torrentPath = path.join(torrentTmp, fname)823 let fruit = getFruit()824 mkdirp.sync(torrentTmp)825 await fs.renameAsync(fpath, torrentPath)826 let result = await getIpcMain().callAsync('addTorrent', { torrentPath, dirUUID, user })827 return await this.successStoreResponseAsync(serverAddr, sessionId, result)828 // fs.rename(fpath, torrentPath, async (error, data) => {829 // if (error) return await this.errorStoreResponseAsync(serverAddr, sessionId, error)830 // else getIpcMain().call('addTorrent', { torrentPath, dirUUID, user }, async (err, result) => {831 // if (err) return await this.errorStoreResponseAsync(serverAddr, sessionId, err.message)832 // else return await this.successStoreResponseAsync(serverAddr, sessionId, result)833 // })834 // })835 }836 // download (create http task)837 async addHttpAsync(data) {838 let { serverAddr, sessionId, user, body, paths } = data839 let { dirUUID, url } = body840 if (!getIpcMain()) return await this.errorResponseAsync(serverAddr, sessionId, new Error('webtorrent is not started'))841 getIpcMain().call('addHttp', { url, dirUUID, user}, async (error, result) => {842 if (error) console.log(error)843 else console.log('not error') 844 if(error) return await this.errorResponseAsync(serverAddr, sessionId, error.message)845 else await this.successResponseJsonAsync(serverAddr, sessionId, result)846 })847 }848 async getTorrentSwitchAsync(data) {849 let { serverAddr, sessionId, user, body, paths } = data850 if (getIpcMain()) await this.successResponseJsonAsync(serverAddr, sessionId, {switch: true})851 else await this.successResponseJsonAsync(serverAddr, sessionId, {switch: false})852 }853 // download (toggle torrent service)854 async patchTorrentSwitchAsync(data) {855 let { serverAddr, sessionId, user, body, paths } = data856 let { op } = body857 let ops = ['start', 'close']858 if(!ops.includes(op)) return await this.errorResponseAsync(serverAddr, sessionId, new Error('unknow op'))859 if (op === 'close') destroyIpcMain()860 else createIpcMain()861 await this.successResponseJsonAsync(serverAddr, sessionId, {})862 }863 /********************************************************************************/864 /********************************* Tasks API **********************************/865 /********************************************************************************/866 async getTasksAsync(data) {867 let { serverAddr, sessionId, user, body, paths } = data868 let fruit = getFruit()869 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))870 let tasks = await new Promise((resolve, reject) => {871 fruit.getTasks(user, (err, tasks) => {872 if(err) return reject(err)873 resolve(tasks)874 })875 })876 await this.successResponseJsonAsync(serverAddr, sessionId, tasks)877 }878 async createTaskAsync(data) {879 let { serverAddr, sessionId, user, body, paths } = data880 let fruit = getFruit()881 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))882 let task = await new Promise((resolve, reject) => {883 fruit.createTask(user, body, (err, task) => {884 if(err) return reject(err)885 resolve(task)886 })887 })888 await this.successResponseJsonAsync(serverAddr, sessionId, task)889 }890 async getTaskAsync(data) {891 let { serverAddr, sessionId, user, body, paths } = data892 let fruit = getFruit()893 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))894 let taskId = paths[1]895 let task = await new Promise((resolve, reject) => {896 fruit.getTask(user, taskId, (err, task) => {897 if(err) return reject(err)898 resolve(task)899 })900 })901 await this.successResponseJsonAsync(serverAddr, sessionId, task)902 }903 async deleteTaskAsync(data) {904 let { serverAddr, sessionId, user, body, paths } = data905 let fruit = getFruit()906 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))907 let taskId = paths[1]908 await new Promise((resolve, reject) => {909 fruit.deleteTask(user, taskId, err => {910 if(err) return reject(err)911 resolve()912 })913 })914 await this.successResponseJsonAsync(serverAddr, sessionId, {})915 }916 async updateSubTaskAsync(data) {917 let { serverAddr, sessionId, user, body, paths } = data918 let fruit = getFruit()919 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))920 let taskId = paths[1]921 let nodeId = paths[3]922 let t = await new Promise((resolve, reject) => {923 fruit.updateSubTask(user, taskId, nodeId, body, (err, t) => {924 if(err) return reject(err)925 resolve(t)926 })927 })928 await this.successResponseJsonAsync(serverAddr, sessionId, t)929 }930 async deleteSubTaskAsync(data) {931 let { serverAddr, sessionId, user, body, paths } = data932 let fruit = getFruit()933 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))934 let taskId = paths[1]935 let nodeId = paths[3]936 await new Promise((resolve, reject) => {937 fruit.deleteSubTask(user, taskId, nodeId, err => {938 if(err) return reject(err)939 resolve()940 })941 })942 await this.successResponseJsonAsync(serverAddr, sessionId, t)943 }944 /********************************************************************************/945 /********************************* Boxes API **********************************/946 /********************************************************************************/947 948 async getBoxesAsync(data) {949 let { serverAddr, sessionId, user, body, paths } = data950 let fruit = getFruit()951 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))952 let docList = fruit.getAllBoxes(user)953 return await this.successResponseJsonAsync(serverAddr, sessionId, docList)954 }955 async getBoxAsync(data) {956 let { serverAddr, sessionId, user, body, paths } = data957 let fruit = getFruit()958 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))959 let boxUUID = paths[1]960 let doc = fruit.getBox(user, boxUUID)961 return await this.successResponseJsonAsync(serverAddr, sessionId, doc)962 }963 async updateBoxAsync(data) {964 let { serverAddr, sessionId, user, body, paths } = data965 let fruit = getFruit()966 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))967 let boxUUID = paths[1]968 let box = await fruit.updateBoxAsync(user, boxUUID, body)969 return await this.successResponseJsonAsync(serverAddr, sessionId, box)970 }971 async deleteBoxAsync(data) {972 let { serverAddr, sessionId, user, body, paths } = data973 let fruit = getFruit()974 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))975 let boxUUID = paths[1]976 await fruit.deleteBoxAsync(user, boxUUID)977 return await this.successResponseJsonAsync(serverAddr, sessionId, {})978 }979 async createBoxAsync(data) {980 let { serverAddr, sessionId, user, body, paths } = data981 let fruit = getFruit()982 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))983 let doc = await fruit.createBoxAsync(user, body)984 return await this.successResponseJsonAsync(serverAddr, sessionId, doc)985 }986 async getTweetsAsync(data) {987 let { serverAddr, sessionId, user, body, paths } = data988 let fruit = getFruit()989 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))990 let boxUUID = paths[1]991 let metadata = body.metadata === 'true' ? true : false992 let { first, last, count, segments } = body993 let props = { first, last, count, segments, metadata }994 let tweets = await fruit.getTweetsAsync(user, boxUUID, props)995 return await this.successResponseJsonAsync(serverAddr, sessionId, tweets)996 }997 async indriveFilesMoveAsync (user, indrive) {998 return new Promise((resolve, reject) => {999 if(!indrive || !indrive.length) return resolve([])1000 let tmpdir = getFruit().getTmpDir()1001 let filecount = indrive.length1002 let error1003 let finish = () => {1004 if(error) return1005 if(indrive.every(i => i.finish))1006 return resolve(indrive)1007 }1008 let errorHandle = (err) => {1009 if(error) return1010 error = err1011 reject(error)1012 }1013 let copyDriveFile = (filePath, tmpPath, callback) => {1014 fs.lstat(filePath, err => {1015 if(err) return callback(err)1016 //TODO: read xstat1017 fs.copyFile(filePath, tmpPath, err => {1018 if(err) return callback(err)1019 let fp = new Fingerprint(filePath)1020 fp.on('error', err => {1021 return callback(err)1022 })1023 1024 fp.on('data', fingerprint => {1025 callback(null, fingerprint)1026 })1027 })1028 })1029 }1030 indrive.forEach(l => {1031 if(error) return1032 let tmpPath = path.join(tmpdir, uuid.v4())1033 if(l.type === 'media') {1034 let files = getFruit().getFilesByFingerprint(user, l.sha256)1035 if(files.length) {1036 let mediaPath = files[0]1037 // TODO: check file xstat1038 fs.copyFile(mediaPath, tmpPath, err => {1039 if(error) return1040 if(err) return errorHandle(err)1041 l.finish = true1042 l.filepath = tmpPath1043 return finish()1044 })1045 } else return errorHandle(new Error(`media ${ l.sha256 } not found`))1046 } else if(l.type === 'file') {1047 let { filename, dirUUID, driveUUID } = l1048 if(!filename || !dirUUID || !driveUUID || !filename.length || !dirUUID.length || !driveUUID.length) 1049 return errorHandle(new Error('filename , dirUUID or driveUUID error'))1050 let dirPath1051 try {1052 dirPath = getFruit().getDriveDirPath(user, driveUUID, dirUUID)1053 } catch(e) {1054 return errorHandle(e)1055 }1056 let filePath = path.join(dirPath, filename)1057 copyDriveFile(filePath, tmpPath, (err, fingerprint) => {1058 if(error) return1059 if(err) return errorHandle(err)1060 l.sha256 = fingerprint1061 l.finish = true1062 l.filepath = tmpPath1063 return finish()1064 })1065 } else return errorHandle(new Error('list item error'))1066 })1067 })1068 }1069 async createTweetAsync(data) {1070 let { serverAddr, sessionId, user, body, paths } = data1071 let fruit = getFruit()1072 if (!fruit) return await this.errorStoreResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))1073 let { parent, type, list, indrive, comment } = body1074 let src = []1075 let boxUUID = paths[1]1076 data.subType = 'CreateTweet'1077 if (list && list.length > 1) return await this.errorStoreResponseAsync(serverAddr, sessionId, new Error('list can only one item if use pipe'))1078 if(list && list.length) {1079 let l = list[0]1080 let store = new StoreFile(this.tmp, l.size, l.sha256)1081 let filepath = await store.storeFileAsync(serverAddr, sessionId, this.stationId, this.token)1082 src.push({ sha256:l.sha256, filepath })1083 }1084 if (indrive) {1085 user = getFruit().findUserByGUID(user.global.id)1086 if(!user) return await this.errorStoreResponseAsync(serverAddr, sessionId, new Error('indrive only use for local user'))1087 let files = await this.indriveFilesMoveAsync(user, indrive)1088 files.map(f => src.push({ sha256: f.sha256, filepath:f.filepath}))1089 }1090 let props1091 if (type === 'list' ) {1092 let li = [], ins = []1093 if(list && list.length) li = list.map(i => { return { sha256: i.sha256, filename: i.filename } })1094 if(indrive) ins = indrive.map(l => { return { sha256:l.sha256, filename:l.filename }})1095 props = { parent, comment, type, list:[...li, ...ins], src }1096 }1097 let tweet = await fruit.createTweetAsync(user, boxUUID, props)1098 return await this.successStoreResponseAsync(serverAddr, sessionId, tweet)1099 }1100 async getBoxFileAsync(data) {1101 let { serverAddr, sessionId, user, body, paths } = data1102 let fruit = getFruit()1103 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))1104 let boxUUID = paths[1]1105 let blobUUID = paths[3]1106 let fPath = fruit.getBoxFilepath(user, boxUUID, blobUUID)1107 if (fPath)1108 return await this.fetchFileResponseAsync(fPath, serverAddr, sessionId)1109 else 1110 return await this.errorFetchResponseAsync(serverAddr, sessionId, new Error('file not found')) 1111 }1112 async deleteBoxTweets(data) {1113 let { serverAddr, sessionId, user, body, paths } = data1114 let fruit = getFruit()1115 if (!fruit) return await this.errorResponseAsync(serverAddr, sessionId, new Error('fruitmix not start'))1116 let boxUUID = paths[1]1117 let indexArr = body.indexArr1118 await fruit.deleteTweetsAsync(req.user, boxUUID, indexArr)1119 return await this.successResponseJsonAsync(serverAddr, sessionId, {})1120 }1121 /********************************************************************************/1122 /******************************** HTTP Utils **********************************/1123 /********************************************************************************/1124 //fetch file -- client download --> post file to cloud1125 /**1126 * 1127 * @param {*} fpath -local file path1128 * @param {*} cloudAddr 1129 * @param {*} sessionId -cloud session id1130 * @param {*} callback 1131 */1132 fetchFileResponse(fpath, cloudAddr, sessionId, callback) {1133 let finished = false1134 let url = cloudAddr + '/s/v1/stations/' + this.stationId + '/response/' + sessionId1135 let rs = fs.createReadStream(fpath)1136 let addr = cloudAddr.split(':')1137 let options = {1138 hostname: addr[0],1139 path: '/s/v1/stations/' + this.stationId + '/response/' + sessionId,1140 method: 'POST',1141 headers: {1142 'Authorization': this.token1143 }1144 }1145 let error = err => {1146 if (finished) return1147 debug('error fetch', err)1148 finished = true1149 callback(err)1150 }1151 let finish = () => {1152 if (finished) return1153 finished = true1154 debug('success fetch', fpath)1155 callback(null)1156 }1157 if (addr.length === 2) options.port = addr[1]1158 let req = http.request(options, res => {1159 res.setEncoding('utf8')1160 res.on('error', error)1161 res.on('end', finish);1162 })1163 req.on('error', error)1164 req.on('abort', error)1165 rs.pipe(req)1166 }1167 async fetchFileResponseAsync(fpath, cloudAddr, sessionId) {1168 return Promise.promisify(this.fetchFileResponse).bind(this)(fpath, cloudAddr, sessionId)1169 }1170 async errorFetchResponseAsync(cloudAddr, sessionId, err) {1171 let url = cloudAddr + '/s/v1/stations/' + this.stationId + '/response/' + sessionId + '/pipe/fetch'1172 let error = { code: 400, message: err.message }1173 let params = { error }1174 debug('pipe handle error', params)1175 await requestAsync('POST', url, { params }, { 'Authorization': this.token })1176 }1177 async errorResponseAsync(cloudAddr, sessionId, err) {1178 let url = cloudAddr + '/s/v1/stations/' + this.stationId + '/response/' + sessionId + '/json'1179 let error = { code: 400, message: err.message }1180 let params = { error } 1181 debug('pipe handle error', params)1182 await requestAsync('POST', url, { params }, { 'Authorization': this.token })1183 }1184 async errorStoreResponseAsync(cloudAddr, sessionId, err) {1185 let url = cloudAddr + '/s/v1/stations/' + this.stationId + '/response/' + sessionId + '/pipe/store'1186 let error = { code: 400, message: err.message }1187 let params = { error }1188 debug('pipe handle error', params)1189 await requestAsync('POST', url, { params }, { 'Authorization': this.token })1190 }1191 async successStoreResponseAsync(cloudAddr, sessionId, data) {1192 let url = cloudAddr + '/s/v1/stations/' + this.stationId + '/response/' + sessionId + '/pipe/store'1193 let params = { data }1194 debug(params)1195 await requestAsync('POST', url, { params }, { 'Authorization': this.token })1196 debug('request success')1197 }1198 // async successResponseFileAsync(cloudAddr, sessionId, fpath) {1199 // let url = cloudAddr + '/s/v1/stations/' + this.connect.saId + '/response/' + sessionId + '/pipe'1200 // let params = data1201 // debug(params)1202 // await this.fetchFileResponseAsync(fpath, cloudAddr, sessionId)1203 // }1204 async successResponseJsonAsync(cloudAddr, sessionId, data) {1205 let url = cloudAddr + '/s/v1/stations/' + this.stationId + '/response/' + sessionId + '/json'1206 let params = { data }1207 debug('aaaaaaa', params)1208 await requestAsync('POST', url, { params }, { 'Authorization': this.token })1209 debug('request success')1210 }1211 1212 register() {1213 this.handlers.set('GetToken', this.getTokenAsync.bind(this))1214 //drives1215 this.handlers.set('GetDrives', this.getDrivesAsync.bind(this))1216 this.handlers.set('CreateDrive', this.createDriveAsync.bind(this))1217 this.handlers.set('GetDrive', this.getDriveAsync.bind(this))1218 this.handlers.set('UpdateDrive', this.updateDriveAsync.bind(this))1219 this.handlers.set('DeleteDrive', this.deleteDriveAsync.bind(this))1220 this.handlers.set('GetDirectories', this.getDirectoriesAsync.bind(this))1221 this.handlers.set('GetDirectory', this.getDirectoryAsync.bind(this))1222 this.handlers.set('WriteDir', this.writeDirAsync.bind(this))1223 this.handlers.set('DownloadFile', this.downloadFileAsync.bind(this))1224 //users1225 this.handlers.set('GetUsers', this.getUsersAsync.bind(this))1226 this.handlers.set('CreateUser', this.createUserAsync.bind(this))1227 this.handlers.set('GetUser', this.getUserAsync.bind(this))1228 this.handlers.set('UpdateUserInfo', this.updateUserInfoAsync.bind(this))1229 this.handlers.set('UpdateUserPasswd', this.updateUserPasswdAsync.bind(this))1230 this.handlers.set('GetMediaBlackList', this.getUserMediaBlackListAsync.bind(this))1231 this.handlers.set('SetMediaBlackList', this.setUserMediaBlackListAsync.bind(this))1232 this.handlers.set('AddMediaBlackList', this.addUserMediaBlackListAsync.bind(this))1233 this.handlers.set('SubtractUserMediaBlackList', this.subtractUserMediaBlackListAsync.bind(this))1234 //media1235 this.handlers.set('GetMetadatas', this.getMetadatasAsync.bind(this))1236 this.handlers.set('GetMetadata', this.getMetadataAsync.bind(this))1237 //tickets1238 this.handlers.set('GetStationInfo', this.getStationInfoAsync.bind(this))1239 this.handlers.set('GetTickets', this.getTicketsAsync.bind(this))1240 this.handlers.set('UpdateStationInfo', this.updateStationInfoAsync.bind(this))1241 this.handlers.set('CreateTicket', this.createTicketAsync.bind(this))1242 this.handlers.set('GetTicket', this.getTicketAsync.bind(this))1243 this.handlers.set('ConfirmTicket', this.confirmTicketAsync.bind(this))1244 //download1245 this.handlers.set('getSummary', this.getSummaryAsync.bind(this))1246 this.handlers.set('ppg3', this.ppg3Async.bind(this))1247 this.handlers.set('checkVersion', this.checkVersionAsync.bind(this))1248 this.handlers.set('patchTorrent', this.patchTorrentAsync.bind(this))1249 this.handlers.set('addMagnet', this.addMagnetAsync.bind(this))1250 this.handlers.set('ppg1', this.ppg1Async.bind(this))1251 this.handlers.set('addTorrent', this.addTorrentAsync.bind(this))//addHttp 1252 this.handlers.set('addHttp', this.addHttpAsync.bind(this))1253 this.handlers.set('getTorrentSwitch', this.getTorrentSwitchAsync.bind(this))1254 this.handlers.set('patchTorrentSwitch', this.patchTorrentSwitchAsync.bind(this))1255 //boxes1256 this.handlers.set('GetBoxes', this.getBoxesAsync.bind(this))1257 this.handlers.set('CreateBox', this.createBoxAsync.bind(this))1258 this.handlers.set('GetBox', this.getBoxAsync.bind(this))1259 this.handlers.set('UpdateBox', this.updateBoxAsync.bind(this))1260 this.handlers.set('DeleteBox', this.deleteBoxAsync.bind(this))1261 this.handlers.set('GetTweets', this.getTweetsAsync.bind(this))1262 this.handlers.set('DeleteTweets', this.deleteBoxTweets.bind(this))1263 this.handlers.set('CreateTweet', this.createTweetAsync.bind(this))1264 this.handlers.set('GetBoxFile', this.getBoxFileAsync.bind(this))1265 //tasks1266 this.handlers.set('GetTasks', this.getTasksAsync.bind(this))1267 this.handlers.set('CreateTask',this.createTaskAsync.bind(this))1268 this.handlers.set('GetTask', this.getTaskAsync.bind(this))1269 this.handlers.set('DeleteTask', this.deleteTaskAsync.bind(this))1270 this.handlers.set('UpdateSubTask', this.updateSubTaskAsync.bind(this))1271 this.handlers.set('DeleteSubTask', this.deleteSubTaskAsync.bind(this))1272 }1273}...

Full Screen

Full Screen

network.js

Source:network.js Github

copy

Full Screen

1import globalEventBus from './globalEventBus.js';2/**3 * Network4 */5class Network {6 /**7 * Constructor network8 */9 constructor() {10 this.serverAddr = 'https://tabutask.ru';11 this.serverAddrWS = 'wss://tabutask.ru';12 // this.serverAddr = 'http://127.0.0.1';13 // this.serverAddrWS = 'ws://127.0.0.1';14 this.requestGet = {15 mode: 'cors',16 credentials: 'include',17 method: 'GET',18 };19 this.requestPost = {20 mode: 'cors',21 credentials: 'include',22 method: 'POST',23 headers: {24 'Content-Type': 'application/json',25 'X-CSRF-Token': '',26 },27 };28 this.requestPut = {29 mode: 'cors',30 credentials: 'include',31 method: 'PUT',32 headers: {33 'Content-Type': 'application/json',34 'X-CSRF-Token': '',35 },36 };37 this.requestDelete = {38 mode: 'cors',39 credentials: 'include',40 method: 'DELETE',41 headers: {42 'Content-Type': 'application/json',43 'X-CSRF-Token': '',44 },45 };46 this.requestFormData = {47 mode: 'cors',48 credentials: 'include',49 method: 'POST',50 headers: {51 'X-CSRF-Token': '',52 },53 };54 }55 /**56 * Send sign in request to server57 * @param {requestData} data58 * @return {Promise<Response>}59 */60 loginRequest(data) {61 const url = this.serverAddr + '/api/login/';62 this.requestPost.body = JSON.stringify(data);63 return fetch(url, this.requestPost);64 }65 /**66 * Send sign up request to server67 * @param {requestData} data68 * @return {Promise<Response>}69 */70 regRequest(data) {71 const url = this.serverAddr + '/api/reg/';72 this.requestPost.body = JSON.stringify(data);73 return fetch(url, this.requestPost);74 }75 /**76 * Send request to server to check77 * if user is authorized78 * @return {Promise<Response>}79 */80 authRequest() {81 const url = this.serverAddr + '/api/';82 return fetch(url, this.requestGet);83 }84 /**85 * get profile information from server86 * @return {Promise<Response>}87 */88 profileGet() {89 const url = this.serverAddr + '/api/profile/';90 return fetch(url, this.requestGet);91 }92 /**93 * request to change profile data on server94 * @param {requestData} data95 * @return {Promise<Response>}96 */97 profileSet(data) {98 const url = this.serverAddr + '/api/profile/';99 this.requestFormData.body = data;100 return fetch(url, this.requestFormData);101 }102 /**103 * request to change password data on server104 * @param {requestData} data105 * @return {Promise<Response>}106 */107 passwordSet(data) {108 const url = this.serverAddr + '/api/password/';109 this.requestPost.body = JSON.stringify(data);110 return fetch(url, this.requestPost);111 }112 /**113 * logout request to server114 * @return {Promise<void>}115 */116 logout() {117 const url = this.serverAddr + '/api/logout/';118 return fetch(url, this.requestGet).then((response) => {119 if (response.ok) {120 globalEventBus.emit('network:logout', null);121 }122 });123 }124 /**125 * request to create board126 * @param {requestData} data127 * @return {Promise<Response>}128 */129 boardCreate(data) {130 const url = this.serverAddr + '/api/board/';131 console.log(data);132 this.requestPost.body = JSON.stringify(data);133 return fetch(url, this.requestPost);134 }135 /**136 * request to get data for board by id137 * @param {string}boardID138 * @return {Promise<Response>}139 */140 boardGet(boardID) {141 const url = this.serverAddr + '/api/board/' + boardID + '/';142 return fetch(url, this.requestGet);143 }144 /**145 * request to change data for board146 * @param {requestData} data147 * @return {Promise<Response>}148 */149 boardSet(data) {150 const url = this.serverAddr + '/api/board/' + data.boardID + '/';151 this.requestPut.body = JSON.stringify(data);152 return fetch(url, this.requestPut);153 }154 /**155 * request to get data for board by id156 * @param {string}boardID157 * @return {Promise<Response>}158 */159 boardDelete(boardID) {160 const url = this.serverAddr + '/api/board/' + boardID + '/';161 return fetch(url, this.requestDelete);162 }163 /**164 * request to add user to board165 * @param {requestData} data166 * @return {Promise<Response>}167 */168 userAddToBoard(data) {169 const url = this.serverAddr + '/api/board/' + data.boardID + '/user-add/';170 this.requestPut.body = JSON.stringify(data);171 return fetch(url, this.requestPut);172 }173 /**174 * request to remove user from board175 * @param {requestData} data176 * @return {Promise<Response>}177 */178 userRemoveFromBoard(data) {179 const url = this.serverAddr + '/api/board/' + data.boardID + '/user-remove/';180 this.requestPut.body = JSON.stringify(data);181 return fetch(url, this.requestPut);182 }183 /**184 * request to create card185 * @param {requestData} data186 * @param {string} boardID187 * @return {Promise<Response>}188 */189 cardCreate(data, boardID) {190 const url = this.serverAddr + '/api/card/' + boardID + '/';191 this.requestPost.body = JSON.stringify(data);192 return fetch(url, this.requestPost);193 }194 /**195 * request to get data for card by id196 * @param {string}cardID197 * @return {Promise<Response>}198 */199 cardGet(cardID) {200 const url = this.serverAddr + '/api/card/' + cardID + '/';201 return fetch(url, this.requestGet);202 }203 /**204 * request to change data for card205 * @param {requestData} data206 * @return {Promise<Response>}207 */208 cardSet(data) {209 const url = this.serverAddr + '/api/card/' + data.cardID + '/';210 this.requestPut.body = JSON.stringify(data);211 return fetch(url, this.requestPut);212 }213 /**214 * request to delete card215 * @param {string}cardID216 * @return {Promise<Response>}217 */218 cardDelete(cardID) {219 const url = this.serverAddr + '/api/card/' + cardID + '/';220 return fetch(url, this.requestDelete);221 }222 /**223 * request to change cards order224 * @param {requestData} data225 * @param {string} boardID226 * @return {Promise<Response>}227 */228 cardsOrder(data, boardID) {229 const url = this.serverAddr + '/api/card-order/' + boardID + '/';230 this.requestPost.body = JSON.stringify(data);231 return fetch(url, this.requestPost);232 }233 /**234 * request to create task235 * @param {requestData} data236 * @param {string} boardID237 * @return {Promise<Response>}238 */239 taskCreate(data, boardID) {240 const url = this.serverAddr + '/api/task/' + boardID + '/';241 this.requestPost.body = JSON.stringify(data);242 return fetch(url, this.requestPost);243 }244 /**245 * request to get data for task by id246 * @param {string}taskID247 * @return {Promise<Response>}248 */249 taskGet(taskID) {250 const url = this.serverAddr + '/api/task/' + taskID + '/';251 return fetch(url, this.requestGet);252 }253 /**254 * request to change data for task255 * @param {requestData} data256 * @return {Promise<Response>}257 */258 taskSet(data) {259 const url = this.serverAddr + '/api/task/' + data.taskID + '/';260 this.requestPut.body = JSON.stringify(data);261 return fetch(url, this.requestPut);262 }263 /**264 * request to delete task265 * @param {string}taskID266 * @return {Promise<Response>}267 */268 taskDelete(taskID) {269 const url = this.serverAddr + '/api/task/' + taskID + '/';270 return fetch(url, this.requestDelete);271 }272 /**273 * request to change tasks order274 * @param {requestData} data275 * @param {string} boardID276 * @return {Promise<Response>}277 */278 tasksOrder(data, boardID) {279 const url = this.serverAddr + '/api/task-order/' + boardID + '/';280 this.requestPost.body = JSON.stringify(data);281 return fetch(url, this.requestPost);282 }283 /**284 * get boards from server285 * @return {Promise<Response>}286 */287 getBoards() {288 const url = this.serverAddr + '/api/boards/';289 return fetch(url, this.requestGet);290 }291 /**292 * request to create tag293 * @param {requestData} data294 * @param {string} boardID295 * @return {Promise<Response>}296 */297 tagCreate(data) {298 const url = this.serverAddr + '/api/tag/' + data.boardID + '/';299 this.requestPost.body = JSON.stringify(data);300 return fetch(url, this.requestPost);301 }302 /**303 * request to change data for tag304 * @param {requestData} data305 * @return {Promise<Response>}306 */307 tagSet(data) {308 const url = this.serverAddr + '/api/tag/' + data.boardID + '/';309 this.requestPut.body = JSON.stringify(data);310 return fetch(url, this.requestPut);311 }312 /**313 * request to delete tag from board314 * @param {requestData} data315 * @return {Promise<Response>}316 */317 tagDelete(data) {318 const url = this.serverAddr + '/api/tag/' + data.boardID + '/';319 this.requestDelete.body = JSON.stringify(data);320 return fetch(url, this.requestDelete);321 }322 /**323 * request to add tag to task324 * @param {requestData} data325 * @return {Promise<Response>}326 */327 tagAddToTask(data) {328 const url = this.serverAddr + '/api/task/' + data.taskID + '/tag-add/';329 this.requestPut.body = JSON.stringify(data);330 return fetch(url, this.requestPut);331 }332 /**333 * request to add tag to task334 * @param {requestData} data335 * @return {Promise<Response>}336 */337 tagRemoveFromTask(data) {338 const url = this.serverAddr + '/api/task/' + data.taskID + '/tag-remove/';339 this.requestPut.body = JSON.stringify(data);340 return fetch(url, this.requestPut);341 }342 /**343 * request to add user to task344 * @param {requestData} data345 * @return {Promise<Response>}346 */347 userAddToTask(data) {348 const url = this.serverAddr + '/api/task/' + data.taskID + '/user-add/';349 this.requestPut.body = JSON.stringify(data);350 return fetch(url, this.requestPut);351 }352 /**353 * request to remove user from task354 * @param {requestData} data355 * @return {Promise<Response>}356 */357 userRemoveFromTask(data) {358 const url = this.serverAddr + '/api/task/' + data.taskID + '/user-remove/';359 this.requestPut.body = JSON.stringify(data);360 return fetch(url, this.requestPut);361 }362 /**363 * request to create comment364 * @param {requestData} data365 * @param {string} taskID366 * @return {Promise<Response>}367 */368 commentCreate(data) {369 const url = this.serverAddr + '/api/comment/' + data.taskID + '/';370 this.requestPost.body = JSON.stringify(data);371 return fetch(url, this.requestPost);372 }373 /**374 * request to change data for comment375 * @param {requestData} data376 * @return {Promise<Response>}377 */378 commentSet(data) {379 const url = this.serverAddr + '/api/comment/' + data.commentID + '/';380 this.requestPut.body = JSON.stringify(data);381 return fetch(url, this.requestPut);382 }383 /**384 * request to delete comment from task385 * @param {requestData} data386 * @return {Promise<Response>}387 */388 commentDelete(data) {389 const url = this.serverAddr + '/api/comment/' + data.commentID + '/';390 this.requestDelete.body = JSON.stringify(data);391 return fetch(url, this.requestDelete);392 }393 /**394 * request to create checklist395 * @param {requestData} data396 * @param {string} taskID397 * @return {Promise<Response>}398 */399 checklistCreate(data) {400 const url = this.serverAddr + '/api/checklist/' + data.taskID + '/';401 this.requestPost.body = JSON.stringify(data);402 return fetch(url, this.requestPost);403 }404 /**405 * request to change data for checklist406 * @param {requestData} data407 * @return {Promise<Response>}408 */409 checklistSet(data) {410 const url = this.serverAddr + '/api/checklist/' + data.taskID + '/';411 this.requestPut.body = JSON.stringify(data);412 return fetch(url, this.requestPut);413 }414 /**415 * request to delete checklist from task416 * @param {requestData} data417 * @return {Promise<Response>}418 */419 checklistDelete(data) {420 const url = this.serverAddr + '/api/checklist/' + data.taskID + '/';421 this.requestDelete.body = JSON.stringify(data);422 return fetch(url, this.requestDelete);423 }424 /**425 * request to create attachment426 * @param {requestData} data427 * @param {string} taskID428 * @return {Promise<Response>}429 */430 attachmentCreate(data) {431 console.log(data);432 const url = this.serverAddr + '/api/attachment/' + data.get('taskID') + '/';433 this.requestFormData.body = data;434 return fetch(url, this.requestFormData);435 }436 /**437 * request to delete attachment from task438 * @param {requestData} data439 * @return {Promise<Response>}440 */441 attachmentDelete(data) {442 const url = this.serverAddr + '/api/attachment/' + data.taskID + '/';443 this.requestDelete.body = JSON.stringify(data);444 return fetch(url, this.requestDelete);445 }446 /**447 * request to stand websocket connection448 * @param {string} boardID449 * @return {WebSocket}450 */451 webSocketBoardConnection(boardID) {452 const url = this.serverAddrWS + '/api/ws/board/' + boardID + '/';453 const ws = new WebSocket(url);454 ws.onopen = function() {455 console.log('Connected webSocketBoard');456 };457 return ws;458 }459 /**460 * request to stand websocket connection461 * @return {WebSocket}462 */463 webSocketNotificationsConnection() {464 const url = this.serverAddrWS + '/api/ws/notification/';465 const ws = new WebSocket(url);466 ws.onopen = function() {467 console.log('Connected webSocketNotifications');468 };469 return ws;470 }471 /**472 * Check token error from server473 * @param {JSON} responseBody474 * @return {boolean}475 */476 ifTokenValid(responseBody) {477 if (responseBody.status === 777) {478 this.setToken(responseBody.token);479 return false;480 }481 return true;482 }483 /**484 * Set token to headers of requests485 * @param {string} token486 */487 setToken(token) {488 this.requestPost.headers['X-CSRF-Token'] = token;489 this.requestPut.headers['X-CSRF-Token'] = token;490 this.requestDelete.headers['X-CSRF-Token'] = token;491 this.requestFormData.headers['X-CSRF-Token'] = token;492 }493 /**494 * get shared url from server495 * @param {string} boardID496 * @return {Promise<Response>}497 */498 getSharedUrl(boardID) {499 const url = this.serverAddr + '/api/shared-url/' + boardID + '/';500 return fetch(url, this.requestGet);501 }502 /**503 * Accept invitation on board504 * @param {string} boardID505 * @param {string} sharedUrl506 * @return {Promise<Response>}507 */508 acceptInvitation(boardID, sharedUrl) {509 const url = this.serverAddr + '/api/invite/board/' + boardID + '/' + sharedUrl + '/';510 return fetch(url, this.requestGet);511 }512}...

Full Screen

Full Screen

util.js

Source:util.js Github

copy

Full Screen

1// Define Utilities2var Util = {3 serverAddr: window.location.origin + "/graphviewer/ViewerServlet/",4 initCenter: [0, 0],5 initZoom: function (container) {6 return Math.abs(Math.floor((Math.log(Math.min($("#" + container).width(), $("#" + container).height())) / Math.log(2))) - 8);7 },8 9 maxZoom: function (data) {10 return Math.max((Math.ceil((Math.log(data.imageDim) - Math.log(256)) / Math.log(2)) + 2), 5);11 },12 init: function () {13 var params = {};14 var tokens;15 var re = /[?&]?([^=]+)=([^&]*)/g;16 while (tokens = re.exec(location.search.split("+").join(" "))) {17 params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);18 }19 this.scheme = params['scheme'];20 this.host = params['host'];21 this.port = params['port'];22 this.authcode = params['authcode'];23 this.recordids = JSON.parse(params['guids']);24 },25 // Fetch all Record Data26 getData: function (recordid) {27 var data = {};28 data.recordid = recordid;29 data.sliceNumber = 0;30 data.frameNumber = 0;31 data.isGrayScale = 0;32 data.isZStacked = 0;33 data.channels = 1;34 data.imageWidth = 0;35 data.imageHeight= 0;36 var url_tmp = this.serverAddr + "getRecordData" +37 "?r=" + data.recordid +38 "&t=" + this.token+39 "&host=" + this.host +40 "&port=" + this.port+41 "&scheme=" + this.scheme;42 console.log(url_tmp);43 // Get the Record data44 $.ajax({45 url: this.serverAddr + "getRecordData" +46 "?r=" + data.recordid +47 "&t=" + this.token+48 "&host=" + this.host +49 "&port=" + this.port+50 "&scheme=" + this.scheme,51 async: false,52 success: function (result) {53 data.frameCount = result["Frame Count"];54 data.sliceCount = result["Slice Count"];55 data.channels = result["Channel Count"];56 }57 });58 return data;59 },60 startTilingUrl: function (data) {61 return this.serverAddr + "startTiling" +62 "?r=" + this.recordids +63 "&sn=" + data.sliceNumber +64 "&fn=" + data.frameNumber +65 "&cn=" + data.channels +66 "&gs=" + data.isGrayScale +67 "&zs=" + data.isZStacked +68 "&t=" + this.token+69 "&host=" + this.host +70 "&port=" + this.port+71 "&scheme=" + this.scheme ;72 },73 getProgressUrl: function () {74 return this.serverAddr + "getProgress" +75 "?r=" + this.recordids +76 "&t=" + this.token+77 "&host=" + this.host +78 "&port=" + this.port+79 "&scheme=" + this.scheme ;80 },81 getsaveOverlaysUrl: function () {82 return this.serverAddr + "saveOverlays" +83 "?r=" + this.recordids +84 "&t=" + this.token+85 "&host=" + this.host +86 "&port=" + this.port+87 "&scheme=" + this.scheme ;88 },89 getloadOverlaysUrl: function (name) {90 return this.serverAddr + "loadOverlays" +91 "?r=" + this.recordids +92 "&t=" + this.token+93 "&host=" + this.host +94 "&port=" + this.port+95 "&name=" + name+96 "&scheme=" + this.scheme ;97 },98 getTileUrl: function (data) {99 return this.serverAddr + "getTile" +100 "?r=" + data.recordid +101 "&sn=" + data.sliceNumber +102 "&fn=" + data.frameNumber +103 "&cn=" + data.channels +104 "&gs=" + data.isGrayScale +105 "&zs=" + data.isZStacked +106 "&iw=" +data.imageWidth+107 "&ih=" +data.imageHeight+108 "&t=" + this.token+109 "&host=" + this.host +110 "&port=" + this.port+111 "&scheme=" + this.scheme ;112 },113 getThumbnailUrl: function (recordid) {114 return this.serverAddr + "getThumbnail" +115 "?r=" + recordid +116 "&t=" + this.token+117 "&host=" + this.host +118 "&port=" + this.port+119 "&scheme=" + this.scheme;120 },121 getLoginUrl: function () {122 return this.serverAddr + "doLogin" +123 "?scheme=" + this.scheme +124 "&host=" + this.host +125 "&port=" + this.port +126 "&authcode=" + this.authcode;127 },128 129 getOverlayUrl: function (recordid) {130 return this.serverAddr + "getOverlays" +131 "?scheme=" + this.scheme +132 "&host=" + this.host +133 "&port=" + this.port +134 "&t=" + this.token +135 "&r="+recordid;136 },137 138 createOverlayUrl: function (recordid) {139 return this.serverAddr + "createOverlay" +140 "?scheme=" + this.scheme +141 "&host=" + this.host +142 "&port=" + this.port +143 "&t=" + this.token +144 "&r="+recordid;145 },146 147 deleteOverlayUrl: function (recordid) {148 return this.serverAddr + "deleteOverlay" +149 "?scheme=" + this.scheme +150 "&host=" + this.host +151 "&port=" + this.port +152 "&t=" + this.token +153 "&r="+recordid;154 },155 156 searchOverlayUrl: function (recordid) {157 return this.serverAddr + "searchOverlay" +158 "?scheme=" + this.scheme +159 "&host=" + this.host +160 "&port=" + this.port +161 "&t=" + this.token +162 "&r="+recordid;163 },164 165 saveOverlayUrl: function (recordid) {166 return this.serverAddr + "saveOverlays" +167 "?scheme=" + this.scheme +168 "&host=" + this.host +169 "&port=" + this.port +170 "&t=" + this.token +171 "&r="+recordid;172 },173 174 getVisualOverlayNamesUrl: function (recordid) {175 return this.serverAddr + "getVisualOverlayNames" +176 "?scheme=" + this.scheme +177 "&host=" + this.host +178 "&port=" + this.port +179 "&t=" + this.token +180 "&r="+recordid;181 }...

Full Screen

Full Screen

config.js

Source:config.js Github

copy

Full Screen

1/**2 * Created by soga on 16/10/11.3 */4import {Dimensions} from 'react-native';5export const WINDOW = {6 width: Dimensions.get('window').width,7 height: Dimensions.get('window').height,8};9//样式配置10export const STYLE = {11 primary:'#f464a2',12 second:'#448AFF',13 gray:'#999',14 black:'#222',15 fontSizeNormal:14,16 fontSizeSmall:12,17 fontSizeLarge:18,18 headerBannerHeight:45,//app顶部banner高19 menuBottomHeight:50,//底部菜单高20 swipHeaderHeight:50,//切换title的高度21}22//export const SERVERADDR = "http://www.newvf.com";23export const SERVERADDR = "http://www.o-front-test.com";24//export const SERVERADDR = "http://www.lgfxiu.com";25//接口配置26export const REQURL = {27 getVideoAll : { url : SERVERADDR + "/videolistall.json", type : 'GET'},//大厅全部数据28 getVideoRec : { url : SERVERADDR + "/videolistrec.json", type : 'GET'},//今日之星数据29 getVideoSls : { url : SERVERADDR + "/videolistsls.json", type : 'GET'},//大秀场数据30 getVideoOrd : { url : SERVERADDR + "/videolistord.json", type : 'GET'},//一对一数据31 getUserInfo : { url : SERVERADDR + "/indexinfo", type : 'GET'},//用户数据32 getMyRecord : { url : SERVERADDR + "/member/consumerd?type=json", type : 'GET'},//获取我的消费记录33 getMyMsg : { url : SERVERADDR + "/member/msglist?type=json", type : 'GET'},//获取我的消息记录34 getMyMount : { url : SERVERADDR + "/member/scene?type=json", type : 'GET'},//获取我的道具35 equipMount : { url : SERVERADDR + "/member/scene", type : 'GET'},//装配坐骑36 cancelMount : { url : SERVERADDR + "/member/cancelscene?type=json", type : 'GET'},//取消坐骑37 login : { url : SERVERADDR + "/login", type : 'POST'},//登录38 logout : { url : SERVERADDR + "/logout?type=json", type : 'POST'},//退出39 getShops : { url : SERVERADDR + "/shop?type=json", type : 'GET'},//获取商品信息40 register : { url : SERVERADDR + "/reg", type : 'POST'},//注册41 //getVData : { url : SERVERADDR + "/videolist.json", type : 'GET'},//获取排行榜相关数据42 getActivity : { url : SERVERADDR + "/act?type=json", type : 'GET'},//获取活动信息43 getActivityDetail : { url : SERVERADDR + "/nac/", type : 'GET'},//获取活动详细信息44 getUid : { url : SERVERADDR + "/getUid", type : 'GET'},//获取用户id45 payMount : { url : SERVERADDR + "/member/pay", type : 'POST'},//购买坐骑46 getVIPMount : { url : SERVERADDR + "/getvipmount", type : 'POST'},//领取VIP坐骑47 openVIP : { url : SERVERADDR + "/openvip", type : 'GET'},//开通vip48 reSetPassword : { url : SERVERADDR + "/member/password", type : 'POST'},//重置密码49 editUserInfo : { url : SERVERADDR + "/member/edituserinfo", type : 'POST'},//编辑个人信息50 search : { url : SERVERADDR + "/find", type : 'GET'},//编辑个人信息51 getVData : { url : "http://v.lgfxiu.com/video_gs/rank/data_ajax", type : 'GET'},//获取排行榜相关数据52 getGifts : { url : "http://v.lgfxiu.com/video_gs/conf", type : 'POST'},//获取礼物数据53 getSendGiftsLists : { url : "http://v.lgfxiu.com/video_gs/rank/list_gift", type : 'GET', model : 'jsonp'},//获取礼物清单54 socketAddr : { url : "http://v.o-front-test.com/video_gs/mobileServer", type : 'GET', model : 'jsonp'},//获取socket地址55};56//基本配置57export const CONFIG = {58 //imageServe : "http://138.68.15.251/",59 giftPath : "http://www.lgfxiu.com/flash/image/",60 imageServe : "http://138.68.15.251/"61 //imageServe : "http://p.lgfxiu.com/",62};63//socket配置64export const SOCKET = {65 host : "139.59.240.47",66 //host : "192.168.5.196",67 ports : {//一般请求:20036 聊天:20037 送礼:2003868 common : 20036,69 chat : 20037,70 gift : 2003871 },72 AES_IV : "0102030405060708",// AES密匙偏移量73 WS_SECTRITY : '35467ug$#6ighegw',//AES加密密匙,通用socket74 WSCHAT_SECTRITY : '985tj@48hgi95353',//AES加密密匙,聊天75 WSGIFT_SECTRITY : '58it^43(&#gig&*7jj'//AES加密密匙,礼物...

Full Screen

Full Screen

alarmList.js

Source:alarmList.js Github

copy

Full Screen

1/**2 * Created by caowei on 2016/07/213 */4$(function(){5 //搜索6 $(".search_btn").unbind("click");7 $(".search_btn").bind("click", function(){8 var startTime = $("#startTime").val();9 var endTime = $("#endTime").val();10 if(startTime.length != 0 && endTime == 0){11// alert("请输入结束时间!");12 layer.msg('请输入结束时间!');13 return;14 } else if(startTime.length == 0 && endTime != 0){15// alert("请输入开始时间!");16 layer.msg('请输入开始时间!');17 return;18 }19 var content = {};20 var serverAddr = $.trim($("#serverAddr").val());21// alert(serverAddr);22 if(serverAddr.length > 0){23// var ipRegex = /^([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/;24// if(ipRegex.test(serverAddr)){25// content.serverAddr=serverAddr;26// } else {27//// alert("IP地址格式有误!");28// layer.msg('IP地址格式有误!');29// return;30// }31 32 content.serverAddr=serverAddr;33 34 }35 36 var dataType = $("#dataType").val();37 var alarmLevel = $("#alarmLevel").val();38// if(serverAddr != "" && serverAddr != null){39// //如果包含%、_,则将其替换为 \%、\_ (%、_在sql中属于特殊字符)40// if(serverAddr.indexOf("%") != -1){41// serverAddr = serverAddr.replace(/%/g, "\\%");42// }else if(serverAddr.indexOf("_") != -1){43// serverAddr = serverAddr.replace(/_/g, "\\_");44// }45// content.serverAddr=serverAddr;46// }47 if(startTime.length > 0 && endTime.length > 0){48 var startDate = new Date(startTime.replace(/-/g,"/"));49 var endDate = new Date(endTime.replace(/-/g,"/"));50 if(startDate >= endDate){51// alert("截止时间必须大于开始时间");52 layer.msg('开始时间不能晚于结束时间!');53 return;54 }55 content.startTime = startTime;56 content.endTime = endTime;57 }58 content.search=true;59 $.ajax({60 url:'../db/alarm',61 type:'POST',62 dataType:'html',63 data:{64 dataType:dataType,65 alarmLevel:alarmLevel,66 content:JSON.stringify(content)67 },68 success:function(data){69 $(".list_table").empty();70 $(".list_table").append(data);71 $("#searchConditions").val(JSON.stringify(content));72 },73 error:function(){74// alert("服务器异常");75 layer.msg('服务器异常');76 }77 78 });79 });80 81 //回车搜索事件82 $("#serverAddr").bind("keydown",function(e){83 // 兼容FF和IE和Opera 84 var theEvent = e || window.event; 85 var code = theEvent.keyCode || theEvent.which || theEvent.charCode; 86 if (code == 13) { 87 //回车执行查询88 $(".search_btn").click();89 } 90 });91 92 laydate({93 elem: '#startTime',94 format: 'YYYY-MM-DD hh:mm:ss',95 //min: laydate.now(), //设定最小日期为当前日期96 //max: '2099-06-16 23:59:59', //最大日期97 istime: true,98 istoday: true,99 choose: function(date){100 //end.min = datas; //开始日选好后,重置结束日的最小日期101 //end.start = datas //将结束日的初始值设定为开始日102 //alert("startTime:" + date);103 }104 });105 106 laydate({107 elem: '#endTime',108 format: 'YYYY-MM-DD hh:mm:ss',109 //min: laydate.now(), //设定最小日期为当前日期110 //max: '2099-06-16 23:59:59', //最大日期111 istime: true,112 istoday: true,113 choose: function(date){114 //end.min = datas; //开始日选好后,重置结束日的最小日期115 //end.start = datas //将结束日的初始值设定为开始日116 //alert("endTime:" + date);117 }118 });119 ...

Full Screen

Full Screen

homeScreenCtrl.js

Source:homeScreenCtrl.js Github

copy

Full Screen

1mainApp.controller("homeScreenCtrl", function(SERVER_INFO, $scope, $http, $rootScope, $uibModal) {2 //console.log("homeScreenCtrl");3 serverAddr = "http://"+SERVER_INFO.IP+":"+SERVER_INFO.PORT;4 $rootScope.navIndex = 1;5 var currentItemsPage = 0;6 $scope.items = [];7 $http.get(serverAddr+ '/users/my')8 .success(function(data) {9 // console.log(JSON.stringify(data));10 $rootScope.user = data;11 if(data.photo_id != undefined) {12 $rootScope.user.photo_user = serverAddr+"/assets/imgs/profiles/"+$rootScope.user.photo_id;13 }14 })15 .error(function(data) {16 console.log('Error: ' + data);17 window.location.href = serverAddr+"/access";18 });19 $scope.logout = function() {20 console.log("Logout");21 window.location.href = serverAddr+"/access";22 };23 $scope.getItems = function() {24 $http.get(serverAddr+'/items', {25 params: {page: currentItemsPage}26 })27 .success(function(data) {28 // console.log(JSON.stringify(data));29 $scope.items = $scope.items.concat(data);30 })31 .error(function(err) {32 console.log('Error: ' + err);33 });34 };35 $scope.getAllItems = function() {36 $http.get(serverAddr+'/items/')37 .success(function(data) {38 $scope.items = data;39 })40 .error(function(data) {41 console.log('Error: ' + data);42 });43 };44 $scope.loadMore = function() {45 currentItemsPage++;46 $scope.getItems();47 };48 $rootScope.openSuccessModal = function() {49 var modalInstance = $uibModal.open({50 templateUrl: '/views/modals/successModal.html',51 controller: function($scope, $uibModalInstance) {52 $scope.close = function()53 {54 $uibModalInstance.dismiss();55 }56 }57 });58 modalInstance.result.then(59 function () {60 console.log("Modal dismiss - Si");61 }, function () {62 console.log("Modal cerrado - No");63 });64 };65 $rootScope.openErrorModal = function() {66 var modalInstance = $uibModal.open({67 templateUrl: '/views/modals/errorModal.html',68 controller: function($scope, $uibModalInstance) {69 $scope.close = function()70 {71 $uibModalInstance.dismiss();72 }73 }74 });75 modalInstance.result.then(76 function () {77 console.log("Modal dismiss - Si");78 }, function () {79 console.log("Modal cerrado - No");80 });81 };82 $rootScope.openItemSuccessModal = function() {83 var modalInstance = $uibModal.open({84 templateUrl: '/views/modals/successModal.html',85 controller: function($scope, $uibModalInstance) {86 $scope.close = function()87 {88 $uibModalInstance.dismiss();89 window.location = serverAddr;90 }91 }92 });93 modalInstance.result.then(94 function () {95 console.log("Modal dismiss - Si");96 window.location = serverAddr;97 }, function () {98 console.log("Modal cerrado - No");99 window.location = serverAddr;100 });101 };...

Full Screen

Full Screen

adminUserController.js

Source:adminUserController.js Github

copy

Full Screen

1adminApp.controller("adminUserController", function(SERVER_INFO, $scope, $http, $location, $routeParams, $uibModal) {2 3 var serverAddr = "http://"+SERVER_INFO.IP+":"+SERVER_INFO.PORT;4 console.log("Server: "+serverAddr);5 6 $http.get(serverAddr+ '/users')7 .success(function(data) {8 $scope.users = data;9 console.log('No Llego: ' + data);10 })11 .error(function(data) {12 console.log('Error: ' + data);13 });14 $http.get(serverAddr+ '/users/order')15 .success(function(data) {16 $scope.users = data;17 console.log('Llego: ' + data);18 })19 .error(function(data) {20 console.log('Error: ' + data);21 });22 23 $scope.createUser = function(user){24 $http.post(serverAddr+ '/users', user)25 .success(function(data) {26 $scope.users.push(user);27 user = {}; 28 console.log("Usuario creado correctamente");29 $location.path( "/" ); 30 })31 .error(function(data) {32 console.log("Error al añadir usuario");33 });34 };35 36 $scope.deleteUser = function(id) {37 $http.delete(serverAddr+ '/users/'+ id)38 .success(function(data) {39 $scope.users = data;40 console.log("Entrada borrada");41 })42 .error(function(data) {43 console.log('Error:' + data);44 });45 };46 $scope.changeUser = function(user){ 47 48 $http.put(serverAddr+ '/users/'+ user._id, user)49 .success(function(data) {50 user = {}; 51 $location.path("/"); 52 })53 .error(function(data) {54 });55 };56 $scope.getUser = function() {57 console.log("GET USER");58 console.log("USER: ", $routeParams.id);59 60 $http.get(serverAddr+ '/users/'+$routeParams.id)61 .success(function(data) {62 $scope.user = data;63 console.log("get user ok ", $scope.user);64 })65 .error(function(data) {66 console.log('Error: ' + data);67 });68 69 };70 $scope.openConfirmDeleteUserModal = function(id) {71 var modalInstance = $uibModal.open({72 templateUrl: '/views/modals/adminConfirmDeleteUser.html',73 controller: function($scope, $uibModalInstance) {74 75 $scope.close = function()76 {77 $uibModalInstance.dismiss();78 }79 $scope.confirm = function()80 { 81 $uibModalInstance.close();82 }83 }84 });85 modalInstance.result.then(86 function () {87 console.log("Modal dismiss - Si");88 $scope.deleteUser(id);89 }, function () {90 console.log("Modal cerrado - No");91 });92 }; 93 ...

Full Screen

Full Screen

NetManager.js

Source:NetManager.js Github

copy

Full Screen

1//服务器接口地址2//var serverAddr = 'http://121.41.101.14:8080/gamedata.py';//正式线上3// var serverAddr = 'http://121.41.101.14:8090/gamedata.py';//正式线上4// var serverAddr = 'http://122.0.71.122:8080/archer/gamedata.py';5var serverAddr = 'http://121.41.101.14:8080/gamedata.py'; //测试服 6// var serverAddr = 'http://121.40.16.212:8080/gamedata.py'; //开发服7//var serverAddr = 'http://service.xcsdedu.com/gamedata.py'; //线上服 8// var Localserver = 'http://123.57.172.138/static/archer';//客户端地址9var Localserver = 'http://192.168.1.121:8090/Sites';10var Localserver = 'http://127.0.0.1/~yiliu/'; 11var serverSDK = 'http://m.888.qq.com/m_qq/active/lg.gameHall.nocache.html?mobile=1&mdebug=1&gameId=woshijianshou&callBackUrl='+Localserver;12//具体方法实现方法13var NetManager = {14 /**15 * 通用获取数据方法getMessage16 * @param successCallBack 成功后回调函数17 * @param errorCallBack 失败后回调函数(默认不填) 18 */19 getMessage: function(data,successCallBack,isSync, isHide) {20 var http = new Http();21 http.getJSON(serverAddr, data, successCallBack, null,isSync, isHide); 22 },...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { serverAddr } = require('playwright/lib/server/server');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();10const { serverAddr } = require('playwright/lib/server/server');11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.screenshot({ path: 'example.png' });17 await browser.close();18})();19const { serverAddr } = require('playwright/lib/server/server');20const { chromium } = require('playwright');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await page.screenshot({ path: 'example.png' });26 await browser.close();27})();28- [serverAddr](#serveraddr)29 - [Parameters](#parameters)30 - [Examples](#examples)31- [serverPort](#serverport)32 - [Parameters](#parameters-1)33 - [Examples](#examples-1)34const { serverAddr } = require('playwright/lib/server/server');35const { chromium } = require('playwright');36(async () => {37 const browser = await chromium.launch();38 const context = await browser.newContext();39 const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2const { serverAddr } = require('playwright/lib/server/server');3(async () => {4 const browser = await playwright.chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const server = await serverAddr();8 console.log(server);9 await browser.close();10})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2const { serverAddr } = playwright.internal;3(async () => {4 const browser = await playwright.chromium.launch();5 const page = await browser.newPage();6 await page.goto(serverAddr('/'));7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();10const playwright = require('playwright');11const { serverAddr } = playwright.internal;12(async () => {13 const browser = await playwright.chromium.launch();14 const page = await browser.newPage();15 await page.goto(serverAddr('/'));16 await page.screenshot({ path: 'example.png' });17 await browser.close();18})();19- [Playwright Internal API](#playwright-internal-api)20 - [serverAddr](#serveraddr)21 - [serverPort](#serverport)22 - [registerFixture](#registerfixture)23 - [registerWorkerFixture](#registerworkerfixture)24 - [registerWorkerFixture](#registerworkerfixture-1)25 - [registerFixture](#registerfixture-1)26 - [registerFixture](#registerfixture-2)27 - [registerFixture](#registerfixture-3)28 - [registerFixture](#registerfixture-4)29 - [registerFixture](#registerfixture-5)30 - [registerFixture](#registerfixture-6)31 - [registerFixture](#registerfixture-7)32 - [registerFixture](#registerfixture-8)33 - [registerFixture](#registerfixture-9)34 - [registerFixture](#registerfixture-10)35 - [registerFixture](#registerfixture-11)36 - [registerFixture](#registerfixture-12)37 - [registerFixture](#registerfixture-13)38 - [registerFixture](#registerfixture-14)39 - [registerFixture](#registerfixture-15)40 - [registerFixture](#registerfixture-16)41 - [registerFixture](#registerfixture-17)42 - [registerFixture](#registerfixture-18)43 - [registerFixture](#registerfixture-19)44 - [registerFixture](#registerfixture-20)45 - [registerFixture](#registerfixture-21)46 - [registerFixture](#registerfixture-

Full Screen

Using AI Code Generation

copy

Full Screen

1const { serverAddr } = require('@playwright/test/lib/server/registry');2module.exports = {3 use: {4 server: async ({ }, use) => {5 await use(await serverAddr());6 },7 },8};

Full Screen

Using AI Code Generation

copy

Full Screen

1const { serverAddr } = require('playwright/lib/utils/utils');2const port = serverAddr().split(':').pop();3const server = require('http').createServer((req, res) => {4 res.writeHead(200, { 'Content-Type': 'text/plain' });5 res.end('Hello World');6});7server.listen(port, () => {8});9afterAll(async () => {10 await server.close();11});12const port = serverAddr().split(':').pop();13const server = require('http').createServer((req, res) => {14 res.writeHead(200, { 'Content-Type': 'text/plain' });15 res.end('Hello World');16});17server.listen(port, () => {18});19afterAll(async () => {20 await server.close();21});22const port = serverAddr().split(':').pop();23const server = require('http').createServer((req, res) => {24 res.writeHead(200, { 'Content-Type': 'text/plain' });25 res.end('Hello World');26});27server.listen(port, () => {28});29afterAll(async () => {

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal 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